Compare commits

..

293 Commits

Author SHA1 Message Date
genofire aa8b9f338f fix usage directTLS of manuelle enter an address 2021-12-11 16:42:31 +01:00
genofire 658c1c58d5 Merge remote-tracking branch 'upstream/master' into develop 2021-11-25 21:20:44 +01:00
genofire 39792f0815 fix Language merge 2021-11-20 22:37:21 +01:00
Daniel Gultsch db834a1f07 indicate call reconnect in notification 2021-11-19 12:26:11 +01:00
Daniel Gultsch f8a94161db don't play tone going from connect->reconnect->connect 2021-11-19 12:25:27 +01:00
Daniel Gultsch 5d526a77e3 include uncertainty into shared geo uri 2021-11-18 11:24:10 +01:00
Daniel Gultsch a508a81553 externalize rtc config generation into seperate method 2021-11-17 11:33:15 +01:00
Daniel Gultsch 61fb38cd84 clean up some error handling error ICE restarts 2021-11-17 10:49:16 +01:00
Daniel Gultsch 1bf2d5dd8f video calls: leave full screen mode during reconnect 2021-11-16 22:01:48 +01:00
Daniel Gultsch 0a18c8613f assume credentials are the same for all contents when restarting ICE 2021-11-16 17:08:34 +01:00
Daniel Gultsch abb671616c synchronize setDescription calls 2021-11-16 15:17:12 +01:00
Daniel Gultsch 297a843b9c use implicit rollback (needed to be enabled on libwebrtc) 2021-11-16 13:17:10 +01:00
Daniel Gultsch 0698fa0d8c store peer dtls setup for later use in ice restart 2021-11-16 11:21:11 +01:00
Daniel Gultsch 70b5d8d81a set proper peer dtls setup on ice restart received 2021-11-15 21:49:31 +01:00
Daniel Gultsch 0a3947b8e3 terminate with application failure when failing to apply ICE restart
This is fairly unlikely to happen in practice
2021-11-15 17:18:45 +01:00
Daniel Gultsch 3f402b132b respond with tie-break to prevent ICE restart race 2021-11-15 13:03:04 +01:00
Daniel Gultsch 5b80c62a63 treat transport-info w/o candidates and changed credentials as offer 2021-11-14 18:22:18 +01:00
Daniel Gultsch 717c83753f delay discovered ice candidates until JingleRtpConnection is ready to receive
otherwise setLocalDescription and the arrival of first candidates might race
the rtpContentDescription being set
2021-11-11 21:02:17 +01:00
Daniel Gultsch b6dee6da6a reverse: webrtc: include oldState in onConnectionChange
turns out we don’t need it and a better way is for RtpConnection to keep track of *all*
states in the current generation
2021-11-11 17:05:36 +01:00
Daniel Gultsch 9c3f55bef2 use stopwatch to keep track of jingle rtp session duration 2021-11-11 16:52:18 +01:00
Daniel Gultsch 9843b72f6f always use Camera2Enumerator 2021-11-11 15:23:45 +01:00
Daniel Gultsch 61851e5f84 do not automacially hang up failed webrtc sessions 2021-11-11 14:40:15 +01:00
Daniel Gultsch 4ec0996dff webrtc: include oldState in onConnectionChange 2021-11-11 11:19:37 +01:00
genofire fa1363cea0 Merge tag '2.10.2' into develop 2021-11-11 00:28:16 +01:00
Daniel Gultsch fda45a7c86 use implicit descriptions for WebRTC
using the parameter-free form of setLocalDescription() solves some potential race conditions
that can occur - especially once we introduce restartIce()
2021-11-10 16:40:24 +01:00
Daniel Gultsch b5786787f0 bump libphone number library 2021-11-09 14:27:26 +01:00
Daniel Gultsch d4cbf2e11e take intent type into account when sharing with conversations 2021-11-07 11:35:00 +01:00
Daniel Gultsch 7d7e158fd7 code clean up for LocationProvider 2021-11-03 16:00:26 +01:00
Daniel Gultsch a8ff88398d version bump to 2.10.2 + changelog 2021-11-03 15:59:05 +01:00
Daniel Gultsch bae9fc45c2 make rtcpMux optional 2021-10-31 10:20:58 +01:00
Daniel Gultsch ba4a47204b fixed IndexOutOfBounds when rendering quotes 2021-10-31 10:20:34 +01:00
Daniel Gultsch 226eb739bd make custom 'xmpp' protocol in address book case insensitve
fixes #4215
2021-10-31 08:35:44 +01:00
Daniel Gultsch 869a135bab bump okhttp 2021-10-20 10:19:59 +02:00
Daniel Gultsch 7ddd60d314 bump jxmpp. fix crash in magic create when entering @ 2021-10-20 10:19:46 +02:00
Daniel Gultsch 2ca00265db bump speed dial version to something that uses AndroidX 2021-10-20 09:52:10 +02:00
Daniel Gultsch e0c4964cc2 bump gradle plugin version 2021-10-14 17:32:07 +02:00
Daniel Gultsch 3706981645 fix mime type detection in urls that have query params or an anchor 2021-10-14 17:30:55 +02:00
genofire a124b3df9a metadata: add changelog 2.10.1 2021-10-13 18:19:29 +02:00
genofire 5a7bae592d Merge tag '2.10.1' into develop 2021-10-13 18:14:50 +02:00
Daniel Gultsch 6d2e406ee5 attempt to parse Link header from https url scanned from welcome screen 2021-10-07 09:48:49 +02:00
Daniel Gultsch cc489ef7bf bump version code 2021-10-06 12:33:36 +02:00
Daniel Gultsch 495537d087 minor code cleanup in UriHandlerActivity 2021-10-06 12:18:58 +02:00
Daniel Gultsch 20e4d108d4 fixed regression of not handling jingle content map parsing failures 2021-10-05 15:43:05 +02:00
Daniel Gultsch d0af5a002e leave code comment about xmpp vs jabber vcard entry 2021-10-04 15:18:37 +02:00
Daniel Gultsch 86de21f6a8 allow encrypted backups. fixes #4190 2021-10-04 14:17:01 +02:00
Daniel Gultsch e664a27cd0 fix typo in action matcher 2021-10-03 18:51:18 +02:00
Daniel Gultsch 4a6df90f0c attempt to read both jabber and xmpp IM fields from address book 2021-10-03 17:26:24 +02:00
Daniel Gultsch fdaab1c27e remove unused import in favor of fqn 2021-10-03 17:01:51 +02:00
Daniel Gultsch f8c59a7b75 support imto://xmpp intents 2021-10-03 17:01:32 +02:00
Daniel Gultsch f182fe6697 use PM on direct reply if last message in notifacation stack is PM 2021-10-03 16:38:30 +02:00
Daniel Gultsch daf1bbfca5 bump version code 2021-10-02 19:49:18 +02:00
Daniel Gultsch b8eec6ae5b pulled translations from transifex 2021-10-02 16:59:39 +02:00
Daniel Gultsch 3ede2d00bd remove logging 2021-10-02 16:54:19 +02:00
Daniel Gultsch d2a387e82f correctly calculate socks destination 2021-10-02 16:44:36 +02:00
Daniel Gultsch da14f83a42 ensure all bytes are read in socks handshake. fixes #4188 2021-10-02 14:24:36 +02:00
Daniel Gultsch 586fff5485 Quicksy: theme choose country activity 2021-09-29 10:51:25 +02:00
Daniel Gultsch ea9b73c1fe Quicksy: fix drawables not being styled in enter phone number screen 2021-09-29 10:42:26 +02:00
Daniel Gultsch e791e19265 ignore non letters when parsing action from xmpp uri 2021-09-27 11:15:56 +02:00
Daniel Gultsch 3de8147b41 pulled translations from transifex 2021-09-27 10:48:04 +02:00
Daniel Gultsch b9ceb67104 version bump to 2.10.1 + changelog 2021-09-24 09:25:27 +02:00
Daniel Gultsch 90a0d36362 fix not recognizing message as download. fixes #4178 2021-09-24 09:15:21 +02:00
Daniel Gultsch bd4d939a29 backport requireActivity method 2021-09-21 11:55:37 +02:00
Daniel Gultsch 64a6edd3fb Revert "Migrate Fragments to AndroidX"
This reverts commit 231d97ea81.

Migrating to AndroidX Fragments seems to have some unforseen side effects
and no clear benefits
2021-09-21 11:41:35 +02:00
Daniel Gultsch 75c20a7a2b handle on-device contacts with unstable system uri
on device contacts (contacts not synced) have an unstable system uri.
For quicksy.im contacts we can identify the contact based on the phone number
instead.

fixes #4174
2021-09-21 10:20:23 +02:00
Daniel Gultsch d5994a8d65 add to address book should add phone number for Quicksy+quicksy.im
fixes #4165
2021-09-21 10:19:09 +02:00
Daniel Gultsch 572b9c2dc6 pulled translations from transifex 2021-09-20 11:29:35 +02:00
Daniel Gultsch f9f994c540 Intent.EXTRA_ALLOW_MULTIPLE is now supported by minSdk 2021-09-20 10:08:11 +02:00
Daniel Gultsch ba9596b37d catch rare exception around execute pending fragment transactions 2021-09-20 10:07:38 +02:00
Daniel Gultsch b01bca74fd fix some linter warnings 2021-09-20 09:54:42 +02:00
Daniel Gultsch bfc8668803 bump appcompat version 2021-09-20 09:27:40 +02:00
Alexei Sorokin 951d84f404 make sure messages_index is always cleaned up fully. fixes #4170 2021-09-20 06:26:35 +00:00
Ashique Bava 231d97ea81
Migrate Fragments to AndroidX 2021-09-20 06:22:55 +00:00
Daniel Gultsch 73000962fe bump transcoder version
fixes #4167
2021-09-15 21:54:03 +02:00
Daniel Gultsch 3075833ab3 swap out transcoder library
the transcoder library we used hasn’t been updated in years

this commit switches to a maintained fork https://natario1.github.io/Transcoder/
2021-09-15 11:38:06 +02:00
Geno eba5dd8654 metadata: add changelog 2.10.0 2021-09-13 00:04:35 +02:00
Geno abe3718353 Merge tag '2.10.0' into develop 2021-09-13 00:02:16 +02:00
Daniel Gultsch 3f315751a1 version bump to 2.10.0 2021-09-11 10:28:34 +02:00
Daniel Gultsch 68d8e2b9cf delete targe file after unsuccessful image compression 2021-09-11 09:55:44 +02:00
Daniel Gultsch c195e8b3d2 run file observer on its own thread. fixes #4164 2021-09-10 19:07:57 +02:00
Daniel Gultsch 25f137441b catch security exception when viewing file from media preview 2021-09-10 18:46:37 +02:00
Daniel Gultsch d436c5f856 catch exception when trying to read display name. fixes #4163 2021-09-10 18:46:10 +02:00
Daniel Gultsch 8d9c51d755 pulled translations from transifex 2021-09-10 10:25:31 +02:00
Daniel Gultsch 2957bccb33 Revert "Fixing trailing characters treated as part of URI error (#3938)."
This reverts commit 8d45cc5827.
2021-09-08 21:30:21 +02:00
Daniel Gultsch 3135550b83 pulled translations from transifex 2021-09-08 20:53:11 +02:00
Millesimus 4d36231fa5 >.< should be quoteable (bugfix). 2021-09-08 16:29:01 +00:00
Millesimus dfeeaff74c >.< should not be rendered as quote (bugfix). 2021-09-08 16:29:01 +00:00
Daniel Gultsch 5a9777f7f1 version bump to 2.10.0-beta.2 + changelog 2021-09-08 11:13:22 +02:00
Daniel Gultsch 63f5f8c89d modify TODOs in JingleRtpConnection upon better understanding of the WebRTC stack 2021-09-08 10:47:34 +02:00
Millesimus ca08c27eef Parse IPv6 URIs (#3841). 2021-09-07 15:14:09 +00:00
Millesimus 4040d5f647 Treat dollar signs as URI chars (fixing #3859). 2021-09-07 15:14:09 +00:00
Millesimus 8d45cc5827 Fixing trailing characters treated as part of URI error (#3938). 2021-09-07 15:14:09 +00:00
Daniel Gultsch 96f0a09a5d pulled translations from transifex 2021-09-07 16:56:24 +02:00
Maximilian Weiler 38a77dbba6 Fix ImportBackupActivity not covered by screenshot prevention feature 2021-09-07 14:50:50 +00:00
Daniel Gultsch 8b817b3bd8 add database migration for new fts scheme 2021-09-07 16:47:40 +02:00
Alexei Sorokin 754773be55 match messages from the full-text index by rowid
"uuid" is a primary key in "messages" but not in "messages_index",
the implication of that is very slow matching by UUID.

What can be done instead is matching messages_index.rowid to messages.rowid,
that is, an always-present clustered index.

This not only improves performance of full-text search but also of just
updating messages in any shape or form.
2021-09-07 16:19:49 +02:00
Alexei Sorokin 4f362aafac make the fulltext index for search more space-efficient
It now uses the data from the messages table instead of having a copy of each
message.

The message UUIDs are no longer part of the index.
2021-09-07 16:19:40 +02:00
Daniel Gultsch ea0dc558cb use androidx ExifInterface to parse rotation. fixes #4154 2021-09-05 16:29:24 +02:00
Daniel Gultsch 80d8b6dd88
Upload APKs after CI 2021-08-27 07:47:55 +00:00
Daniel Gultsch 2819545a43 click on action bar title should open chat details screen 2021-08-25 20:04:47 +02:00
Daniel Gultsch 9526456d75 pulled translations from transifex 2021-08-25 18:57:20 +02:00
Daniel Gultsch f975b5ddac executePendingTransactions before trying to access secondary_fragment
If we don’t executePendingTransactions we might still access the overview fragment
while a replacement operation is in the works. This will lead to two
conversationfragments opening.
2021-08-25 18:54:03 +02:00
Daniel Gultsch 581eb511b9 version bump to 2.10.0-beta 2021-08-24 18:48:50 +02:00
Daniel Gultsch af42e34654 Revert "Always show Quote as last action"
This reverts commit e528b9f5df.

I was originally convinced by the argumentation (quote always in same place)
but testing this out for a while really seems to break 'last correct' for me.

I use that way more frequently that quote
2021-08-24 16:53:23 +02:00
Daniel Gultsch 0495470ca8 pulled translations from transifex 2021-08-24 15:32:10 +02:00
Daniel Gultsch 6c88a4b4fa reset affiliation when inviting someone not currently in group. fixes #4146 2021-08-24 14:42:50 +02:00
Daniel Gultsch 88d7ddf124 PIP aspect ratio should match video aspect ratio. fixes #4077 2021-08-24 14:40:12 +02:00
Daniel Gultsch e6d8bee035 stop agp7 complaining about missing proguard rules 2021-08-24 13:33:19 +02:00
Daniel Gultsch 208c9d91db dexOptions is no longer used in agp7 2021-08-24 13:02:31 +02:00
Licaon_Kter bf3c1d573b Avoid description repetition screenshots 2021-08-24 11:00:43 +00:00
Daniel Gultsch 4e90c0dbbb
Update android.yml to download webrtc 2021-08-24 09:21:17 +00:00
Daniel Gultsch caefec2fbf
Create android.yml 2021-08-24 09:19:08 +00:00
Daniel Gultsch 339ee8f6ea bump libwebrtc version to m92 2021-08-24 11:15:50 +02:00
Daniel Gultsch b00b8996d5 bump gradle version and agp 2021-08-24 10:13:03 +02:00
Maximilian Weiler 06fbb06aee Remove unused import 2021-08-24 07:15:30 +00:00
Maximilian Weiler ef8f10cc13 Optionally prevent taking screenshots
- Add setting to prevent screenshots
- Enforce using FLAG_SECURE in onResume for each activity
2021-08-24 07:15:30 +00:00
Millesimus b6fe1898e7 Minor duplication fix. 2021-08-24 07:14:34 +00:00
Millesimus 955a6f3fe1 Bugfix for 6cc06bcb98acc05c7677c642adf8ded90ffc8372. 2021-08-24 07:14:34 +00:00
Millesimus a0529a4e1e On quoting, translate French quotes to XEP-0393 quotes. 2021-08-24 07:14:34 +00:00
Millesimus 2db2ca95ce Move differentiation between XEP-0393 quotes and French quotes to QuoteHelper. 2021-08-24 07:14:34 +00:00
Millesimus a0bca08997 Rewrite QuoteHelper to integrate French quotes logics. Also reallow QuoteChars not followed by whitespace as indicated in XEP-0393. 2021-08-24 07:14:34 +00:00
Millesimus 748443cd4e Fixing message preview. 2021-08-24 07:14:34 +00:00
Millesimus 3921f3a940 QUOTING_MAX_DEPTH=1 for transitory compatibility with older versions. QUOTE_MAX_DEPTH=7 for performance testing and hiding of a rerendering bug occuring when two adjacent messages are merged. 2021-08-24 07:14:34 +00:00
Millesimus c81c8a62b3 Small refactoring for a more intuitive config. 2021-08-24 07:14:34 +00:00
Millesimus e850900b40 Quoting quotes, limited by nesting depth. 2021-08-24 07:14:34 +00:00
Millesimus 74d60d0131 Implement nested quotes through iteration. 2021-08-24 07:14:34 +00:00
Millesimus 65a72827bc New helper to help with quotes. 2021-08-24 07:14:34 +00:00
Millesimus 309082a9b3 Fixing xmpp:uri bug in channel details. #4139 2021-08-12 08:28:43 +00:00
Licaon_Kter e528b9f5df Always show Quote as last action 2021-08-12 08:28:36 +00:00
Daniel Gultsch 1e1dad780b add .opus file extension to mime table 2021-07-28 16:57:57 +02:00
Daniel Gultsch 0e54cde4bf add omemo media sharing to doap file 2021-07-23 08:04:36 +02:00
Alexei Sorokin b99f9d4f1c make search case-insensitive not only for ASCII 2021-05-26 06:16:20 +00:00
Daniel Gultsch 7466d12505 ring during device discovery 2021-05-22 19:37:20 +02:00
Daniel Gultsch 98ffadd87d log exception when file is not a ceb 2021-05-18 10:11:35 +02:00
Daniel Gultsch af33a57bf2 add description for text/plain 2021-05-17 16:00:00 +02:00
Daniel Gultsch 87f99d3570 Transferables interface needs to differentiate between 0 and null file size 2021-05-17 15:51:21 +02:00
Daniel Gultsch b025265f91 execute status code check on HEAD 2021-05-16 16:17:06 +02:00
Daniel Gultsch 0f3181555a FileParams indicate unavailable file size as null
since 0 is a valid file size we should use null to indicate absence
2021-05-16 15:32:57 +02:00
Daniel Gultsch 76fb0180d6 bump gradle plugin version 2021-05-16 15:29:45 +02:00
Daniel Gultsch e02aaed7d2 call SVGs 'vector graphic' instead of 'image' 2021-05-14 08:37:42 +02:00
Daniel Gultsch c9f1bdc551 fixup: update some libraries 2021-05-13 11:05:26 +02:00
Daniel Gultsch 2b9862adea update some libraries 2021-05-13 10:27:05 +02:00
Daniel Gultsch d91cd3e9e8 bump jxmpp-jid version 2021-05-13 09:19:16 +02:00
Geno e21d49efc8 Merge tag '2.9.13' into develop 2021-05-10 12:38:11 +02:00
Daniel Gultsch 56535e07ff show black bars in video call when video orientation doesn’t match screen orientation
fixes #4056
2021-05-10 09:24:20 +02:00
Dheeraj Chintaluri 60c5906fe9 Update libwebrtc version 2021-05-10 07:20:53 +00:00
Daniel Gultsch 67e5f839f1 ignore crypto callbacks when rtp session has already been terminated 2021-05-08 11:50:18 +02:00
Daniel Gultsch 89012b0f8b synchronize startRinging() to not create multiple vibrate futures 2021-05-08 11:49:24 +02:00
Daniel Gultsch 7476dccc0e do not fetch keys before making call 2021-05-08 11:21:33 +02:00
Daniel Gultsch 9182a300c5 report fingerprint missmatch as securiy exception 2021-05-08 10:35:07 +02:00
Daniel Gultsch faa4c87b5f build omemo session when encountering unknown on RTP proceed 2021-05-08 09:25:51 +02:00
Daniel Gultsch 8d391753d7 encrypt rtp map as future 2021-05-08 08:45:31 +02:00
Daniel Gultsch 337aa4a110 consider Config.REQUIRE_RTP_VERIFICATION on decrypt. fail as future 2021-05-07 22:55:20 +02:00
Daniel Gultsch ddf597e0d3 invoke x509 verification upon receiving prekey message in rtp session 2021-05-06 18:40:35 +02:00
Daniel Gultsch 9c16af25fb bump gradle version 2021-05-06 17:57:06 +02:00
Daniel Gultsch e2324209ed make sure omemo sessions are verified if the the respective config flag is set 2021-05-04 19:04:01 +02:00
Daniel Gultsch 9544b994dc invoke omemo trust/fetch activity when triggering phone call in require_verification mode 2021-05-04 17:52:17 +02:00
Daniel Gultsch 3b25fb9038 encrypt to inactive and untrusted devices in jingle
encrypting to untrusted devices means no degradition of security
compared to not encrypting at all. Trust status display (shield) is made
independently at a later stage.
2021-05-04 10:49:45 +02:00
Daniel Gultsch 48156dd27f a/v calls: seperate out SECURITY error from APP_FAILURE
until now problems with verifying the call (omemo or DTLS missing) would
just be another app failure. This commit displays verifications problems as
their own thing.
2021-05-04 10:10:34 +02:00
Daniel Gultsch 905489e237 bump firebase-messaging libray version 2021-05-04 09:47:09 +02:00
Daniel Gultsch a5ad2b7fc6 version bump to 2.9.13 + changelog 2021-05-03 16:21:10 +02:00
Daniel Gultsch 5d3ad6e36b pulled translations from transifex 2021-05-03 13:14:09 +02:00
Daniel Gultsch 6d91551f59 use onAddTrack instead of deprecated onAddStream 2021-05-03 13:06:42 +02:00
Daniel Gultsch 0717f9ba18 upgrade libwebrtc to m90 and enable extmap-allow-mixed 2021-05-03 09:48:46 +02:00
Daniel Gultsch ac7855a332 show domains in manual cert accept dialog 2021-05-03 08:28:03 +02:00
Daniel Gultsch a40b82b85b version bump to 2.9.12 + changelog 2021-05-02 08:23:00 +02:00
Daniel Gultsch c5e90199c3 trigger registration dialog on roster;ibr=y only if no accounts are configured
fixes #4065
2021-04-30 11:32:42 +02:00
Daniel Gultsch 53908dd56e pulled translations from transifex 2021-04-30 11:00:03 +02:00
Daniel Gultsch 9d9514a091 Add User-Agent to all HTTP calls 2021-04-30 10:54:36 +02:00
Daniel Gultsch bc58fb0fbd Always verify hostname/domain
There might be corner cases where it is required to use self signed
certificates. However there should be no corner cases where it is
required to use a wrong domain name. This commit swaps out the
MemorizingHostnameVerifier that let users accept wrong domains with the
standard XmppDomainVerifier.

closes #4066
2021-04-30 09:55:22 +02:00
Daniel Gultsch ec061bedc1 always show contact permission explain dialog on Quicksy
Until now Conversations and Quicksy would only disply the dialog that explains
why we want contact read permissions after the user rejected the request once

(following Android design guidelines and `shouldShowRequestPermissionRationale()`)

However for PlayStore policy this is no longer enough and the app needs to
explain and ask for consent before starting to upload the data.

This commit now displays the explain dialog immediately before asking for the
first time.
2021-04-24 08:20:30 +02:00
Geno a7f4abbab5 Merge tag '2.9.11' into develop 2021-04-20 12:08:34 +02:00
Daniel Gultsch f9b292fd6a version bump to 2.9.11 + changelog 2021-04-18 18:46:05 +02:00
Daniel Gultsch 8aed588405 ensure vibration future is canceled when scheduling a new one 2021-04-18 16:09:36 +02:00
Daniel Gultsch ea2acc2963 use new hasInternet() API only on Android Q+
some VPN apps are broken on Android 7.1 (and below?)

fixes #4058
2021-04-18 15:47:31 +02:00
Daniel Gultsch 2760f07307 disable read timeout for HTTP Upload
fixes #4057
2021-04-18 15:46:47 +02:00
Daniel Gultsch ec22a39538 link to help.conversations.im from feature list in readme
fixes #4053
2021-04-13 16:10:50 +02:00
Daniel Gultsch 331fd30699 version bump to 2.9.10 + changelog 2021-04-09 15:50:19 +02:00
Daniel Gultsch c469b2dc22 pulled translations from transifex 2021-04-09 15:50:11 +02:00
Daniel Gultsch 202bde46ed properly error out if upload fails. fixes #4052 2021-04-09 15:49:33 +02:00
Daniel Gultsch 37ce311764 do not attempt to play ringtone if none was found 2021-04-08 10:53:01 +02:00
Daniel Gultsch 9fc04c4b1e when receiving out-of-order session-init in terminal state do not move to terminal again
fixes #4049
2021-04-08 10:23:39 +02:00
Daniel Gultsch 5f020af2cc pulled translations from transifex 2021-04-08 09:34:16 +02:00
Daniel Gultsch 55b2f2656d fix HTTP up/download for users that dont trust system CAs 2021-04-08 08:56:58 +02:00
Daniel Gultsch fb681dfd60 ammend 2.9.9 changelog 2021-04-03 09:34:24 +02:00
Daniel Gultsch 5e59f20685 delete issue template and contributing guidelines
people with half a brain will implicitly follow those guidelines any way and
provide the information requested in the issue template.

The vast majority of people have ignored the issue template in the past anyway.
2021-04-03 09:32:24 +02:00
Daniel Gultsch 0fc191d004 migrate hasInternetConnection() to new api
Thank you to @ailicic for figuring out the new API.

Closes #4050
2021-03-29 10:58:15 +02:00
Daniel Gultsch 30c9e7399e log track class in onAddTrack 2021-03-29 10:57:56 +02:00
Geno 35e6c476dd Merge tag '2.9.9' into develop 2021-03-28 10:36:21 +02:00
Daniel Gultsch f632c7bbc9 version bump to 2.9.9 + changelog 2021-03-26 14:54:46 +01:00
Daniel Gultsch 08f27ddcf8 don’t show video call button if no camera is available 2021-03-26 14:04:36 +01:00
Daniel Gultsch 1822a71c2a Do not crash when receiving video call on device w/o camera
Upon accepting a video call on a device that can not establish a video track on
its own (for example by not having a camera), displaying the video enable/disable
button would fail. This commit defaults this button to disabled.
2021-03-26 12:54:26 +01:00
Daniel Gultsch 77f448692c catch security exception when reading file 2021-03-24 10:47:50 +01:00
Daniel Gultsch 9cc95d4cc2 pulled translations from transifex 2021-03-24 09:59:12 +01:00
Daniel Gultsch ff756647a9 clear dns cache on network switch 2021-03-23 21:03:58 +01:00
Daniel Gultsch 9a7fc3d9b8 disable omemo by default for *.covid.monal.im domains 2021-03-23 11:52:34 +01:00
Daniel Gultsch d37140ebf0 pulled translations from transifex 2021-03-23 11:48:17 +01:00
Daniel Gultsch d288f5bff2 version bump to 2.9.9-beta 2021-03-23 10:36:56 +01:00
Daniel Gultsch aad34783ad remove logging from needsUploading() 2021-03-22 19:05:46 +01:00
Daniel Gultsch 914ea9c398 use http proxy below android 7.1 2021-03-22 18:03:25 +01:00
Daniel Gultsch 02b16063c6 show popup dialog when backup has been started. fixes #4031 2021-03-22 15:40:22 +01:00
Daniel Gultsch 45c5f9aa90 bump okhttp version 2021-03-22 15:26:13 +01:00
Daniel Gultsch 4ac64f3a3b clean up code for posh cache 2021-03-22 15:15:35 +01:00
Daniel Gultsch 8b90c1c498 port POSH code to OkHttp 2021-03-22 14:32:31 +01:00
Daniel Gultsch 70fc08314f remove unused method 2021-03-22 11:14:35 +01:00
Daniel Gultsch ce7f59a76c use okhttp to fetch captcha 2021-03-22 10:39:53 +01:00
Daniel Gultsch 1cd95aefa6 migrate redirection urls to HttpUrl 2021-03-22 10:12:53 +01:00
Daniel Gultsch 739d20428a optimize imports 2021-03-21 21:39:04 +01:00
Daniel Gultsch 6ee2807027 bump gradle plugin 2021-03-21 21:18:33 +01:00
Daniel Gultsch a6244d986a use settable futures for slot requester 2021-03-21 20:45:26 +01:00
Daniel Gultsch 8ac97b0027 disable extmap_allow_mixed by default 2021-03-21 19:40:52 +01:00
Daniel Gultsch 7a115cb967 pulled translations from transifex 2021-03-21 19:36:21 +01:00
Daniel Gultsch d1195d21ae pulled translations from transifex 2021-03-20 11:58:43 +01:00
Daniel Gultsch 72828c6c4e fix 'checking file size' status display 2021-03-20 11:21:48 +01:00
Daniel Gultsch 38ef69a926 do not display toast for cancelled downloads 2021-03-20 11:00:20 +01:00
Daniel Gultsch aaac8296b3 only overwrite body in text messages 2021-03-19 19:51:13 +01:00
Daniel Gultsch e217551a82 migrate to OkHttp instead of HttpUrlConnection
OkHttp gives us more fine grained control over the HTTP library and frees us from any platform bugs
2021-03-19 14:57:20 +01:00
Daniel Gultsch b09a1432a3 Stanza.getErrorCondation only ever needs the tag name 2021-03-18 11:35:41 +01:00
Geno f161a9c4bf metadata: add changelog 2.9.8 2021-03-17 10:18:53 +01:00
Geno f8e69f9fc2 Merge tag '2.9.8' into develop 2021-03-17 10:17:05 +01:00
Daniel Gultsch 6f1b71970d parse extmap-allow-mixed 2021-03-16 18:52:38 +01:00
Daniel Gultsch 3baacf8862 switch to unified plan 2021-03-16 18:52:38 +01:00
Daniel Gultsch 9c2da0a1b8 upgrade libwebrtc to m89 2021-03-16 18:52:38 +01:00
Daniel Gultsch 2681ad82e1 complain if mLineIndex can not be found when receiving candidates 2021-03-16 18:52:25 +01:00
Daniel Gultsch 8764d11cce kill pending queries when archiving conversation 2021-03-16 10:22:52 +01:00
Daniel Gultsch 3c60de54cb minor code clean up 2021-03-16 08:16:07 +01:00
Daniel Gultsch d30a08266a
Fix typo in readme 2021-03-15 06:51:00 +00:00
Daniel Gultsch 859f3b2a1d fix NPE after race condition. fixes #4033 2021-03-13 11:13:19 +01:00
Daniel Gultsch bf25b24967 modify away when locked behaviour to locked || screen off
this new behaviour still takes care of not going online when quickly
checking for the time but it also includes systems that don’t have a
lock screen or incorrectly report being unlocked.
2021-03-13 10:52:06 +01:00
Daniel Gultsch 7c53dcc4f4 fixed NPE when service isnt bound 2021-03-13 10:51:41 +01:00
Daniel Gultsch bf9d1a5759 remove docs folder
* mission statement is now hosted on https://gultsch.de
* XEPs.md has been replaced by conversations.doap
* observations.md is just outdated and boring by now
2021-03-12 18:31:11 +01:00
Daniel Gultsch ddb54bb222 version bump to 2.9.8 + changelog 2021-03-11 10:37:29 +01:00
Daniel Gultsch 813b07e18d pulled translations from transifex 2021-03-09 09:58:33 +01:00
Daniel Gultsch 0fa06d65b5 overwrite body for plaintext group chat messages only 2021-03-07 09:59:09 +01:00
Daniel Gultsch e947a3f808 modify boyy on muc reflection 2021-03-06 12:43:59 +01:00
Daniel Gultsch b34f6e0720 null check weak reference value 2021-03-06 09:45:42 +01:00
Daniel Gultsch b8c61b795e use different top margin for vert and land for duration display 2021-03-06 09:45:13 +01:00
Daniel Gultsch cf68c544aa pulled translations from transifex 2021-03-06 08:58:28 +01:00
Christopher Vollick ef24d2050b Remove Renomination from WebRTC Options
This is a feature of WebRTC that's [not standardized][1] and only
supported by libwebrtc. Since there's no support in jingle for passing
this capability from one peer to another, we're currently hard-coding
this option into both the local candidate and also the remote candidate
so they can use it.

But I'm trying to call a user that isn't using WebRTC, and renomination
is causing the call to stay in "connecting..." state for 10 or 20
seconds, sometimes longer, while both sides wait for the other to
nominate something based on their individual beliefs about the standards
they're using.

Removing this seems to make connecting relatively instantaneous.

If we want to reintroduce this feature, we should probably make a XEP so
the peers can negotiate honestly about it, and only use it if both sides
truely support the feature.

[1]: https://datatracker.ietf.org/doc/html/draft-thatcher-ice-renomination-01
2021-03-04 08:26:52 +00:00
Daniel Gultsch 4a175f915d version bump to 2.9.8-beta 2021-03-04 09:25:20 +01:00
Daniel Gultsch 5848013a1e handle pre key messages in dtls verification 2021-03-03 14:03:08 +01:00
Daniel Gultsch c5f801c1fe do not push empty candidates to backlog 2021-03-03 13:12:10 +01:00
Daniel Gultsch d52c46d582 use omemo verification only if omemo is enabled in conversation 2021-03-03 12:55:27 +01:00
Daniel Gultsch e81fb1b24e pulled translations from transifex 2021-03-03 09:48:29 +01:00
Daniel Gultsch 3ee70b1d48 show verified shield in rtp session activity 2021-03-03 09:41:05 +01:00
Daniel Gultsch e4b2bb4a42 throw exception when unable to encrypt 2021-03-03 08:22:21 +01:00
Daniel Gultsch 8a6430ae29 ground work for omemo dtls verification 2021-03-02 21:13:49 +01:00
Geno a213b00091 Merge tag '2.9.7' into develop 2021-02-26 15:46:02 +01:00
Geno 64e88d946f fix crashes with internal database error 2021-02-26 14:46:41 +01:00
Daniel Gultsch 47a904b4fc pulled translations from transifex 2021-02-26 10:18:59 +01:00
Daniel Gultsch 33e73a2b47 bump version code for release 2021-02-24 12:18:14 +01:00
Daniel Gultsch d889c02a0a make ascii armor parsing more resiliant 2021-02-24 11:05:11 +01:00
Daniel Gultsch 073b6a998a pulled translations from transifex 2021-02-24 10:35:46 +01:00
Daniel Gultsch 9450d49b0b do not vibrate when in DND mode 2021-02-24 10:35:33 +01:00
Daniel Gultsch 5e0c158cde fix default ringtone for incoming call setting 2021-02-22 13:59:07 +01:00
Daniel Gultsch 16b1c561d4 pulled translations from transifex 2021-02-22 09:31:13 +01:00
Daniel Gultsch 24f2f52512 limit http upload / download to 4 parallel connections 2021-02-22 09:24:41 +01:00
Daniel Gultsch e98ec40b7f pulled translations from transifex 2021-02-21 14:15:33 +01:00
Daniel Gultsch f92ea5c70b resend <propose/> only if server has stream mgmt 2021-02-21 13:37:08 +01:00
Daniel Gultsch 81505c6202 version bump to 2.9.7-beta + changelog 2021-02-20 11:07:02 +01:00
Daniel Gultsch 638f30b902 pulled translations from transifex 2021-02-20 10:16:56 +01:00
Daniel Gultsch 0812bae1ab do not run alpha check on jpegs 2021-02-20 10:08:43 +01:00
Daniel Gultsch 6bfe16f044 replace away when screen off with away when locked
fixes #3978
2021-02-19 15:59:56 +01:00
Daniel Gultsch 53da64b7e2 do not attempt to play 'none' ringtone
trying to play 'none' ringtone resulted in the default ring tone being played
2021-02-19 15:31:01 +01:00
Daniel Gultsch ebb38d7d75 consume volume down event 2021-02-18 22:16:28 +01:00
Daniel Gultsch 484f633180 let Conversations (not Android) play ringtone and vibration
fixes #3972 fixes #3801 fixes #3931
2021-02-18 20:55:31 +01:00
Daniel Gultsch 78c89664c4 moved translations into new resource on transifex
the 'strings' resource on transifex was in the internal 'Android 1' format
instead of the more modern 'Android 2' format.

This according to transifex support caused some weird issues…

The only work around (apparently) was to create a new resource (now call
main-strings) and use that instead.

I hope we didn’t mess anything up in the process.

Let's be extra careful with the next release
2021-02-18 16:56:59 +01:00
Daniel Gultsch 90270069da pulled translations from transifex 2021-02-18 11:05:02 +01:00
Daniel Gultsch 49992f300b repharse omemo fingerprint description 2021-02-18 10:35:10 +01:00
Daniel Gultsch 72e268e6b1 add TODO comments wrt to missing <retract/> parsing 2021-02-18 09:36:51 +01:00
Daniel Gultsch 78901e3339 use detached signatures 2021-02-17 22:47:40 +01:00
Daniel Gultsch 149224a073 do not deduplicate disco queries
Conversations used to deduplicate disco queries based on their hash.
However that relies on the first query to go through (device to actually
respond) and to respond properly (hash matches).

Creating a proper retry behaviour for this is actually quite challanging.
(which one would you try next, how long do you wait?)
2021-02-17 18:14:18 +01:00
Daniel Gultsch db447f845e resend session proposal on rebind 2021-02-12 11:36:44 +01:00
Daniel Gultsch 6cab0ad496 make rtp proposal tracked by SM. fixes #3983 2021-02-12 10:35:13 +01:00
Daniel Gultsch 9f869d3895 slightly change wording of sync_with_contacts_long 2021-02-11 18:55:27 +01:00
Daniel Gultsch b808a03702 update dependencies
now that we have minSdk=21 we can bump retrofit and okhttp
2021-02-11 18:28:48 +01:00
Daniel Gultsch 7330d8a7f0 fixed race conditions around PROCEED state. fixes #3989 2021-02-11 16:56:57 +01:00
Daniel Gultsch 6e3dc0eef6 fix up for last commit. (re-add \n) 2021-02-11 09:05:29 +01:00
Daniel Gultsch 3847ab8465 paramaterize app name in more places 2021-02-10 15:56:02 +01:00
Daniel Gultsch deee31e517 pulled translations from transifex 2021-02-10 14:29:36 +01:00
mimi89999 ab17f935c3 Fix formatting of openkeychain_required_long message 2021-02-10 13:16:56 +00:00
mimi89999 d51b4380d7 Add variable app name in res strings
Closes #3988
2021-02-10 11:35:49 +00:00
Daniel Gultsch b6d62c13ef use ascii notation for punycode domains in SNI 2021-02-07 09:38:55 +01:00
Daniel Gultsch b76b60df5c verify against IDN variant of domain 2021-02-04 11:15:59 +01:00
Daniel Gultsch f82ae0a9b8 Merge branch 'maxim432-fix_leaks' 2021-01-31 10:13:35 +01:00
Daniel Gultsch 358c70828f close inputstream in image meta data analysers 2021-01-31 10:13:20 +01:00
maxim432 156c4da2b3 Fix couple of leaks 2021-01-30 17:56:54 -08:00
Daniel Gultsch ca496fd39f look at only subset of pixels to check for alpha 2021-01-30 01:50:03 +01:00
Daniel Gultsch 53a038d90e fix rtp offline discovery 2021-01-30 01:47:03 +01:00
Daniel Gultsch d77d89b356 mention in changelog that Android 5 is required 2021-01-30 00:37:09 +01:00
Daniel Gultsch 2155a50875 do not compress images with alpha channels 2021-01-29 21:25:00 +01:00
Daniel Gultsch 4a9dfb9567 fix copy url to clipboard action for undownloaded files 2021-01-28 17:49:34 +01:00
Daniel Gultsch 10382e83bf remove unused methods 2021-01-28 17:40:58 +01:00
Daniel Gultsch c11ac40df4 use 'missed call' as label for missed call status 2021-01-28 11:00:27 +01:00
245 changed files with 34196 additions and 29166 deletions

View File

@ -1,14 +0,0 @@
#!/bin/sh
find -type d -name "siacs" -print0 | xargs --null -I{} bash -c 'x="{}"; mv "$x" "${x/siacs/sum7}" '
find -type f -name "*.java" -exec sed -i "/eu.siacs.conversations.axolotl/! s/eu.siacs./eu.sum7./" "{}" \;
find -type f -name "*.xml" -exec sed -i "/eu.siacs.conversations.axolotl/! s/eu.siacs./eu.sum7./" "{}" \;
# workaround for bug in fdroid nightly
sed -i "s/-debug.apk/-unsigned.apk/" /usr/lib/python3/dist-packages/fdroidserver/nightly.py
# generate new version
git fetch --tags
export versionCode="$DRONE_BUILD_NUMBER"
export versionName="$(git describe --tag --abbrev=0)-${DRONE_BUILD_NUMBER}"
echo "set VersionCode '${versionCode}' and VersonName '${versionName}'"
sed -i "s/^\(\s*versionCode\s*\).*$/\1$versionCode/" build.gradle
sed -i "0,/versionName/s/^\(\s*versionName\).*/\1 \"$versionName\"/" build.gradle
cat -n build.gradle

View File

@ -1,31 +0,0 @@
---
kind: pipeline
type: docker
name: default
steps:
- image: registry.gitlab.com/fdroid/ci-images-client:latest
name: build
when:
branch:
exclude:
- droneci
commands:
- ./gradlew assembleConversationsFreeCompatDebug
- image: registry.gitlab.com/fdroid/ci-images-client:latest
name: publish
when:
branch:
include:
- droneci
environment:
DEBUG_KEYSTORE:
from_secret: DEBUG_KEYSTORE
commands:
- .ci/prepare-publish.sh
# build free version
- ./gradlew assembleConversationsFreeCompatRelease
- ls build/outputs/apk/conversationsFreeCompat/*
# publish on nightly fdroid repo
- fdroid nightly -v

38
.github/workflows/android.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: Android CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: set up JDK 11
uses: actions/setup-java@v2
with:
java-version: '11'
distribution: 'adopt'
- name: Download WebRTC
run: mkdir libs && wget -O libs/libwebrtc-m92.aar https://gultsch.de/files/libwebrtc-m92.aar
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build Quicksy (Compat)
run: ./gradlew assembleQuicksyFreeCompatDebug
- name: Build Quicksy (System)
run: ./gradlew assembleQuicksyFreeSystemDebug
- name: Build Conversations (Compat)
run: ./gradlew assembleConversationsFreeCompatDebug
- name: Build Conversations (System)
run: ./gradlew assembleConversationsFreeSystemDebug
- uses: actions/upload-artifact@v2
with:
name: Conversations all-flavors (debug)
path: ./build/outputs/apk/**/debug/Conversations-*.apk

View File

@ -1,22 +0,0 @@
language: android
jdk:
- oraclejdk8
android:
components:
- platform-tools
- tools
- build-tools-28.0.3
- extra-google-google_play_services
licenses:
- '.+'
before_script:
- mkdir libs
- wget -O libs/libwebrtc-m87.aar https://gultsch.de/files/libwebrtc-m87.aar
script:
- ./gradlew assembleQuicksyFreeCompatDebug
- ./gradlew assembleQuicksyFreeSystemDebug
- ./gradlew assembleConversationsFreeCompatDebug
- ./gradlew assembleConversationsFreeSystemDebug
before_install:
- yes | sdkmanager "platforms;android-28"

View File

@ -2,7 +2,7 @@
host = https://www.transifex.com host = https://www.transifex.com
lang_map = af_ZA: af-rZA, am_ET: am-rET, ar_AE: ar-rAE, ar_BH: ar-rBH, ar_DZ: ar-rDZ, ar_EG: ar-rEG, ar_IQ: ar-rIQ, ar_JO: ar-rJO, ar_KW: ar-rKW, ar_LB: ar-rLB, ar_LY: ar-rLY, ar_MA: ar-rMA, ar_OM: ar-rOM, ar_QA: ar-rQA, ar_SA: ar-rSA, ar_SY: ar-rSY, ar_TN: ar-rTN, ar_YE: ar-rYE, arn_CL: arn-rCL, as_IN: as-rIN, az_AZ: az-rAZ, ba_RU: ba-rRU, be_BY: be-rBY, bg_BG: bg-rBG, bn_BD: bn-rBD, bn_IN: bn-rIN, bo_CN: bo-rCN, br_FR: br-rFR, bs_BA: bs-rBA, ca_ES: ca-rES, co_FR: co-rFR, cs_CZ: cs-rCZ, cy_GB: cy-rGB, da_DK: da-rDK, de_AT: de-rAT, de_CH: de-rCH, de_DE: de-rDE, de_LI: de-rLI, de_LU: de-rLU, dsb_DE: dsb-rDE, dv_MV: dv-rMV, el_GR: el-rGR, en_AU: en-rAU, en_BZ: en-rBZ, en_CA: en-rCA, en_GB: en-rGB, en_IE: en-rIE, en_IN: en-rIN, en_JM: en-rJM, en_MY: en-rMY, en_NZ: en-rNZ, en_PH: en-rPH, en_SG: en-rSG, en_TT: en-rTT, en_US: en-rUS, en_ZA: en-rZA, en_ZW: en-rZW, es_AR: es-rAR, es_BO: es-rBO, es_CL: es-rCL, es_CO: es-rCO, es_CR: es-rCR, es_DO: es-rDO, es_EC: es-rEC, es_ES: es-rES, es_GT: es-rGT, es_HN: es-rHN, es_MX: es-rMX, es_NI: es-rNI, es_PA: es-rPA, es_PE: es-rPE, es_PR: es-rPR, es_PY: es-rPY, es_SV: es-rSV, es_US: es-rUS, es_UY: es-rUY, es_VE: es-rVE, et_EE: et-rEE, eu_ES: eu-rES, fa_IR: fa-rIR, fi_FI: fi-rFI, fil_PH: fil-rPH, fo_FO: fo-rFO, fr_BE: fr-rBE, fr_CA: fr-rCA, fr_CH: fr-rCH, fr_FR: fr-rFR, fr_LU: fr-rLU, fr_MC: fr-rMC, fy_NL: fy-rNL, ga_IE: ga-rIE, gd_GB: gd-rGB, gl_ES: gl-rES, gsw_FR: gsw-rFR, gu_IN: gu-rIN, ha_NG: ha-rNG, hi_IN: hi-rIN, hr_BA: hr-rBA, hr_HR: hr-rHR, hsb_DE: hsb-rDE, hu_HU: hu-rHU, hy_AM: hy-rAM, id_ID: id-rID, ig_NG: ig-rNG, ii_CN: ii-rCN, is_IS: is-rIS, it_CH: it-rCH, it_IT: it-rIT, iu_CA: iu-rCA, ja_JP: ja-rJP, ka_GE: ka-rGE, kk_KZ: kk-rKZ, kl_GL: kl-rGL, km_KH: km-rKH, kn_IN: kn-rIN, ko_KR: ko-rKR, kok_IN: kok-rIN, ky_KG: ky-rKG, lb_LU: lb-rLU, lo_LA: lo-rLA, lt_LT: lt-rLT, lv_LV: lv-rLV, mi_NZ: mi-rNZ, mk_MK: mk-rMK, ml_IN: ml-rIN, mn_CN: mn-rCN, mn_MN: mn-rMN, moh_CA: moh-rCA, mr_IN: mr-rIN, ms_BN: ms-rBN, ms_MY: ms-rMY, mt_MT: mt-rMT, nb_NO: nb-rNO, ne_NP: ne-rNP, nl_BE: nl-rBE, nl_NL: nl-rNL, nn_NO: nn-rNO, nso_ZA: nso-rZA, oc_FR: oc-rFR, or_IN: or-rIN, pa_IN: pa-rIN, pl_PL: pl-rPL, prs_AF: prs-rAF, ps_AF: ps-rAF, pt_BR: pt-rBR, pt_PT: pt-rPT, qut_GT: qut-rGT, quz_BO: quz-rBO, quz_EC: quz-rEC, quz_PE: quz-rPE, rm_CH: rm-rCH, ro_RO: ro-rRO, ru_RU: ru-rRU, rw_RW: rw-rRW, sa_IN: sa-rIN, sah_RU: sah-rRU, se_FI: se-rFI, se_NO: se-rNO, se_SE: se-rSE, si_LK: si-rLK, sk_SK: sk-rSK, sl_SI: sl-rSI, sma_NO: sma-rNO, sma_SE: sma-rSE, smj_NO: smj-rNO, smj_SE: smj-rSE, smn_FI: smn-rFI, sms_FI: sms-rFI, sq_AL: sq-rAL, sr_BA: sr-rBA, sr_CS: sr-rCS, sr_ME: sr-rME, sr_RS: sr-rRS, sv_FI: sv-rFI, sv_SE: sv-rSE, sw_KE: sw-rKE, syr_SY: syr-rSY, ta_IN: ta-rIN, te_IN: te-rIN, tg_TJ: tg-rTJ, th_TH: th-rTH, tk_TM: tk-rTM, tn_ZA: tn-rZA, tr_TR: tr-rTR, tt_RU: tt-rRU, tzm_DZ: tzm-rDZ, ug_CN: ug-rCN, uk_UA: uk-rUA, ur_PK: ur-rPK, uz_UZ: uz-rUZ, vi_VN: vi-rVN, wo_SN: wo-rSN, xh_ZA: xh-rZA, yo_NG: yo-rNG, zh_CN: zh-rCN, zh_HK: zh-rHK, zh_MO: zh-rMO, zh_SG: zh-rSG, zh_TW: zh-rTW, zu_ZA: zu-rZA, no_NO: no-rNO, he_IL: iw-rIL, he: iw lang_map = af_ZA: af-rZA, am_ET: am-rET, ar_AE: ar-rAE, ar_BH: ar-rBH, ar_DZ: ar-rDZ, ar_EG: ar-rEG, ar_IQ: ar-rIQ, ar_JO: ar-rJO, ar_KW: ar-rKW, ar_LB: ar-rLB, ar_LY: ar-rLY, ar_MA: ar-rMA, ar_OM: ar-rOM, ar_QA: ar-rQA, ar_SA: ar-rSA, ar_SY: ar-rSY, ar_TN: ar-rTN, ar_YE: ar-rYE, arn_CL: arn-rCL, as_IN: as-rIN, az_AZ: az-rAZ, ba_RU: ba-rRU, be_BY: be-rBY, bg_BG: bg-rBG, bn_BD: bn-rBD, bn_IN: bn-rIN, bo_CN: bo-rCN, br_FR: br-rFR, bs_BA: bs-rBA, ca_ES: ca-rES, co_FR: co-rFR, cs_CZ: cs-rCZ, cy_GB: cy-rGB, da_DK: da-rDK, de_AT: de-rAT, de_CH: de-rCH, de_DE: de-rDE, de_LI: de-rLI, de_LU: de-rLU, dsb_DE: dsb-rDE, dv_MV: dv-rMV, el_GR: el-rGR, en_AU: en-rAU, en_BZ: en-rBZ, en_CA: en-rCA, en_GB: en-rGB, en_IE: en-rIE, en_IN: en-rIN, en_JM: en-rJM, en_MY: en-rMY, en_NZ: en-rNZ, en_PH: en-rPH, en_SG: en-rSG, en_TT: en-rTT, en_US: en-rUS, en_ZA: en-rZA, en_ZW: en-rZW, es_AR: es-rAR, es_BO: es-rBO, es_CL: es-rCL, es_CO: es-rCO, es_CR: es-rCR, es_DO: es-rDO, es_EC: es-rEC, es_ES: es-rES, es_GT: es-rGT, es_HN: es-rHN, es_MX: es-rMX, es_NI: es-rNI, es_PA: es-rPA, es_PE: es-rPE, es_PR: es-rPR, es_PY: es-rPY, es_SV: es-rSV, es_US: es-rUS, es_UY: es-rUY, es_VE: es-rVE, et_EE: et-rEE, eu_ES: eu-rES, fa_IR: fa-rIR, fi_FI: fi-rFI, fil_PH: fil-rPH, fo_FO: fo-rFO, fr_BE: fr-rBE, fr_CA: fr-rCA, fr_CH: fr-rCH, fr_FR: fr-rFR, fr_LU: fr-rLU, fr_MC: fr-rMC, fy_NL: fy-rNL, ga_IE: ga-rIE, gd_GB: gd-rGB, gl_ES: gl-rES, gsw_FR: gsw-rFR, gu_IN: gu-rIN, ha_NG: ha-rNG, hi_IN: hi-rIN, hr_BA: hr-rBA, hr_HR: hr-rHR, hsb_DE: hsb-rDE, hu_HU: hu-rHU, hy_AM: hy-rAM, id_ID: id-rID, ig_NG: ig-rNG, ii_CN: ii-rCN, is_IS: is-rIS, it_CH: it-rCH, it_IT: it-rIT, iu_CA: iu-rCA, ja_JP: ja-rJP, ka_GE: ka-rGE, kk_KZ: kk-rKZ, kl_GL: kl-rGL, km_KH: km-rKH, kn_IN: kn-rIN, ko_KR: ko-rKR, kok_IN: kok-rIN, ky_KG: ky-rKG, lb_LU: lb-rLU, lo_LA: lo-rLA, lt_LT: lt-rLT, lv_LV: lv-rLV, mi_NZ: mi-rNZ, mk_MK: mk-rMK, ml_IN: ml-rIN, mn_CN: mn-rCN, mn_MN: mn-rMN, moh_CA: moh-rCA, mr_IN: mr-rIN, ms_BN: ms-rBN, ms_MY: ms-rMY, mt_MT: mt-rMT, nb_NO: nb-rNO, ne_NP: ne-rNP, nl_BE: nl-rBE, nl_NL: nl-rNL, nn_NO: nn-rNO, nso_ZA: nso-rZA, oc_FR: oc-rFR, or_IN: or-rIN, pa_IN: pa-rIN, pl_PL: pl-rPL, prs_AF: prs-rAF, ps_AF: ps-rAF, pt_BR: pt-rBR, pt_PT: pt-rPT, qut_GT: qut-rGT, quz_BO: quz-rBO, quz_EC: quz-rEC, quz_PE: quz-rPE, rm_CH: rm-rCH, ro_RO: ro-rRO, ru_RU: ru-rRU, rw_RW: rw-rRW, sa_IN: sa-rIN, sah_RU: sah-rRU, se_FI: se-rFI, se_NO: se-rNO, se_SE: se-rSE, si_LK: si-rLK, sk_SK: sk-rSK, sl_SI: sl-rSI, sma_NO: sma-rNO, sma_SE: sma-rSE, smj_NO: smj-rNO, smj_SE: smj-rSE, smn_FI: smn-rFI, sms_FI: sms-rFI, sq_AL: sq-rAL, sr_BA: sr-rBA, sr_CS: sr-rCS, sr_ME: sr-rME, sr_RS: sr-rRS, sv_FI: sv-rFI, sv_SE: sv-rSE, sw_KE: sw-rKE, syr_SY: syr-rSY, ta_IN: ta-rIN, te_IN: te-rIN, tg_TJ: tg-rTJ, th_TH: th-rTH, tk_TM: tk-rTM, tn_ZA: tn-rZA, tr_TR: tr-rTR, tt_RU: tt-rRU, tzm_DZ: tzm-rDZ, ug_CN: ug-rCN, uk_UA: uk-rUA, ur_PK: ur-rPK, uz_UZ: uz-rUZ, vi_VN: vi-rVN, wo_SN: wo-rSN, xh_ZA: xh-rZA, yo_NG: yo-rNG, zh_CN: zh-rCN, zh_HK: zh-rHK, zh_MO: zh-rMO, zh_SG: zh-rSG, zh_TW: zh-rTW, zu_ZA: zu-rZA, no_NO: no-rNO, he_IL: iw-rIL, he: iw
[conversations.strings] [conversations.main-strings]
file_filter = src/main/res/values-<lang>/strings.xml file_filter = src/main/res/values-<lang>/strings.xml
source_file = src/main/res/values/strings.xml source_file = src/main/res/values/strings.xml
source_lang = en source_lang = en

View File

@ -1,5 +1,54 @@
# Changelog # Changelog
### Version 2.10.2
* Fix crash when rendering some quotes
* Fix crash in welcome screen
### Version 2.10.1
* Fix issue with some videos not being compressed
* Fix rare crash when opening notification
### Version 2.10.0
* Show black bars when remote video does not match aspect ratio of screen
* Improve search performance
* Add setting to prevent screenshots
### Version 2.9.13
* minor A/V improvements
### Version 2.9.12
* Always verify domain name. No user overwrite
* Support roster pre authentication
### Version 2.9.11
* Fixed 'No Connectivity' issues on Android 7.1
### Version 2.9.10
* fix HTTP up/download for users that dont trust system CAs
### Version 2.9.9
* Various bug fixes around Tor support
* Improve call compatibility with Dino
### Version 2.9.8
* Verify A/V calls with preexisting OMEMO sessions
* Improve compatibility with non libwebrtc WebRTC implementations
### Version 2.9.7
* Ability to select incoming call ringtone
* Fix OpenPGP key id discovery for OpenKeychain 5.6+
* Properly verify punycode TLS certificates
* Improve stability of RTP session establishment (calling)
### Version 2.9.6 ### Version 2.9.6
* Show call button for offline contacts if they previously announced support * Show call button for offline contacts if they previously announced support
@ -12,6 +61,7 @@
### Version 2.9.4 ### Version 2.9.4
* minor stability improvements for A/V calls * minor stability improvements for A/V calls
* Conversations releases from here on forward require Android 5
### Version 2.9.3 ### Version 2.9.3

View File

@ -43,7 +43,7 @@
* End-to-end encryption with [OMEMO](http://conversations.im/omemo/) or [OpenPGP](http://openpgp.org/about/) * End-to-end encryption with [OMEMO](http://conversations.im/omemo/) or [OpenPGP](http://openpgp.org/about/)
* Send and receive images as well as other kind of files * Send and receive images as well as other kind of files
* Encrypted audio and video calls (DTLS-SRTP) * [Encrypted audio and video calls (DTLS-SRTP)](https://help.conversations.im)
* Share your location * Share your location
* Send voice messages * Send voice messages
* Indication when your contact has read your message * Indication when your contact has read your message
@ -139,7 +139,7 @@ Note: This is kind of a weird quirk in OpenFire. Most other servers would just t
Maybe you attempted to use the Jabber ID `test@b.tld` because `a.tld` doesnt point to the correct host. In that case you might have to enable the extended connection settings in the expert settings of Conversations and set a host name. Maybe you attempted to use the Jabber ID `test@b.tld` because `a.tld` doesnt point to the correct host. In that case you might have to enable the extended connection settings in the expert settings of Conversations and set a host name.
### I get 'Stream opening error'. What does that mean? #### I get 'Stream opening error'. What does that mean?
In most cases this error is caused by ejabberd advertising support for TLSv1.3 but not properly supporting it. This can happen if the OpenSSL version on the server already supports TLSv1.3 but the fast\_tls wrapper library used by ejabberd not (properly) support it. Upgrading fast\_tls and ejabberd or - theoretically - downgrading OpenSSL should fix the issue. A work around is to explicitly disable TLSv1.3 support in the ejabberd configuration. More information can be found on [this issue on the ejabberd issue tracker](https://github.com/processone/ejabberd/issues/2614). In most cases this error is caused by ejabberd advertising support for TLSv1.3 but not properly supporting it. This can happen if the OpenSSL version on the server already supports TLSv1.3 but the fast\_tls wrapper library used by ejabberd not (properly) support it. Upgrading fast\_tls and ejabberd or - theoretically - downgrading OpenSSL should fix the issue. A work around is to explicitly disable TLSv1.3 support in the ejabberd configuration. More information can be found on [this issue on the ejabberd issue tracker](https://github.com/processone/ejabberd/issues/2614).
@ -371,7 +371,7 @@ Unfortunately we dont have a recommendation for iPhones right now. There are
**Note:** Starting with version 2.8.0 you will need to compile libwebrtc. **Note:** Starting with version 2.8.0 you will need to compile libwebrtc.
[Instructions](https://webrtc.github.io/webrtc-org/native-code/android/) can be found on the WebRTC [Instructions](https://webrtc.github.io/webrtc-org/native-code/android/) can be found on the WebRTC
website. Place the resulting libwebrtc.aar in the `libs/` directory. The PlayStore release currently website. Place the resulting libwebrtc.aar in the `libs/` directory. The PlayStore release currently
uses the stable M81 release and renamed the file name to `libwebrtc-m81.aar` put potentially you can uses the stable M90 release and renamed the file name to `libwebrtc-m90.aar` put potentially you can
reference any file name by modifying `build.gradle`. reference any file name by modifying `build.gradle`.
Make sure to have ANDROID_HOME point to your Android SDK. Use the Android SDK Manager to install missing dependencies. Make sure to have ANDROID_HOME point to your Android SDK. Use the Android SDK Manager to install missing dependencies.

View File

@ -1,14 +1,12 @@
import com.android.build.OutputFile
// Top-level build file where you can add configuration options common to all // Top-level build file where you can add configuration options common to all
// sub-projects/modules. // sub-projects/modules.
buildscript { buildscript {
repositories { repositories {
google() google()
jcenter() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:4.1.2' classpath 'com.android.tools.build:gradle:7.0.3'
} }
} }
@ -16,8 +14,8 @@ apply plugin: 'com.android.application'
repositories { repositories {
google() google()
jcenter()
mavenCentral() mavenCentral()
jcenter()
} }
configurations { configurations {
@ -35,24 +33,23 @@ configurations {
dependencies { dependencies {
implementation 'androidx.viewpager:viewpager:1.0.0' implementation 'androidx.viewpager:viewpager:1.0.0'
//should remain that low because later versions introduce dependency to androidx (not sure exactly from what version) playstoreImplementation('com.google.firebase:firebase-messaging:22.0.0') {
playstoreImplementation('com.google.firebase:firebase-messaging:21.0.1') {
exclude group: 'com.google.firebase', module: 'firebase-core' exclude group: 'com.google.firebase', module: 'firebase-core'
exclude group: 'com.google.firebase', module: 'firebase-analytics' exclude group: 'com.google.firebase', module: 'firebase-analytics'
exclude group: 'com.google.firebase', module: 'firebase-measurement-connector' exclude group: 'com.google.firebase', module: 'firebase-measurement-connector'
} }
conversationsPlaystoreCompatImplementation("com.android.installreferrer:installreferrer:2.2") conversationsPlaystoreCompatImplementation("com.android.installreferrer:installreferrer:2.2")
conversationsPlaystoreSystemImplementation("com.android.installreferrer:installreferrer:2.2") conversationsPlaystoreSystemImplementation("com.android.installreferrer:installreferrer:2.2")
quicksyPlaystoreCompatImplementation 'com.google.android.gms:play-services-auth-api-phone:17.5.0' quicksyPlaystoreCompatImplementation 'com.google.android.gms:play-services-auth-api-phone:17.5.1'
quicksyPlaystoreSystemImplementation 'com.google.android.gms:play-services-auth-api-phone:17.5.0' quicksyPlaystoreSystemImplementation 'com.google.android.gms:play-services-auth-api-phone:17.5.1'
implementation 'org.sufficientlysecure:openpgp-api:10.0' implementation 'org.sufficientlysecure:openpgp-api:10.0'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0' implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.exifinterface:exifinterface:1.3.2' implementation 'androidx.exifinterface:exifinterface:1.3.3'
implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'androidx.emoji:emoji:1.1.0' implementation 'androidx.emoji:emoji:1.1.0'
implementation 'com.google.android.material:material:1.2.1' implementation 'com.google.android.material:material:1.4.0'
compatImplementation 'androidx.emoji:emoji-appcompat:1.1.0' compatImplementation 'androidx.emoji:emoji-appcompat:1.1.0'
conversationsFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0' conversationsFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0'
quicksyFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0' quicksyFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0'
@ -65,21 +62,22 @@ dependencies {
implementation 'org.whispersystems:signal-protocol-java:2.6.2' implementation 'org.whispersystems:signal-protocol-java:2.6.2'
implementation 'com.makeramen:roundedimageview:2.3.0' implementation 'com.makeramen:roundedimageview:2.3.0'
implementation "com.wefika:flowlayout:0.4.1" implementation "com.wefika:flowlayout:0.4.1"
implementation 'net.ypresto.androidtranscoder:android-transcoder:0.3.0' implementation 'com.otaliastudios:transcoder:0.10.4'
implementation 'org.jxmpp:jxmpp-jid:0.6.4'
implementation 'org.osmdroid:osmdroid-android:6.1.5' implementation 'org.jxmpp:jxmpp-jid:1.0.2'
implementation 'org.osmdroid:osmdroid-android:6.1.10'
implementation 'org.hsluv:hsluv:0.2' implementation 'org.hsluv:hsluv:0.2'
implementation 'org.conscrypt:conscrypt-android:2.2.1' implementation 'org.conscrypt:conscrypt-android:2.5.2'
implementation 'me.drakeet.support:toastcompat:1.1.0' implementation 'me.drakeet.support:toastcompat:1.1.0'
implementation "com.leinardi.android:speed-dial:2.0.1" implementation "com.leinardi.android:speed-dial:3.2.0"
//retrofit needs to stick with 2.6.x (https://github.com/square/retrofit/blob/master/CHANGELOG.md)
implementation "com.squareup.retrofit2:retrofit:2.6.4" implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.6.4" implementation "com.squareup.retrofit2:converter-gson:2.9.0"
//okhttp needs to stick with 3.12.x implementation "com.squareup.okhttp3:okhttp:4.9.2"
implementation 'com.squareup.okhttp3:okhttp:3.12.12'
implementation 'com.google.guava:guava:27.1-android' implementation 'com.google.guava:guava:30.1.1-android'
quicksyImplementation 'io.michaelrocks:libphonenumber-android:8.12.16' quicksyImplementation 'io.michaelrocks:libphonenumber-android:8.12.36'
//implementation fileTree(include: ['libwebrtc-m87.aar'], dir: 'libs') // implementation fileTree(include: ['libwebrtc-m92.aar'], dir: 'libs')
implementation 'org.webrtc:google-webrtc:1.0.32006' implementation 'org.webrtc:google-webrtc:1.0.32006'
} }
@ -95,26 +93,25 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 29 targetSdkVersion 29
versionCode 408 versionCode 4202301
versionName "2.9.6.1" versionName "2.10.2"
archivesBaseName += "-$versionName" archivesBaseName += "-$versionName"
applicationId "eu.sum7.conversations" applicationId "eu.sum7.conversations"
resValue "string", "applicationId", applicationId resValue "string", "applicationId", applicationId
resValue "string", "app_name", "Conv6ations" def appName = "Conv6ations"
buildConfigField "String", "LOGTAG", "\"conver6ations\"" resValue "string", "app_name", appName
buildConfigField "String", "APP_NAME", "\"$appName\"";
} }
configurations {
implementation.exclude group: 'org.jetbrains' , module:'annotations'
}
dataBinding { dataBinding {
enabled true enabled true
} }
dexOptions {
// Skip pre-dexing when running on Travis CI or when disabled via -Dpre-dex=false.
preDexLibraries = preDexEnabled && !travisBuild
jumboMode true
}
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8
@ -127,9 +124,11 @@ android {
quicksy { quicksy {
dimension "mode" dimension "mode"
applicationId = "im.quicksy.client" applicationId = "im.quicksy.client"
resValue "string", "app_name", "Quicksy"
resValue "string", "applicationId", applicationId resValue "string", "applicationId", applicationId
buildConfigField "String", "LOGTAG", "\"quicksy\""
def appName = "Quicksy"
resValue "string", "app_name", appName
buildConfigField "String", "APP_NAME", "\"$appName\"";
} }
conversations { conversations {
@ -263,5 +262,4 @@ android {
exclude 'META-INF/BCKEY.DSA' exclude 'META-INF/BCKEY.DSA'
exclude 'META-INF/BCKEY.SF' exclude 'META-INF/BCKEY.SF'
} }
} }

View File

@ -453,12 +453,19 @@
<xmpp:version>0.2.0</xmpp:version> <xmpp:version>0.2.0</xmpp:version>
</xmpp:SupportedXep> </xmpp:SupportedXep>
</implements> </implements>
<implements>
<xmpp:SupportedXep>
<xmpp:xep rdf:resource="https://xmpp.org/extensions/xep-0454.html"/>
<xmpp:status>complete</xmpp:status>
<xmpp:version>0.1.0</xmpp:version>
</xmpp:SupportedXep>
</implements>
<release> <release>
<Version> <Version>
<revision>2.5.8</revision> <revision>2.9.13</revision>
<created>2019-09-12</created> <created>2021-05-03</created>
<file-release rdf:resource="https://github.com/iNPUTmice/Conversations/archive/2.5.8.tar.gz"/> <file-release rdf:resource="https://github.com/iNPUTmice/Conversations/archive/2.9.13.tar.gz"/>
</Version> </Version>
</release> </release>
</Project> </Project>

View File

@ -1,25 +0,0 @@
Conversations is a messenger for the next decade. Based on already established
internet standards that have been around for over ten years Conversations isnt
trying to replace current commercial messengers. It will simply outlive them.
Commercial, closed source products are coming and going. 15 years ago we had ICQ
which was replaced by Skype. MySpace was replaced by Facebook. WhatsApp and
Hangouts will disappear soon. Internet standards however stick around. People
are still using IRC and e-mail even though these protocols have been around for
decades. Utilizing proven standards doesnt mean one can not evolve. GMail has
revolutionized the way we look at e-mail. Firefox and Chrome have changed the
way we use the Web. Conversations will change the way we look at instant
messaging. Being less obtrusive than a telephone call instant messaging has
always played an important role in modern society. Conversations will show that
instant messaging can be fast, reliable and private. Conversations will not
force its security and privacy aspects upon the user. For those willing to use
encryption Conversations will make it as uncomplicated as possible. However
Conversations is aware that end-to-end encryption by the very principle isnt
trivial. Instead of trying the impossible and making encryption easier than
comparing a fingerprint Conversations will try to educate the willing user and
explain the necessary steps and the reasons behind them. Those unwilling to
learn about encryption will still be protected by the design principals of
Conversations. Conversations will simply not share or generate certain
information for example by encouraging the use of federated servers.
Conversations will always utilize the best available standards for encryption
and media encoding instead of reinventing the wheel. However it isnt afraid to
break with behavior patterns that have been proven ineffective.

View File

@ -1,32 +0,0 @@
* XEP-0027: Current Jabber OpenPGP Usage
* XEP-0030: Service Discovery
* XEP-0045: Multi-User Chat
* XEP-0048: Bookmarks
* XEP-0084: User Avatar
* XEP-0085: Chat State Notifications
* XEP-0092: Software Version
* XEP-0115: Entity Capabilities
* XEP-0163: Personal Eventing Protocol (avatars and nicks)
* XEP-0166: Jingle (only used for file transfer)
* XEP-0172: User Nickname
* XEP-0184: Message Delivery Receipts (reply only)
* XEP-0191: Blocking command
* XEP-0198: Stream Management
* XEP-0199: XMPP Ping
* XEP-0234: Jingle File Transfer
* XEP-0237: Roster Versioning
* XEP-0245: The /me Command
* XEP-0249: Direct MUC Invitations (receiving only)
* XEP-0260: Jingle SOCKS5 Bytestreams Transport Method
* XEP-0261: Jingle In-Band Bytestreams Transport Method
* XEP-0280: Message Carbons
* XEP-0308: Last Message Correction
* XEP-0313: Message Archive Management
* XEP-0319: Last User Interaction in Presence
* XEP-0333: Chat Markers
* XEP-0352: Client State Indication
* XEP-0357: Push Notifications
* XEP-0363: HTTP File Upload
* XEP-0368: SRV records for XMPP over TLS
* XEP-0377: Spam Reporting
* XEP-0384: OMEMO Encryption

View File

@ -1,97 +0,0 @@
Observations on implementing XMPP
=================================
After spending the last two and a half month basically writing my own XMPP
library from scratch I decided to share some of the observations I made in the
process. In part this article can be seen as a response to a blog post made by
Dr. Ing. Georg Lukas. The blog post introduces a couple of XEP (XMPP Extensions)
which make the life on mobile devices a lot easier but states that they are
currently very few implementations of those XEPs. So I went ahead and
implemented all of them in my Android XMPP client.
### General observations
The first thing I noticed is that XMPP is actually okish designed. If you were
to design a new chat protocol today you probably wouldnt choose XML again
however the protocol basically consists of only three different packages which
are quickly hidden under some sort of abstraction layer within your library.
Getting from zero to sending messages to other users actually was very simple
and straight forward. But then came the XEPs.
### Multi-User Chat
The first one was XEP-0045 Multi-User Chat. This is the one XEP of the XEPs Im
going to mention in my article which is actually wildly adopted. Most clients
and servers I know of support MUC. However the level of completeness varies.
MUC actually introduces access and permission roles which are far more complex
than what some of us are used to from IRC but a lot of clients just dont
implement them. Im not implementing them myself (at least for now) because I
somewhat doubt that someone would actually use them (however this might be some
sort of chicken or egg problem). I did find some strange bugs though which might
be interesting for other library developers. In theory a MUC server
implementation can allow a single user (same jid) to join a conference room
multiple times with the same nick from different clients. This means if someone
wants to participate in a conference from two different devices (mobile and
desktop for example) one wouldnt have to name oneself `userDesktop` and
`userMobile` but just `user`. Both ejabberd and prosody support this but with
strange side effects. Prosody for example doesnt allow a user to change its
name once two clients are “merged” by having the same nick.
### Carbons and Stream Management
Two of the other XEPs Lukas mentions — Carbons (XEP-0280) and Stream Management
(XEP-0198) — were actually fairly easy to implement. The only challenges were to
find a server to support them (I ended up running my own Prosody server) and a
desktop client to test them with. For carbons there is a patched Mcabber version
and Gajim. After implementing stream management I had very good results on my
mobile device. I had sessions running for up to 24 hours with a walking outside,
loosing mobile coverage for a few minutes and so on. The only limitation was
that I had to keep on developing and reinstalling my app.
### Off the record
And then came OTR... This is were I spend the most time debugging stuff and
trying to get things right and compatible with other clients. This is the part
were I want to help other developers not to make the same mistakes and maybe
come to some sort of consent among XMPP developers to ultimately increase the
interoperability. OTR has some down sides which make it difficult or at times
even dangerous to implement within XMPP. First of all it is a synchronous
protocol which is tunneled through a different protocol (XMPP). Synchronous
means — among other things — auto replies. (An OTR session begins with “hi Im
speaking otr give me your key” “ok cool here is my key”) And auto replies — we
know that since the first time an out of office auto responder went postal — are
dangerous. Things really start to get messy when you use one of the best
features of XMPP — multiple clients. The way XMPP works is that clients are
encouraged to send their messages to the raw jid and let the server decide what
full jid the messages are routed to. If in doubt even all of them. So what
happens when Alice sends a start-otr-message to Bobs raw jid? Bob receives the
message on his notebook as well as his cell phone. Both of them answer. Alice
gets two different replies. Shit explodes. Even if Alice sends the message to
bob/notebook chances are that Bob has carbon messages enabled and still receives
the messages on both devices. Now assuming that Bobs client is clever enough not
to auto reply to carbonated messages Bob/cellphone will still end up with a lot
of garbage messages. (Essentially the entire conversation between Alice and
Bob/notebook but unreadable of course) Therefor it should be good practice to
tag OTR messages as both private and no-copy (private is part of the carbons
XEP, no-copy is a general hint). I found that prosody for some reasons doesnt
honor the private tag on outgoing messages. While this is easily fixed I presume
that having both the private and the no-copy tag will make it more compatible
with servers or clients I dont know about yet.
#### Rules to follow when implementing OTR
To summarize my observations on implementing OTR in XMPP let me make the
following three statements.
1. While it is good practice for unencrypted messages to be send to the raw jid
and have the receiving server or user decide how they should be routed OTR
messages must be send to a specific resource. To make this work the user should
be given the option to select the presence (which can be assisted with some
educated guessing by the client based on previous messages). Furthermore a
client should encourage a user to choose meaningful presences instead of the
clients name or even random ones. Something like `/mobile`, `/notebook`,
`/desktop` is a greater assist to any one who wants to start an otr session then
`/Gajim`, `/mcabber` or `/pidgin`.
2. Messages should be tagged private and no-copy to avoid unnecessary traffic or
otr error loops with faulty clients. This tagging should be done even if your
own client doesnt support carbons.
3. When dealing with “legacy clients” — meaning clients which dont follow my
advise — a client should be extra careful not to create message loops. This
means to not respond with otr errors if a client is not 100% sure it is the only
client which received the message

View File

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip

View File

@ -0,0 +1,4 @@
• Ability to select incoming call ringtone
• Fix OpenPGP key id discovery for OpenKeychain 5.6+
• Properly verify punycode TLS certificates
• Improve stability of RTP session establishment (calling)

View File

@ -0,0 +1,2 @@
• Verify A/V calls with preexisting OMEMO sessions
• Improve compatibility with non libwebrtc WebRTC implementations

View File

@ -0,0 +1 @@
• Various bug fixes around Tor support

View File

@ -0,0 +1,3 @@
• Improve call compatibility with Dino
• fix HTTP up/download for users that dont trust system CAs
• Fixed 'No Connectivity' issues on Android 7.1

View File

@ -0,0 +1,3 @@
• Always verify domain name. No user overwrite
• Support roster pre authentication
• minor A/V improvements

View File

@ -0,0 +1,3 @@
• Show black bars when remote video does not match aspect ratio of screen
• Improve search performance
• Add setting to prevent screenshots

View File

@ -0,0 +1,2 @@
• Fix issue with some videos not being compressed
• Fix rare crash when opening notification

View File

@ -0,0 +1,2 @@
• Fix crash when rendering some quotes
• Fix crash in welcome screen

View File

@ -0,0 +1 @@
• Fix usage directTLS of manuelle enter an address

9
proguard-rules.pro vendored
View File

@ -26,6 +26,15 @@
-dontwarn java.lang.** -dontwarn java.lang.**
-dontwarn javax.lang.** -dontwarn javax.lang.**
-dontwarn com.android.org.conscrypt.SSLParametersImpl
-dontwarn org.apache.harmony.xnet.provider.jsse.SSLParametersImpl
-dontwarn org.bouncycastle.jsse.BCSSLParameters
-dontwarn org.bouncycastle.jsse.BCSSLSocket
-dontwarn org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
-dontwarn org.openjsse.javax.net.ssl.SSLParameters
-dontwarn org.openjsse.javax.net.ssl.SSLSocket
-dontwarn org.openjsse.net.ssl.OpenJSSE
-keepclassmembers class eu.siacs.conversations.http.services.** { -keepclassmembers class eu.siacs.conversations.http.services.** {
!transient <fields>; !transient <fields>;
} }

View File

@ -6,7 +6,6 @@ import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
import android.util.Log; import android.util.Log;
@ -30,6 +29,7 @@ import eu.siacs.conversations.databinding.ActivityImportBackupBinding;
import eu.siacs.conversations.databinding.DialogEnterPasswordBinding; import eu.siacs.conversations.databinding.DialogEnterPasswordBinding;
import eu.siacs.conversations.services.ImportBackupService; import eu.siacs.conversations.services.ImportBackupService;
import eu.siacs.conversations.ui.adapter.BackupFileAdapter; import eu.siacs.conversations.ui.adapter.BackupFileAdapter;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
public class ImportBackupActivity extends ActionBarActivity implements ServiceConnection, ImportBackupService.OnBackupFilesLoaded, BackupFileAdapter.OnItemClickedListener, ImportBackupService.OnBackupProcessed { public class ImportBackupActivity extends ActionBarActivity implements ServiceConnection, ImportBackupService.OnBackupFilesLoaded, BackupFileAdapter.OnItemClickedListener, ImportBackupService.OnBackupProcessed {
@ -56,6 +56,12 @@ public class ImportBackupActivity extends ActionBarActivity implements ServiceCo
this.backupFileAdapter.setOnItemClickedListener(this); this.backupFileAdapter.setOnItemClickedListener(this);
} }
@Override
protected void onResume(){
super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
}
@Override @Override
public boolean onCreateOptionsMenu(final Menu menu) { public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.import_backup, menu); getMenuInflater().inflate(R.menu.import_backup, menu);
@ -125,7 +131,8 @@ public class ImportBackupActivity extends ActionBarActivity implements ServiceCo
try { try {
final ImportBackupService.BackupFile backupFile = ImportBackupService.BackupFile.read(this, uri); final ImportBackupService.BackupFile backupFile = ImportBackupService.BackupFile.read(this, uri);
showEnterPasswordDialog(backupFile, finishOnCancel); showEnterPasswordDialog(backupFile, finishOnCancel);
} catch (IOException | IllegalArgumentException e) { } catch (final IOException | IllegalArgumentException e) {
Log.d(Config.LOGTAG, "unable to open backup file " + uri, e);
Snackbar.make(binding.coordinator, R.string.not_a_backup_file, Snackbar.LENGTH_LONG).show(); Snackbar.make(binding.coordinator, R.string.not_a_backup_file, Snackbar.LENGTH_LONG).show();
} }
} }
@ -181,6 +188,7 @@ public class ImportBackupActivity extends ActionBarActivity implements ServiceCo
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) { public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
if (requestCode == 0xbac) { if (requestCode == 0xbac) {
openBackupFileFromUri(intent.getData(), false); openBackupFileFromUri(intent.getData(), false);
@ -225,15 +233,17 @@ public class ImportBackupActivity extends ActionBarActivity implements ServiceCo
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_open_backup_file) { if (item.getItemId() == R.id.action_open_backup_file) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); openBackupFile();
intent.setType("*/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
}
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, getString(R.string.open_backup)), 0xbac);
return true; return true;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
private void openBackupFile() {
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, getString(R.string.open_backup)), 0xbac);
}
} }

View File

@ -228,6 +228,7 @@ public class ManageAccountActivity extends XmppActivity implements OnAccountUpda
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) { if (grantResults.length > 0) {
if (allGranted(grantResults)) { if (allGranted(grantResults)) {
switch (requestCode) { switch (requestCode) {

View File

@ -106,7 +106,8 @@ public class WelcomeActivity extends XmppActivity implements XmppConnectionServi
} }
@Override @Override
public void onNewIntent(Intent intent) { public void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
if (intent != null) { if (intent != null) {
setIntent(intent); setIntent(intent);
} }
@ -201,6 +202,7 @@ public class WelcomeActivity extends XmppActivity implements XmppConnectionServi
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults); UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
if (grantResults.length > 0) { if (grantResults.length > 0) {
if (allGranted(grantResults)) { if (allGranted(grantResults)) {

View File

@ -0,0 +1,11 @@
package eu.siacs.conversations.utils;
import android.content.Context;
import eu.siacs.conversations.xmpp.Jid;
public class PhoneNumberUtilWrapper {
public static String toFormattedPhoneNumber(Context context, Jid jid) {
throw new AssertionError("This method is not implemented in Conversations");
}
}

View File

@ -3,4 +3,18 @@
<string name="pick_a_server">اختر مزود خدمة XMPP الخاص بك</string> <string name="pick_a_server">اختر مزود خدمة XMPP الخاص بك</string>
<string name="use_chat.sum7.eu">استخدِم chat.sum7.eu</string> <string name="use_chat.sum7.eu">استخدِم chat.sum7.eu</string>
<string name="create_new_account">أنشئ حسابًا جديدًا</string> <string name="create_new_account">أنشئ حسابًا جديدًا</string>
<string name="do_you_have_an_account">هل تملك حساب XMPP؟؟ قد يكون ذلك ممكنا لو كنت تستعمل خدمة XMPP أخرى أو إستعملت تطبيق كونفرسايشنز سابقا. أو يمكنك صنع حساب XMPP جديد الآن.
ملاحظة: بعض خدمات البريد الإلكتروني تقدم حسابات XMPP.</string>
<string name="server_select_text">XMPP هي خدمة مستقلة للتواصل بشبكة الرسائل المباشرة. يمكنك إستعمال هذه الخدمة مع أي خادم XMPP تختاره.
سعيا لراحتك جعلنا خلق حساب في كونفيرسايشنز سهلا مع مقدم خدمة خاص بالإستعمال مع كونفيرسايشنز.</string>
<string name="magic_create_text_on_x">لقد تمت دعوتك لـ %1$s. سيتم دلّك على طريقة صنع حساب.
عندما تختار %1$sكمقدّم خدمة سيصبح من الممكن لك التواصل مع مستعملين من أي خادم آخر عن طريق إعطائهم عنوانك الكامل على XMPP.</string>
<string name="magic_create_text_fixed">تمّت دعوتك إلى %1$s. تم إختيار إسم مستخدم خاص بك. سيتم قيادتك عبر طريقة صنع حساب.
سيمكنك التواصل مع مستخدمين من مزودين آخرين عبر إعطائهم كامل عنوانك XMPP.</string>
<string name="your_server_invitation">سيرفر دعوتك</string>
<string name="improperly_formatted_provisioning">لم يتم التقاط الكود بطريقة جيّدة</string>
<string name="tap_share_button_send_invite">إضغط على زر مشاركة لترسل إلى المتصل بك دعوة إلى %1$s.</string>
<string name="if_contact_is_nearby_use_qr">إذا كان المتصل بك قريبا منك، يمكنه فحص الكود بالأسفل ليقبل دعوتك.</string>
<string name="easy_invite_share_text">إنظم %1$s وتحدّث معي: %2$s</string>
<string name="share_invite_with">شارك إستدعاء مع...</string>
</resources> </resources>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pick_a_server">XMPP সার্ভার নির্বাচন করুন</string>
<string name="use_chat.sum7.eu">chat.sum7.eu ব্যবহার করা যাক</string>
<string name="create_new_account">নতুন অ্যকাউন্ট তৈরী করা যাক</string>
<string name="do_you_have_an_account">আপনার কি একটা XMPP অ্যকাউন্ট ইতিমধ্যে করা আছে? সেরকমটা হতেই পারে যদি এর আগে আপনি কোনো অন্য XMPP প্রোগ্রাম বা অ্যাপ ব্যবহার করে থাকেন। এই মুহুর্তে আরেকটা অ্যকাউন্ট তৈরী করা সম্ভব না।‌\nHint: মাঝে মাঝে ইমেল অ্যকাউন্ট খুললেও এরকম অ্যকাউন্ট নিজে থেকেই তৈরী হয়ে যায়।</string>
<string name="server_select_text">XMPP কোনো একটি নির্দিষ্ট সংস্থার উপরে নির্ভরশীল নয়। এই অ্যপটি আপনি যেকোনো সংস্থার XMPP সার্ভারের সাথে ব্যবহার করতে পারেন।\nমনে রাখবেন, সুধুমাত্র আপনার সুবিধার্থেই chat.sum7.eu -এ আপনার জন্যে একটি অ্যকাউন্ট তৈরী করে দেওয়া হয়েছে। Conversations অ্যপটি এই সার্ভারের সাথে সবথেকে বেশী কার্যকারী।</string>
<string name="magic_create_text_on_x">আপনাকে %1$s-এ আমন্ত্রিত করা হয়েছে। অ্যকাউন্ট তৈরী করার সময় আপনাকে সাহায্য করা হবে।\n%1$s ব্যবহার করলেও, অন্য সেবা-প্রদানকারী সংস্থার ব্যবহারকারীদের সাথে আপনি কথা বলতে পারবেন, আপনার সম্পূর্ণ XMPP অ্যড্রেস তাদেরকে বলে দিয়ে।</string>
<string name="magic_create_text_fixed">আপনাকে %1$s-এ নিমন্ত্রণ করা হয়েছে। একটি username-ও আপনার জন্যে নির্দিষ্ট করে রাখা হয়েছে। অ্যকাউন্ট তৈরী করার সময় আপনাকে সাহায্য করা হবে।\nঅন্য XMPP সেবা প্রদানকারী সংস্থার ব্যবহারকারীদের সাথে আপনিও কথা বলতে পারবেন, আপনার সম্পূর্ণ XMPP অ্যড্রেস তাদেরকে বলে দিয়ে।</string>
<string name="your_server_invitation">আপনার নিমন্ত্রণপত্র, সার্ভার থেকে</string>
<string name="improperly_formatted_provisioning">Provisioning code-এ গরমিল আছে</string>
<string name="tap_share_button_send_invite">Share বোতামটা টিপে %1$s-কে একটি আমন্ত্রপত্র পাঠান</string>
<string name="if_contact_is_nearby_use_qr">পরিচিত ব্যক্তি যদি নিকটেই থাকেন, তাহলে তারা এই কোডটাও স্ক্যান করে নিতে পারেন</string>
<string name="easy_invite_share_text">%1$sতে এসো, আর আমার সাথে কথা বলো: %2$s</string>
<string name="share_invite_with">একটি আমন্ত্রণপত্র দেওয়া যাক...</string>
</resources>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pick_a_server">Vælg din XMPP-udbyder</string>
<string name="use_chat.sum7.eu">Brug chat.sum7.eu</string>
<string name="create_new_account">Opret ny konto</string>
<string name="do_you_have_an_account">Har du allerede en XMPP-konto? Dette kan være tilfældet, hvis du allerede bruger en anden XMPP-klient eller har brugt Conversations før. Hvis ikke, kan du lige nu oprette en ny XMPP-konto.\nTip: Nogle e-mail-udbydere leverer også XMPP-konti.</string>
<string name="server_select_text">XMPP er et udbyderuafhængigt onlinemeddelelsesnetværk. Du kan bruge denne klient med hvilken XMPP-server du end vælger.\nMen for din nemhedsskyld har vi gjort vi det let at oprette en konto på chat.sum7.eu; en udbyder, der er specielt velegnet til brug med Conversations.</string>
<string name="magic_create_text_on_x">Du er blevet inviteret til %1$s. Vi guider dig gennem processen med at oprette en konto.\nNår du vælger %1$s som udbyder, kan du kommunikere med brugere fra andre udbydere ved at give dem din fulde XMPP-adresse.</string>
<string name="magic_create_text_fixed">Du er blevet inviteret til %1$s. Der er allerede valgt et brugernavn til dig. Vi guider dig gennem processen med at oprette en konto.\nDu vil være i stand til at kommunikere med brugere fra andre udbydere ved at give dem din fulde XMPP-adresse.</string>
<string name="your_server_invitation">Din server invitation</string>
<string name="improperly_formatted_provisioning">Forkert formateret klargøringskode</string>
<string name="tap_share_button_send_invite">Tryk på deleknappen for at sende din kontakt en invitation til %1$s.</string>
<string name="if_contact_is_nearby_use_qr">Hvis din kontakt er i nærheden, kan de også skanne koden nedenfor for at acceptere din invitation.</string>
<string name="easy_invite_share_text">Deltag med %1$s og chat med mig: %2$s</string>
<string name="share_invite_with">Del invitation med...</string>
</resources>

View File

@ -9,4 +9,8 @@
<string name="magic_create_text_fixed">Έχετε προσκληθεί στο %1$s. Ένα όνομα χρήστη έχει ήδη επιλεγεί για εσάς. Θα σας καθοδηγήσουμε στη διαδικασία δημιουργίας λογαριασμού.\nΘα μπορείτε να επικοινωνείτε με χρήστες άλλων παρόχων δίνοντάς τους την πλήρη διεύθυνση XMPP σας.</string> <string name="magic_create_text_fixed">Έχετε προσκληθεί στο %1$s. Ένα όνομα χρήστη έχει ήδη επιλεγεί για εσάς. Θα σας καθοδηγήσουμε στη διαδικασία δημιουργίας λογαριασμού.\nΘα μπορείτε να επικοινωνείτε με χρήστες άλλων παρόχων δίνοντάς τους την πλήρη διεύθυνση XMPP σας.</string>
<string name="your_server_invitation">Η πρόσκλησή σας στον διακομιστή</string> <string name="your_server_invitation">Η πρόσκλησή σας στον διακομιστή</string>
<string name="improperly_formatted_provisioning">Λάθος μορφοποίηση κώδικα παροχής</string> <string name="improperly_formatted_provisioning">Λάθος μορφοποίηση κώδικα παροχής</string>
<string name="tap_share_button_send_invite">Πατήστε το πλήκτρο διαμοιρασμού για να στείλετε στην επαφή σας μια πρόσκληση στο %1$s.</string>
<string name="if_contact_is_nearby_use_qr">Αν η επαφή σας βρίσκεται κοντά σας, μπορεί επίσης να σαρώσει τον κωδικό παρακάτω για να αποδεχτεί την πρόσκλησή σας.</string>
<string name="easy_invite_share_text">Μπείτε στο %1$s και συνομιλήστε μαζί μου: %2$s</string>
<string name="share_invite_with">Διαμοιρασμός πρόσκλησης με...</string>
</resources> </resources>

View File

@ -9,4 +9,8 @@
<string name="magic_create_text_fixed">Vous avez été invité à %1$s. Un nom dutilisateur a déjà été choisi pour vous. Nous allons vous guider à travers le processus de création dun compte.\nVous pourrez communiquer avec les utilisateurs des autres fournisseurs en leur donnant votre adresse XMPP complète.</string> <string name="magic_create_text_fixed">Vous avez été invité à %1$s. Un nom dutilisateur a déjà été choisi pour vous. Nous allons vous guider à travers le processus de création dun compte.\nVous pourrez communiquer avec les utilisateurs des autres fournisseurs en leur donnant votre adresse XMPP complète.</string>
<string name="your_server_invitation">Votre invitation au serveur</string> <string name="your_server_invitation">Votre invitation au serveur</string>
<string name="improperly_formatted_provisioning">Code de provisionnement mal formaté</string> <string name="improperly_formatted_provisioning">Code de provisionnement mal formaté</string>
<string name="tap_share_button_send_invite">Appuyez sur le bouton partager pour envoyer à votre contact une invitation pour %1$s</string>
<string name="if_contact_is_nearby_use_qr">Si vos contacts sont à votre côté, ils peuvent aussi scanner le code ci dessous pour accepter votre invitation</string>
<string name="easy_invite_share_text">Rejoignez %1$set discutez avec moi : %2$s</string>
<string name="share_invite_with">Partager une invitation avec ...</string>
</resources> </resources>

View File

@ -9,4 +9,8 @@
<string name="magic_create_text_fixed">Meghívást kapott a(z) %1$s kiszolgálóra. Már kiválasztottak Önnek egy felhasználónevet. Végig fogjuk vezetni egy fiók létrehozásának folyamatán.\nKépes lesz más szolgáltatók felhasználóival is kommunikálni, ha megadja nekik a teljes XMPP-címét.</string> <string name="magic_create_text_fixed">Meghívást kapott a(z) %1$s kiszolgálóra. Már kiválasztottak Önnek egy felhasználónevet. Végig fogjuk vezetni egy fiók létrehozásának folyamatán.\nKépes lesz más szolgáltatók felhasználóival is kommunikálni, ha megadja nekik a teljes XMPP-címét.</string>
<string name="your_server_invitation">Az Ön kiszolgálómeghívása</string> <string name="your_server_invitation">Az Ön kiszolgálómeghívása</string>
<string name="improperly_formatted_provisioning">Helytelenül formázott kiépítési kód</string> <string name="improperly_formatted_provisioning">Helytelenül formázott kiépítési kód</string>
<string name="tap_share_button_send_invite">Koppintson a megosztás gombra, hogy meghívót küldjön a partnerének erre: %1$s.</string>
<string name="if_contact_is_nearby_use_qr">Ha a partnere a közelben van, akkor a meghívás elfogadásához leolvashatja a lenti kódot.</string>
<string name="easy_invite_share_text">Csatlakozzon ehhez: %1$s, és csevegjen velem: %2$s</string>
<string name="share_invite_with">Meghívás megosztása…</string>
</resources> </resources>

View File

@ -1,14 +1,14 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="pick_a_server">Scegli il tuo provider XMPP</string> <string name="pick_a_server">Scegli il tuo fornitore XMPP</string>
<string name="use_chat.sum7.eu">Usa chat.sum7.eu</string> <string name="use_chat.sum7.eu">Usa chat.sum7.eu</string>
<string name="create_new_account">Crea un nuovo account</string> <string name="create_new_account">Crea un nuovo profilo</string>
<string name="do_you_have_an_account">Possiedi già un account XMPP? Questo succede se stai già usando un diverso client XMPP o hai già usato prima Conversations. In caso negativo puoi creare un account XMPP adesso. <string name="do_you_have_an_account">Possiedi già un profilo XMPP? Questo succede se stai già usando un diverso client XMPP o hai già usato prima Conversations. In caso negativo puoi creare un profilo XMPP adesso.
Suggerimento: alcuni provider di email forniscono anche un account XMPP.</string> Suggerimento: alcuni provider di email forniscono anche un account XMPP.</string>
<string name="server_select_text">XMPP è una rete di instant messaging indipendente dal provider. Puoi usare questo client con qualsiasi server XMPP. <string name="server_select_text">XMPP è una rete di messaggistica istantanea indipendente dal fornitore. Puoi usare questo client con qualsiasi server XMPP.
In ogni caso per facilitare puoi creare facilmente un account su chat.sum7.eu, un provider pensato apposta per essere usato con Conversations.</string> In ogni caso per facilitare puoi creare facilmente un account su chat.sum7.eu, un fornitore pensato apposta per essere usato con Conversations.</string>
<string name="magic_create_text_on_x">Sei stato invitato su %1$s. Ti guideremo nel procedimento per creare un account.\nQuando scegli %1$s come fornitore sarai in grado di comunicare con utenti di altri fornitori dando loro l\'indirizzo XMPP completo.</string> <string name="magic_create_text_on_x">Hai ricevuto un invito per %1$s. Ti guideremo nel procedimento per creare un profilo.\nQuando scegli %1$s come fornitore sarai in grado di comunicare con utenti di altri fornitori dando loro l\'indirizzo XMPP completo.</string>
<string name="magic_create_text_fixed">Sei stato invitato su %1$s. È già stato scelto un nome utente per te. Ti guideremo nel procedimento per creare un account.\nSarai in grado di comunicare con utenti di altri fornitori dando loro l\'indirizzo XMPP completo.</string> <string name="magic_create_text_fixed">Hai ricevuto un invito per %1$s. È già stato scelto un nome utente per te. Ti guideremo nel procedimento per creare un profilo.\nSarai in grado di comunicare con utenti di altri fornitori dando loro l\'indirizzo XMPP completo.</string>
<string name="your_server_invitation">Il tuo invito al server</string> <string name="your_server_invitation">Il tuo invito al server</string>
<string name="improperly_formatted_provisioning">Codice di approvvigionamento formattato male</string> <string name="improperly_formatted_provisioning">Codice di approvvigionamento formattato male</string>
<string name="tap_share_button_send_invite">Tocca il pulsante condividi per inviare al contatto un invito per %1$s.</string> <string name="tap_share_button_send_invite">Tocca il pulsante condividi per inviare al contatto un invito per %1$s.</string>

View File

@ -2,11 +2,15 @@
<resources> <resources>
<string name="pick_a_server">XMPP プロバイダーを選択してください</string> <string name="pick_a_server">XMPP プロバイダーを選択してください</string>
<string name="use_chat.sum7.eu">chat.sum7.eu を利用する</string> <string name="use_chat.sum7.eu">chat.sum7.eu を利用する</string>
<string name="create_new_account">アカウントを作成</string> <string name="create_new_account">新規アカウントを作成</string>
<string name="do_you_have_an_account">XMPPアカウントをお持ちですか既にほかのXMPPクライアントを利用しているか、Conversationsを利用したことがある場合はこちら。初めての方は、今すぐ新しいXMPPアカウントを作成できます。\nヒント: eメールのプロバイダーがXMPPアカウントも提供している場合があります。</string> <string name="do_you_have_an_account">XMPP アカウントをお持ちですか?既にほかの XMPP クライアントを利用しているか、 Conversations を利用したことがある場合はこちら。初めての方は、今すぐ新規 XMPP アカウントを作成できます。\nヒント: e メールのプロバイダーが XMPP アカウントも提供している場合があります。</string>
<string name="server_select_text">XMPP は、プロバイダーに依存しないインスタントメッセージのプロトコルです。 XMPP サーバーならどこでも、このクライアントを使用することができます。\nよろしければ、 Conversations に最適化されたプロバイダー chat.sum7.eu で簡単にアカウントを作成することもできます。</string> <string name="server_select_text">XMPP は、プロバイダーに依存しないインスタントメッセージのプロトコルです。 XMPP サーバーならどこでも、このクライアントを使用することができます。\nよろしければ、 Conversations に最適化されたプロバイダー chat.sum7.eu で簡単にアカウントを作成することもできます。</string>
<string name="magic_create_text_on_x">%1$s へ招待されました。アカウント作成手順をご案内します。 \n%1$s をプロバイダーに選択してほかのプロバイダーのユーザーと会話するには、 XMPP のフルアドレスを相手にお知らせください。</string> <string name="magic_create_text_on_x">%1$s へ招待されました。アカウント作成手順をご案内します。 \n%1$s をプロバイダーに選択してほかのプロバイダーのユーザーと会話するには、 XMPP のフルアドレスを相手にお知らせください。</string>
<string name="magic_create_text_fixed">%1$sへ招待されました。ユーザーネームは既に選択されています。アカウント作成手順をご案内します。 \nほかのプロバイダーのユーザーと会話するには、XMPPのフルアドレスを相手にお知らせください。</string> <string name="magic_create_text_fixed">%1$s へ招待されました。ユーザー名は既に選択されています。アカウント作成手順をご案内します。 \nほかのプロバイダーのユーザーと会話するには、 XMPP のフルアドレスを相手にお知らせください。</string>
<string name="your_server_invitation">サーバーの招待</string> <string name="your_server_invitation">サーバーの招待</string>
<string name="improperly_formatted_provisioning">仮コードの書式が不正です</string> <string name="improperly_formatted_provisioning">仮コードの書式が不正です</string>
<string name="tap_share_button_send_invite">共有ボタンを叩いて、連絡先の %1$s に招待を送信する。</string>
<string name="if_contact_is_nearby_use_qr">あなたの連絡先が近くにいる場合は、下のコードをスキャンして、あなたの招待を受け取ることもできます。</string>
<string name="easy_invite_share_text">%1$s に参加して私とお話しましょう: %2$s</string>
<string name="share_invite_with">…で招待を共有</string>
</resources> </resources>

View File

@ -9,4 +9,8 @@
<string name="magic_create_text_fixed">Вас пригласили на %1$s. Вам уже назначили имя пользователя. Мы проведём вас через процесс создания аккаунта. Этот аккаунт позволит вам общаться с пользователями и на этом, и на других серверах, используя ваш полный XMPP-адрес.</string> <string name="magic_create_text_fixed">Вас пригласили на %1$s. Вам уже назначили имя пользователя. Мы проведём вас через процесс создания аккаунта. Этот аккаунт позволит вам общаться с пользователями и на этом, и на других серверах, используя ваш полный XMPP-адрес.</string>
<string name="your_server_invitation">Ваше приглашение</string> <string name="your_server_invitation">Ваше приглашение</string>
<string name="improperly_formatted_provisioning">Неправильный формат кода</string> <string name="improperly_formatted_provisioning">Неправильный формат кода</string>
<string name="tap_share_button_send_invite">Нажмите кнопку «Поделиться», чтобы отправить вашему контакту приглашение в %1$s.</string>
<string name="if_contact_is_nearby_use_qr">Если ваш контакт находится поблизости, он также может отсканировать приведенный ниже код, чтобы принять ваше приглашение.</string>
<string name="easy_invite_share_text">Присоединяйтесь к %1$s и пообщайтесь со мной: %2$s</string>
<string name="share_invite_with">Поделиться приглашением с…</string>
</resources> </resources>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pick_a_server">Vyberte si svojho XMPP poskytovateľa</string>
<string name="use_chat.sum7.eu">Použiť chat.sum7.eu</string>
<string name="create_new_account">Vytvoriť nové konto</string>
<string name="do_you_have_an_account">Máte už svoje XMPP konto? Môže to tak byť v prípade, že už používate iného klienta XMPP alebo ste predtým používali Conversations. Ak nie, môžete si vytvoriť nové XMPP konto práve teraz.\nHint: Niektorí poskytovatelia emailu zároveň poskytujú aj XMPP kontá.</string>
<string name="server_select_text">XMPP je sieť pre okamžité správy nezávislá od poskytovateľa. Tohto klienta môžete používať s akýmkoľvek XMPP serverom, ktorý si vyberiete..\nAvšak pre vaše pohodlie sme zjednodušili vytvorenie konta na chat.sum7.eu; poskytovateľ špeciálne vhodný na používanie s Conversations.</string>
<string name="magic_create_text_on_x">Boli ste pozvaný do %1$s. Prevedieme vás procesom vytvorenia konta..\nPo výbere %1$s ako poskytovateľa, budete môcť komunikovať s užívateľmi iných poskytovateľov tak, že im dáte vašu úplnú XMPP adresu.</string>
<string name="magic_create_text_fixed">Boli ste pozvaný do %1$s . Užívateľské meno vám už bolo vopred vybrané. Prevedieme vás procesom vytvorenia konta..\nBudete môcť komunikovať s užívateľmi iných poskytovateľov tak, že im dáte vašu úplnú XMPP adresu.</string>
<string name="tap_share_button_send_invite">Ťuknite na tlačidlo zdieľať na odoslanie pozvánky do %1$s vášmu kontaktu.</string>
<string name="if_contact_is_nearby_use_qr">Ak je váš kontakt blízko, na prijatie vašej pozvánky si môže nasnímať kód nižšie.</string>
<string name="easy_invite_share_text">Pripojte sa k %1$sa rozprávajte sa so mnou: %2$s</string>
<string name="share_invite_with">Zdieľať pozvánku s...</string>
</resources>

View File

@ -1,5 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="pick_a_server">Välj din XMPP leverantör</string>
<string name="use_chat.sum7.eu">Använd chat.sum7.eu</string> <string name="use_chat.sum7.eu">Använd chat.sum7.eu</string>
<string name="create_new_account">Skapa nytt konto</string> <string name="create_new_account">Skapa nytt konto</string>
<string name="your_server_invitation">Din server inbjudan</string>
<string name="share_invite_with">Dela inbjudan med...</string>
</resources> </resources>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pick_a_server">Chọn nhà cung cấp XMPP của bạn</string>
<string name="use_chat.sum7.eu">Sử dụng chat.sum7.eu</string>
<string name="create_new_account">Tạo tài khoản mới</string>
<string name="do_you_have_an_account">Bạn đã có tài khoản XMPP chưa? Điều này có thể đúng nếu bạn đang dùng một ứng dụng khách cho XMPP khác hoặc đã sử dụng Conversations trước đó. Nếu không, bạn có thể tạo tài khoản XMPP mới ngay bây giờ.\nGợi ý: Một số nhà cung cấp email cũng cung cấp tài khoản XMPP.</string>
<string name="server_select_text">XMPP là một mạng nhắn tin ngay lập tức không phụ thuộc vào nhà cung cấp. Bạn có thể sử dụng ứng dụng khách này với bất kỳ máy chủ XMPP nào mà bạn chọn.\nTuy nhiên, vì sự thuận tiện của bạn, chúng tôi đã làm cho việc tạo tài khoản trên chat.sum7.eu được dễ dàng; một nhà cung cấp đặc biệt phù hợp với việc sử dụng Conversations.</string>
<string name="magic_create_text_on_x">Bạn đã được mời vào %1$s. Chúng tôi sẽ hướng dẫn bạn trong quá trình tạo tài khoản.\nKhi chọn %1$s là nhà cung cấp, bạn sẽ có thể giao tiếp với những người dùng của các nhà cung cấp khác bằng cách đưa cho họ địa chỉ XMPP đầy đủ của bạn.</string>
<string name="magic_create_text_fixed">Bạn đã được mời vào %1$s. Một tên người dùng đã được chọn sẵn cho bạn. Chúng tôi sẽ hướng dẫn bạn trong quá trình tạo tài khoản.\nBạn sẽ có thể giao tiếp với những người dùng của các nhà cung cấp khác bằng cách đưa cho họ địa chỉ XMPP đầy đủ của bạn.</string>
<string name="your_server_invitation">Lời mời vào máy chủ của bạn</string>
<string name="improperly_formatted_provisioning">Mã cung cấp không được định dạng đúng</string>
<string name="tap_share_button_send_invite">Nhấn nút chia sẻ để gửi lời mời vào %1$s đến liên hệ của bạn.</string>
<string name="if_contact_is_nearby_use_qr">Nếu liên hệ của bạn ở gần đây, họ cũng có thể quét mã ở dưới để chấp nhận lời mời của bạn.</string>
<string name="easy_invite_share_text">Hãy tham gia vào %1$s và trò chuyện với tôi: %2$s</string>
<string name="share_invite_with">Chia sẻ lời mời với...</string>
</resources>

View File

@ -39,8 +39,6 @@
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" /> <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
<uses-feature <uses-feature
android:name="android.hardware.camera" android:name="android.hardware.camera"
android:required="false" /> android:required="false" />
@ -54,7 +52,8 @@
<application <application
android:allowBackup="false" android:allowBackup="true"
android:fullBackupContent="@xml/backup_content"
android:appCategory="social" android:appCategory="social"
android:hardwareAccelerated="true" android:hardwareAccelerated="true"
android:icon="@mipmap/new_launcher" android:icon="@mipmap/new_launcher"
@ -144,6 +143,14 @@
<data android:scheme="imto" /> <data android:scheme="imto" />
<data android:host="jabber" /> <data android:host="jabber" />
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="imto" />
<data android:host="xmpp" />
</intent-filter>
</activity> </activity>
<activity <activity
android:name=".ui.StartConversationActivity" android:name=".ui.StartConversationActivity"

View File

@ -3,9 +3,12 @@ package eu.siacs.conversations;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale;
import eu.siacs.conversations.crypto.XmppDomainVerifier;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
@ -33,7 +36,7 @@ public final class Config {
return (ENCRYPTION_MASK & (ENCRYPTION_MASK - 1)) != 0; return (ENCRYPTION_MASK & (ENCRYPTION_MASK - 1)) != 0;
} }
public static final String LOGTAG = BuildConfig.LOGTAG; public static final String LOGTAG = BuildConfig.APP_NAME.toLowerCase(Locale.US);
public static final Jid BUG_REPORTS = Jid.of("bugs@chat.sum7.eu"); public static final Jid BUG_REPORTS = Jid.of("bugs@chat.sum7.eu");
public static final Uri HELP = Uri.parse("https://sum7.eu/chat"); public static final Uri HELP = Uri.parse("https://sum7.eu/chat");
@ -101,6 +104,7 @@ public final class Config {
public static final boolean REMOVE_BROKEN_DEVICES = false; public static final boolean REMOVE_BROKEN_DEVICES = false;
public static final boolean OMEMO_PADDING = false; public static final boolean OMEMO_PADDING = false;
public static final boolean PUT_AUTH_TAG_INTO_KEY = true; public static final boolean PUT_AUTH_TAG_INTO_KEY = true;
public static final boolean AUTOMATICALLY_COMPLETE_SESSIONS = true;
public static final boolean USE_BOOKMARKS2 = false; public static final boolean USE_BOOKMARKS2 = false;
@ -114,6 +118,7 @@ public final class Config {
public static final boolean ENCRYPT_ON_HTTP_UPLOADED = false; public static final boolean ENCRYPT_ON_HTTP_UPLOADED = false;
public static final boolean X509_VERIFICATION = false; //use x509 certificates to verify OMEMO keys public static final boolean X509_VERIFICATION = false; //use x509 certificates to verify OMEMO keys
public static final boolean REQUIRE_RTP_VERIFICATION = false; //require a/v calls to be verified with OMEMO
public static final boolean ONLY_INTERNAL_STORAGE = false; //use internal storage instead of sdcard to save attachments public static final boolean ONLY_INTERNAL_STORAGE = false; //use internal storage instead of sdcard to save attachments
@ -173,7 +178,14 @@ public final class Config {
//if the contacts domain matches one of the following domains OMEMO wont be turned on automatically //if the contacts domain matches one of the following domains OMEMO wont be turned on automatically
//can be used for well known, widely used gateways //can be used for well known, widely used gateways
public static final List<String> CONTACT_DOMAINS = Collections.singletonList("cheogram.com"); private static final List<String> CONTACT_DOMAINS = Arrays.asList(
"cheogram.com",
"*.covid.monal.im"
);
public static boolean matchesContactDomain(final String domain) {
return XmppDomainVerifier.matchDomain(domain, CONTACT_DOMAINS);
}
} }
private Config() { private Config() {
@ -188,4 +200,9 @@ public final class Config {
public final static float LOCATION_FIX_SPACE_DELTA = 10; // m public final static float LOCATION_FIX_SPACE_DELTA = 10; // m
public final static int LOCATION_FIX_SIGNIFICANT_TIME_DELTA = 1000 * 60 * 2; // ms public final static int LOCATION_FIX_SIGNIFICANT_TIME_DELTA = 1000 * 60 * 2; // ms
} }
// How deep nested quotes should be displayed. '2' means one quote nested in another.
public static final int QUOTE_MAX_DEPTH = 7;
// How deep nested quotes should be created on quoting a message.
public static final int QUOTING_MAX_DEPTH = 1;
} }

View File

@ -17,6 +17,21 @@ import eu.siacs.conversations.xmpp.Jid;
public class JabberIdContact extends AbstractPhoneContact { public class JabberIdContact extends AbstractPhoneContact {
private static final String[] PROJECTION = new String[]{ContactsContract.Data._ID,
ContactsContract.Data.DISPLAY_NAME,
ContactsContract.Data.PHOTO_URI,
ContactsContract.Data.LOOKUP_KEY,
ContactsContract.CommonDataKinds.Im.DATA
};
private static final String SELECTION = ContactsContract.Data.MIMETYPE + "=? AND (" + ContactsContract.CommonDataKinds.Im.PROTOCOL + "=? or (" + ContactsContract.CommonDataKinds.Im.PROTOCOL + "=? and lower(" + ContactsContract.CommonDataKinds.Im.CUSTOM_PROTOCOL + ")=?))";
private static final String[] SELECTION_ARGS = {
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Im.PROTOCOL_JABBER),
String.valueOf(ContactsContract.CommonDataKinds.Im.PROTOCOL_CUSTOM),
"xmpp"
};
private final Jid jid; private final Jid jid;
private JabberIdContact(Cursor cursor) throws IllegalArgumentException { private JabberIdContact(Cursor cursor) throws IllegalArgumentException {
@ -36,38 +51,26 @@ public class JabberIdContact extends AbstractPhoneContact {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
return Collections.emptyMap(); return Collections.emptyMap();
} }
final String[] PROJECTION = new String[]{ContactsContract.Data._ID, try (final Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, null)) {
ContactsContract.Data.DISPLAY_NAME, if (cursor == null) {
ContactsContract.Data.PHOTO_URI,
ContactsContract.Data.LOOKUP_KEY,
ContactsContract.CommonDataKinds.Im.DATA};
final String SELECTION = "(" + ContactsContract.Data.MIMETYPE + "=\""
+ ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE
+ "\") AND (" + ContactsContract.CommonDataKinds.Im.PROTOCOL
+ "=\"" + ContactsContract.CommonDataKinds.Im.PROTOCOL_JABBER
+ "\")";
final Cursor cursor;
try {
cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, PROJECTION, SELECTION, null, null);
} catch (Exception e) {
return Collections.emptyMap(); return Collections.emptyMap();
} }
final HashMap<Jid, JabberIdContact> contacts = new HashMap<>(); final HashMap<Jid, JabberIdContact> contacts = new HashMap<>();
while (cursor != null && cursor.moveToNext()) { while (cursor.moveToNext()) {
try { try {
final JabberIdContact contact = new JabberIdContact(cursor); final JabberIdContact contact = new JabberIdContact(cursor);
final JabberIdContact preexisting = contacts.put(contact.getJid(), contact); final JabberIdContact preexisting = contacts.put(contact.getJid(), contact);
if (preexisting == null || preexisting.rating() < contact.rating()) { if (preexisting == null || preexisting.rating() < contact.rating()) {
contacts.put(contact.getJid(), contact); contacts.put(contact.getJid(), contact);
} }
} catch (IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
Log.d(Config.LOGTAG, "unable to create jabber id contact"); Log.d(Config.LOGTAG, "unable to create jabber id contact");
} }
} }
if (cursor != null) {
cursor.close();
}
return contacts; return contacts;
} catch (final Exception e) {
Log.d(Config.LOGTAG, "unable to query", e);
return Collections.emptyMap();
}
} }
} }

View File

@ -1,10 +1,11 @@
package eu.siacs.conversations.crypto; package eu.siacs.conversations.crypto;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
public interface DomainHostnameVerifier extends HostnameVerifier { public interface DomainHostnameVerifier extends HostnameVerifier {
boolean verify(String domain, String hostname, SSLSession sslSession); boolean verify(String domain, String hostname, SSLSession sslSession) throws SSLPeerUnverifiedException;
} }

View File

@ -14,7 +14,6 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -209,7 +208,7 @@ public class PgpDecryptionService {
message.setRelativeFilePath(path); message.setRelativeFilePath(path);
} }
} }
URL url = message.getFileParams().url; final String url = message.getFileParams().url;
mXmppConnectionService.getFileBackend().updateFileParams(message, url); mXmppConnectionService.getFileBackend().updateFileParams(message, url);
message.setEncryption(Message.ENCRYPTION_DECRYPTED); message.setEncryption(Message.ENCRYPTION_DECRYPTED);
mXmppConnectionService.updateMessage(message); mXmppConnectionService.updateMessage(message);

View File

@ -6,6 +6,10 @@ import android.util.Log;
import androidx.annotation.StringRes; import androidx.annotation.StringRes;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult; import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpApi;
@ -18,6 +22,7 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
@ -29,6 +34,7 @@ import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.UiCallback; import eu.siacs.conversations.ui.UiCallback;
import eu.siacs.conversations.utils.AsciiArmor;
public class PgpEngine { public class PgpEngine {
private final OpenPgpApi api; private final OpenPgpApi api;
@ -66,7 +72,7 @@ public class PgpEngine {
params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
String body; String body;
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
body = message.getFileParams().url.toString(); body = message.getFileParams().url;
} else { } else {
body = message.getBody(); body = message.getBody();
} }
@ -77,14 +83,14 @@ public class PgpEngine {
case OpenPgpApi.RESULT_CODE_SUCCESS: case OpenPgpApi.RESULT_CODE_SUCCESS:
try { try {
os.flush(); os.flush();
StringBuilder encryptedMessageBody = new StringBuilder(); final ArrayList<String> encryptedMessageBody = new ArrayList<>();
String[] lines = os.toString().split("\n"); final String[] lines = os.toString().split("\n");
for (int i = 2; i < lines.length - 1; ++i) { for (int i = 2; i < lines.length - 1; ++i) {
if (!lines[i].contains("Version")) { if (!lines[i].contains("Version")) {
encryptedMessageBody.append(lines[i].trim()); encryptedMessageBody.add(lines[i].trim());
} }
} }
message.setEncryptedBody(encryptedMessageBody.toString()); message.setEncryptedBody(Joiner.on('\n').join(encryptedMessageBody));
message.setEncryption(Message.ENCRYPTION_DECRYPTED); message.setEncryption(Message.ENCRYPTION_DECRYPTED);
mXmppConnectionService.sendMessage(message); mXmppConnectionService.sendMessage(message);
callback.success(message); callback.success(message);
@ -147,36 +153,26 @@ public class PgpEngine {
} }
} }
public long fetchKeyId(Account account, String status, String signature) { public long fetchKeyId(final Account account, final String status, final String signature) {
if ((signature == null) || (api == null)) { if (signature == null || api == null) {
return 0; return 0;
} }
if (status == null) { final Intent params = new Intent();
status = "";
}
final StringBuilder pgpSig = new StringBuilder();
pgpSig.append("-----BEGIN PGP SIGNED MESSAGE-----");
pgpSig.append('\n');
pgpSig.append('\n');
pgpSig.append(status);
pgpSig.append('\n');
pgpSig.append("-----BEGIN PGP SIGNATURE-----");
pgpSig.append('\n');
pgpSig.append('\n');
pgpSig.append(signature.replace("\n", "").trim());
pgpSig.append('\n');
pgpSig.append("-----END PGP SIGNATURE-----");
Intent params = new Intent();
params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY); params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true); try {
InputStream is = new ByteArrayInputStream(pgpSig.toString().getBytes()); params.putExtra(OpenPgpApi.RESULT_DETACHED_SIGNATURE, AsciiArmor.decode(signature));
ByteArrayOutputStream os = new ByteArrayOutputStream(); } catch (final Exception e) {
Intent result = api.executeApi(params, is, os); Log.d(Config.LOGTAG, "unable to parse signature", e);
return 0;
}
final InputStream is = new ByteArrayInputStream(Strings.nullToEmpty(status).getBytes());
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final Intent result = api.executeApi(params, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
OpenPgpApi.RESULT_CODE_ERROR)) { OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: case OpenPgpApi.RESULT_CODE_SUCCESS:
OpenPgpSignatureResult sigResult = result final OpenPgpSignatureResult sigResult = result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE); //TODO unsure that sigResult.getResult() is either 1, 2 or 3
if (sigResult != null) { if (sigResult != null) {
return sigResult.getKeyId(); return sigResult.getKeyId();
} else { } else {
@ -223,18 +219,17 @@ public class PgpEngine {
api.executeApiAsync(params, is, os, result -> { api.executeApiAsync(params, is, os, result -> {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) { switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: case OpenPgpApi.RESULT_CODE_SUCCESS:
StringBuilder signatureBuilder = new StringBuilder(); final ArrayList<String> signature = new ArrayList<>();
try { try {
os.flush(); os.flush();
String[] lines = os.toString().split("\n");
boolean sig = false; boolean sig = false;
for (String line : lines) { for (final String line : Splitter.on('\n').split(os.toString())) {
if (sig) { if (sig) {
if (line.contains("END PGP SIGNATURE")) { if (line.contains("END PGP SIGNATURE")) {
sig = false; sig = false;
} else { } else {
if (!line.contains("Version")) { if (!line.contains("Version")) {
signatureBuilder.append(line.trim()); signature.add(line.trim());
} }
} }
} }
@ -246,7 +241,7 @@ public class PgpEngine {
callback.error(R.string.openpgp_error, null); callback.error(R.string.openpgp_error, null);
return; return;
} }
callback.success(signatureBuilder.toString()); callback.success(Joiner.on('\n').join(signature));
return; return;
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
callback.userInputRequired(result.getParcelableExtra(OpenPgpApi.RESULT_INTENT), status); callback.userInputRequired(result.getParcelableExtra(OpenPgpApi.RESULT_INTENT), status);

View File

@ -1,9 +1,10 @@
package eu.siacs.conversations.crypto; package eu.siacs.conversations.crypto;
import android.os.Build;
import android.util.Log; import android.util.Log;
import android.util.Pair; import android.util.Pair;
import com.google.common.collect.ImmutableList;
import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DERTaggedObject;
@ -16,17 +17,20 @@ import org.bouncycastle.asn1.x500.style.IETFUtils;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import java.io.IOException; import java.io.IOException;
import java.net.IDN;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
public class XmppDomainVerifier implements DomainHostnameVerifier { public class XmppDomainVerifier {
private static final String LOGTAG = "XmppDomainVerifier"; private static final String LOGTAG = "XmppDomainVerifier";
@ -71,8 +75,8 @@ public class XmppDomainVerifier implements DomainHostnameVerifier {
} }
} }
private static boolean matchDomain(String needle, List<String> haystack) { public static boolean matchDomain(final String needle, final List<String> haystack) {
for (String entry : haystack) { for (final String entry : haystack) {
if (entry.startsWith("*.")) { if (entry.startsWith("*.")) {
int offset = 0; int offset = 0;
while (offset < needle.length()) { while (offset < needle.length()) {
@ -80,16 +84,13 @@ public class XmppDomainVerifier implements DomainHostnameVerifier {
if (i < 0) { if (i < 0) {
break; break;
} }
Log.d(LOGTAG, "comparing " + needle.substring(i) + " and " + entry.substring(1));
if (needle.substring(i).equalsIgnoreCase(entry.substring(1))) { if (needle.substring(i).equalsIgnoreCase(entry.substring(1))) {
Log.d(LOGTAG, "domain " + needle + " matched " + entry);
return true; return true;
} }
offset = i + 1; offset = i + 1;
} }
} else { } else {
if (entry.equalsIgnoreCase(needle)) { if (entry.equalsIgnoreCase(needle)) {
Log.d(LOGTAG, "domain " + needle + " matched " + entry);
return true; return true;
} }
} }
@ -97,25 +98,42 @@ public class XmppDomainVerifier implements DomainHostnameVerifier {
return false; return false;
} }
@Override public boolean verify(final String unicodeDomain, final String unicodeHostname, SSLSession sslSession) throws SSLPeerUnverifiedException {
public boolean verify(String domain, String hostname, SSLSession sslSession) { final String domain = IDN.toASCII(unicodeDomain);
try { final String hostname = unicodeHostname == null ? null : IDN.toASCII(unicodeHostname);
Certificate[] chain = sslSession.getPeerCertificates(); final Certificate[] chain = sslSession.getPeerCertificates();
if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) { if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) {
return false; return false;
} }
X509Certificate certificate = (X509Certificate) chain[0]; final X509Certificate certificate = (X509Certificate) chain[0];
final List<String> commonNames = getCommonNames(certificate); final List<String> commonNames = getCommonNames(certificate);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isSelfSigned(certificate)) { if (isSelfSigned(certificate)) {
if (commonNames.size() == 1 && matchDomain(domain, commonNames)) { if (commonNames.size() == 1 && matchDomain(domain, commonNames)) {
Log.d(LOGTAG, "accepted CN in self signed cert as work around for " + domain); Log.d(LOGTAG, "accepted CN in self signed cert as work around for " + domain);
return true; return true;
} }
} }
Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); try {
List<String> xmppAddrs = new ArrayList<>(); final ValidDomains validDomains = parseValidDomains(certificate);
List<String> srvNames = new ArrayList<>(); Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + validDomains.srvNames + " xmppAddrs: " + validDomains.xmppAddrs + " domains:" + validDomains.domains);
List<String> domains = new ArrayList<>(); if (hostname != null) {
Log.d(LOGTAG, "also trying to verify hostname " + hostname);
}
return validDomains.xmppAddrs.contains(domain)
|| validDomains.srvNames.contains("_xmpp-client." + domain)
|| matchDomain(domain, validDomains.domains)
|| (hostname != null && matchDomain(hostname, validDomains.domains));
} catch (final Exception e) {
return false;
}
}
public static ValidDomains parseValidDomains(final X509Certificate certificate) throws CertificateParsingException {
final List<String> commonNames = getCommonNames(certificate);
final Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
final List<String> xmppAddrs = new ArrayList<>();
final List<String> srvNames = new ArrayList<>();
final List<String> domains = new ArrayList<>();
if (alternativeNames != null) { if (alternativeNames != null) {
for (List<?> san : alternativeNames) { for (List<?> san : alternativeNames) {
final Integer type = (Integer) san.get(0); final Integer type = (Integer) san.get(0);
@ -144,16 +162,26 @@ public class XmppDomainVerifier implements DomainHostnameVerifier {
if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) { if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) {
domains.addAll(commonNames); domains.addAll(commonNames);
} }
Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains); return new ValidDomains(xmppAddrs, srvNames, domains);
if (hostname != null) {
Log.d(LOGTAG, "also trying to verify hostname " + hostname);
} }
return xmppAddrs.contains(domain)
|| srvNames.contains("_xmpp-client." + domain) public static final class ValidDomains {
|| matchDomain(domain, domains) final List<String> xmppAddrs;
|| (hostname != null && matchDomain(hostname, domains)); final List<String> srvNames;
} catch (Exception e) { final List<String> domains;
return false;
private ValidDomains(List<String> xmppAddrs, List<String> srvNames, List<String> domains) {
this.xmppAddrs = xmppAddrs;
this.srvNames = srvNames;
this.domains = domains;
}
public List<String> all() {
ImmutableList.Builder<String> all = new ImmutableList.Builder<>();
all.addAll(xmppAddrs);
all.addAll(srvNames);
all.addAll(domains);
return all.build();
} }
} }
@ -165,9 +193,4 @@ public class XmppDomainVerifier implements DomainHostnameVerifier {
return false; return false;
} }
} }
@Override
public boolean verify(String domain, SSLSession sslSession) {
return verify(domain, null, sslSession);
}
} }

View File

@ -8,6 +8,13 @@ import android.util.Pair;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.IdentityKey;
import org.whispersystems.libsignal.IdentityKeyPair; import org.whispersystems.libsignal.IdentityKeyPair;
@ -49,9 +56,15 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.SerialSingleThreadExecutor; import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded; import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jingle.OmemoVerification;
import eu.siacs.conversations.xmpp.jingle.OmemoVerifiedRtpContentMap;
import eu.siacs.conversations.xmpp.jingle.RtpContentMap;
import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
import eu.siacs.conversations.xmpp.jingle.stanzas.OmemoVerifiedIceUdpTransportInfo;
import eu.siacs.conversations.xmpp.pep.PublishOptions; import eu.siacs.conversations.xmpp.pep.PublishOptions;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket; import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
@ -725,16 +738,22 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
axolotlStore.setFingerprintStatus(fingerprint, status); axolotlStore.setFingerprintStatus(fingerprint, status);
} }
private void verifySessionWithPEP(final XmppAxolotlSession session) { private ListenableFuture<XmppAxolotlSession> verifySessionWithPEP(final XmppAxolotlSession session) {
Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep"); Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
final SignalProtocolAddress address = session.getRemoteAddress(); final SignalProtocolAddress address = session.getRemoteAddress();
final IdentityKey identityKey = session.getIdentityKey(); final IdentityKey identityKey = session.getIdentityKey();
final Jid jid;
try { try {
IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.of(address.getName()), address.getDeviceId()); jid = Jid.of(address.getName());
mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { } catch (final IllegalArgumentException e) {
@Override fetchStatusMap.put(address, FetchStatus.SUCCESS);
public void onIqPacketReceived(Account account, IqPacket packet) { finishBuildingSessionsFromPEP(address);
Pair<X509Certificate[], byte[]> verification = mXmppConnectionService.getIqParser().verification(packet); return Futures.immediateFuture(session);
}
final SettableFuture<XmppAxolotlSession> future = SettableFuture.create();
final IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(jid, address.getDeviceId());
mXmppConnectionService.sendIqPacket(account, packet, (account, response) -> {
Pair<X509Certificate[], byte[]> verification = mXmppConnectionService.getIqParser().verification(response);
if (verification != null) { if (verification != null) {
try { try {
Signature verifier = Signature.getInstance("sha256WithRSA"); Signature verifier = Signature.getInstance("sha256WithRSA");
@ -751,13 +770,14 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]); Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
try { try {
final String cn = information.getString("subject_cn"); final String cn = information.getString("subject_cn");
final Jid jid = Jid.of(address.getName()); final Jid jid1 = Jid.of(address.getName());
Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn); Log.d(Config.LOGTAG, "setting common name for " + jid1 + " to " + cn);
account.getRoster().getContact(jid).setCommonName(cn); account.getRoster().getContact(jid1).setCommonName(cn);
} catch (final IllegalArgumentException ignored) { } catch (final IllegalArgumentException ignored) {
//ignored //ignored
} }
finishBuildingSessionsFromPEP(address); finishBuildingSessionsFromPEP(address);
future.set(session);
return; return;
} catch (Exception e) { } catch (Exception e) {
Log.d(Config.LOGTAG, "could not verify certificate"); Log.d(Config.LOGTAG, "could not verify certificate");
@ -771,12 +791,9 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
fetchStatusMap.put(address, FetchStatus.SUCCESS); fetchStatusMap.put(address, FetchStatus.SUCCESS);
finishBuildingSessionsFromPEP(address); finishBuildingSessionsFromPEP(address);
} future.set(session);
}); });
} catch (IllegalArgumentException e) { return future;
fetchStatusMap.put(address, FetchStatus.SUCCESS);
finishBuildingSessionsFromPEP(address);
}
} }
private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) { private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
@ -892,22 +909,23 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
private void buildSessionFromPEP(final SignalProtocolAddress address) { private ListenableFuture<XmppAxolotlSession> buildSessionFromPEP(final SignalProtocolAddress address) {
buildSessionFromPEP(address, null); return buildSessionFromPEP(address, null);
} }
private void buildSessionFromPEP(final SignalProtocolAddress address, OnSessionBuildFromPep callback) { private ListenableFuture<XmppAxolotlSession> buildSessionFromPEP(final SignalProtocolAddress address, OnSessionBuildFromPep callback) {
final SettableFuture<XmppAxolotlSession> sessionSettableFuture = SettableFuture.create();
Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString()); Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
if (address.equals(getOwnAxolotlAddress())) { if (address.equals(getOwnAxolotlAddress())) {
throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!"); throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
} }
final Jid jid = Jid.of(address.getName()); final Jid jid = Jid.of(address.getName());
final boolean oneOfOurs = jid.asBareJid().equals(account.getJid().asBareJid()); final boolean oneOfOurs = jid.asBareJid().equals(account.getJid().asBareJid());
IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(jid, address.getDeviceId()); IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(jid, address.getDeviceId());
mXmppConnectionService.sendIqPacket(account, bundlesPacket, (account, packet) -> { mXmppConnectionService.sendIqPacket(account, bundlesPacket, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.TIMEOUT) { if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
fetchStatusMap.put(address, FetchStatus.TIMEOUT); fetchStatusMap.put(address, FetchStatus.TIMEOUT);
sessionSettableFuture.setException(new CryptoFailedException("Unable to build session. Timeout"));
} else if (packet.getType() == IqPacket.TYPE.RESULT) { } else if (packet.getType() == IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing..."); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
final IqParser parser = mXmppConnectionService.getIqParser(); final IqParser parser = mXmppConnectionService.getIqParser();
@ -920,6 +938,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callback.onSessionBuildFailed(); callback.onSessionBuildFailed();
} }
sessionSettableFuture.setException(new CryptoFailedException("Unable to build session. IQ Packet Invalid"));
return; return;
} }
Random random = new Random(); Random random = new Random();
@ -931,6 +950,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callback.onSessionBuildFailed(); callback.onSessionBuildFailed();
} }
sessionSettableFuture.setException(new CryptoFailedException("Unable to build session. No suitable PreKey found"));
return; return;
} }
@ -945,7 +965,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey()); XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
sessions.put(address, session); sessions.put(address, session);
if (Config.X509_VERIFICATION) { if (Config.X509_VERIFICATION) {
verifySessionWithPEP(session); //TODO; maybe inject callback in here too sessionSettableFuture.setFuture(verifySessionWithPEP(session)); //TODO; maybe inject callback in here too
} else { } else {
FingerprintStatus status = getFingerprintTrust(CryptoHelper.bytesToHex(bundle.getIdentityKey().getPublicKey().serialize())); FingerprintStatus status = getFingerprintTrust(CryptoHelper.bytesToHex(bundle.getIdentityKey().getPublicKey().serialize()));
FetchStatus fetchStatus; FetchStatus fetchStatus;
@ -961,6 +981,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callback.onSessionBuildSuccessful(); callback.onSessionBuildSuccessful();
} }
sessionSettableFuture.set(session);
} }
} catch (UntrustedIdentityException | InvalidKeyException e) { } catch (UntrustedIdentityException | InvalidKeyException e) {
Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": " Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
@ -973,6 +994,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callback.onSessionBuildFailed(); callback.onSessionBuildFailed();
} }
sessionSettableFuture.setException(new CryptoFailedException(e));
} }
} else { } else {
fetchStatusMap.put(address, FetchStatus.ERROR); fetchStatusMap.put(address, FetchStatus.ERROR);
@ -986,8 +1008,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
if (callback != null) { if (callback != null) {
callback.onSessionBuildFailed(); callback.onSessionBuildFailed();
} }
sessionSettableFuture.setException(new CryptoFailedException("Unable to build session. IQ Packet Error"));
} }
}); });
return sessionSettableFuture;
} }
private void removeFromDeviceAnnouncement(Integer id) { private void removeFromDeviceAnnouncement(Integer id) {
@ -1161,7 +1185,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId()); final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
final String content; final String content;
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
content = message.getFileParams().url.toString(); content = message.getFileParams().url;
} else { } else {
content = message.getBody(); content = message.getBody();
} }
@ -1198,6 +1222,154 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
}); });
} }
private OmemoVerifiedIceUdpTransportInfo encrypt(final IceUdpTransportInfo element, final XmppAxolotlSession session) throws CryptoFailedException {
final OmemoVerifiedIceUdpTransportInfo transportInfo = new OmemoVerifiedIceUdpTransportInfo();
transportInfo.setAttributes(element.getAttributes());
for (final Element child : element.getChildren()) {
if ("fingerprint".equals(child.getName()) && Namespace.JINGLE_APPS_DTLS.equals(child.getNamespace())) {
final Element fingerprint = new Element("fingerprint", Namespace.OMEMO_DTLS_SRTP_VERIFICATION);
fingerprint.setAttribute("setup", child.getAttribute("setup"));
fingerprint.setAttribute("hash", child.getAttribute("hash"));
final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
final String content = child.getContent();
axolotlMessage.encrypt(content);
axolotlMessage.addDevice(session, true);
fingerprint.addChild(axolotlMessage.toElement());
transportInfo.addChild(fingerprint);
} else {
transportInfo.addChild(child);
}
}
return transportInfo;
}
public ListenableFuture<OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> encrypt(final RtpContentMap rtpContentMap, final Jid jid, final int deviceId) {
return Futures.transformAsync(
getSession(jid, deviceId),
session -> encrypt(rtpContentMap, session),
MoreExecutors.directExecutor()
);
}
private ListenableFuture<OmemoVerifiedPayload<OmemoVerifiedRtpContentMap>> encrypt(final RtpContentMap rtpContentMap, final XmppAxolotlSession session) {
if (Config.REQUIRE_RTP_VERIFICATION) {
requireVerification(session);
}
final ImmutableMap.Builder<String, RtpContentMap.DescriptionTransport> descriptionTransportBuilder = new ImmutableMap.Builder<>();
final OmemoVerification omemoVerification = new OmemoVerification();
omemoVerification.setDeviceId(session.getRemoteAddress().getDeviceId());
omemoVerification.setSessionFingerprint(session.getFingerprint());
for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : rtpContentMap.contents.entrySet()) {
final RtpContentMap.DescriptionTransport descriptionTransport = content.getValue();
final OmemoVerifiedIceUdpTransportInfo encryptedTransportInfo;
try {
encryptedTransportInfo = encrypt(descriptionTransport.transport, session);
} catch (final CryptoFailedException e) {
return Futures.immediateFailedFuture(e);
}
descriptionTransportBuilder.put(
content.getKey(),
new RtpContentMap.DescriptionTransport(descriptionTransport.description, encryptedTransportInfo)
);
}
return Futures.immediateFuture(
new OmemoVerifiedPayload<>(
omemoVerification,
new OmemoVerifiedRtpContentMap(rtpContentMap.group, descriptionTransportBuilder.build())
));
}
private ListenableFuture<XmppAxolotlSession> getSession(final Jid jid, final int deviceId) {
final SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
final XmppAxolotlSession session = sessions.get(address);
if (session == null) {
return buildSessionFromPEP(address);
}
return Futures.immediateFuture(session);
}
public ListenableFuture<OmemoVerifiedPayload<RtpContentMap>> decrypt(OmemoVerifiedRtpContentMap omemoVerifiedRtpContentMap, final Jid from) {
final ImmutableMap.Builder<String, RtpContentMap.DescriptionTransport> descriptionTransportBuilder = new ImmutableMap.Builder<>();
final OmemoVerification omemoVerification = new OmemoVerification();
final ImmutableList.Builder<ListenableFuture<XmppAxolotlSession>> pepVerificationFutures = new ImmutableList.Builder<>();
for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : omemoVerifiedRtpContentMap.contents.entrySet()) {
final RtpContentMap.DescriptionTransport descriptionTransport = content.getValue();
final OmemoVerifiedPayload<IceUdpTransportInfo> decryptedTransport;
try {
decryptedTransport = decrypt((OmemoVerifiedIceUdpTransportInfo) descriptionTransport.transport, from, pepVerificationFutures);
} catch (CryptoFailedException e) {
return Futures.immediateFailedFuture(e);
}
omemoVerification.setOrEnsureEqual(decryptedTransport);
descriptionTransportBuilder.put(
content.getKey(),
new RtpContentMap.DescriptionTransport(descriptionTransport.description, decryptedTransport.payload)
);
}
processPostponed();
final ImmutableList<ListenableFuture<XmppAxolotlSession>> sessionFutures = pepVerificationFutures.build();
return Futures.transform(
Futures.allAsList(sessionFutures),
sessions -> {
if (Config.REQUIRE_RTP_VERIFICATION) {
for (XmppAxolotlSession session : sessions) {
requireVerification(session);
}
}
return new OmemoVerifiedPayload<>(
omemoVerification,
new RtpContentMap(omemoVerifiedRtpContentMap.group, descriptionTransportBuilder.build())
);
},
MoreExecutors.directExecutor()
);
}
private OmemoVerifiedPayload<IceUdpTransportInfo> decrypt(final OmemoVerifiedIceUdpTransportInfo verifiedIceUdpTransportInfo, final Jid from, ImmutableList.Builder<ListenableFuture<XmppAxolotlSession>> pepVerificationFutures) throws CryptoFailedException {
final IceUdpTransportInfo transportInfo = new IceUdpTransportInfo();
transportInfo.setAttributes(verifiedIceUdpTransportInfo.getAttributes());
final OmemoVerification omemoVerification = new OmemoVerification();
for (final Element child : verifiedIceUdpTransportInfo.getChildren()) {
if ("fingerprint".equals(child.getName()) && Namespace.OMEMO_DTLS_SRTP_VERIFICATION.equals(child.getNamespace())) {
final Element fingerprint = new Element("fingerprint", Namespace.JINGLE_APPS_DTLS);
fingerprint.setAttribute("setup", child.getAttribute("setup"));
fingerprint.setAttribute("hash", child.getAttribute("hash"));
final Element encrypted = child.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(encrypted, from.asBareJid());
final XmppAxolotlSession session = getReceivingSession(xmppAxolotlMessage);
final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintext = xmppAxolotlMessage.decrypt(session, getOwnDeviceId());
final Integer preKeyId = session.getPreKeyIdAndReset();
if (preKeyId != null) {
postponedSessions.add(session);
}
if (session.isFresh()) {
pepVerificationFutures.add(putFreshSession(session));
} else if (Config.REQUIRE_RTP_VERIFICATION) {
pepVerificationFutures.add(Futures.immediateFuture(session));
}
fingerprint.setContent(plaintext.getPlaintext());
omemoVerification.setDeviceId(session.getRemoteAddress().getDeviceId());
omemoVerification.setSessionFingerprint(plaintext.getFingerprint());
transportInfo.addChild(fingerprint);
} else {
transportInfo.addChild(child);
}
}
return new OmemoVerifiedPayload<>(omemoVerification, transportInfo);
}
private static void requireVerification(final XmppAxolotlSession session) {
if (session.getTrust().isVerified()) {
return;
}
throw new NotVerifiedException(String.format(
"session with %s was not verified",
session.getFingerprint()
));
}
public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) { public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
executor.execute(new Runnable() { executor.execute(new Runnable() {
@Override @Override
@ -1318,7 +1490,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} else { } else {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": nothing to flush. Not republishing key"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": nothing to flush. Not republishing key");
} }
if (trustedOrPreviouslyResponded(session)) { if (trustedOrPreviouslyResponded(session) && Config.AUTOMATICALLY_COMPLETE_SESSIONS) {
completeSession(session); completeSession(session);
} }
} }
@ -1333,7 +1505,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
final Iterator<XmppAxolotlSession> iterator = postponedSessions.iterator(); final Iterator<XmppAxolotlSession> iterator = postponedSessions.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
final XmppAxolotlSession session = iterator.next(); final XmppAxolotlSession session = iterator.next();
if (trustedOrPreviouslyResponded(session)) { if (trustedOrPreviouslyResponded(session) && Config.AUTOMATICALLY_COMPLETE_SESSIONS) {
completeSession(session); completeSession(session);
} }
iterator.remove(); iterator.remove();
@ -1395,15 +1567,16 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
return keyTransportMessage; return keyTransportMessage;
} }
private void putFreshSession(XmppAxolotlSession session) { private ListenableFuture<XmppAxolotlSession> putFreshSession(XmppAxolotlSession session) {
sessions.put(session); sessions.put(session);
if (Config.X509_VERIFICATION) { if (Config.X509_VERIFICATION) {
if (session.getIdentityKey() != null) { if (session.getIdentityKey() != null) {
verifySessionWithPEP(session); return verifySessionWithPEP(session);
} else { } else {
Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": identity key was empty after reloading for x509 verification"); Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": identity key was empty after reloading for x509 verification");
} }
} }
return Futures.immediateFuture(session);
} }
public enum FetchStatus { public enum FetchStatus {
@ -1565,4 +1738,36 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
} }
public static class OmemoVerifiedPayload<T> {
private final int deviceId;
private final String fingerprint;
private final T payload;
private OmemoVerifiedPayload(OmemoVerification omemoVerification, T payload) {
this.deviceId = omemoVerification.getDeviceId();
this.fingerprint = omemoVerification.getFingerprint();
this.payload = payload;
}
public int getDeviceId() {
return deviceId;
}
public String getFingerprint() {
return fingerprint;
}
public T getPayload() {
return payload;
}
}
public static class NotVerifiedException extends SecurityException {
public NotVerifiedException(String message) {
super(message);
}
}
} }

View File

@ -59,7 +59,7 @@ public class XmppAxolotlMessage {
switch (keyElement.getName()) { switch (keyElement.getName()) {
case KEYTAG: case KEYTAG:
try { try {
Integer recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID)); int recipientId = Integer.parseInt(keyElement.getAttribute(REMOTEID));
byte[] key = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT); byte[] key = Base64.decode(keyElement.getContent().trim(), Base64.DEFAULT);
boolean isPreKey = keyElement.getAttributeAsBoolean("prekey"); boolean isPreKey = keyElement.getAttributeAsBoolean("prekey");
this.keys.add(new XmppAxolotlSession.AxolotlKey(recipientId, key, isPreKey)); this.keys.add(new XmppAxolotlSession.AxolotlKey(recipientId, key, isPreKey));
@ -145,7 +145,7 @@ public class XmppAxolotlMessage {
return ciphertext != null; return ciphertext != null;
} }
void encrypt(String plaintext) throws CryptoFailedException { void encrypt(final String plaintext) throws CryptoFailedException {
try { try {
SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE); SecretKey secretKey = new SecretKeySpec(innerKey, KEYTYPE);
IvParameterSpec ivSpec = new IvParameterSpec(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv);

View File

@ -4,7 +4,8 @@ import android.content.ContentValues;
import android.database.Cursor; import android.database.Cursor;
import android.os.SystemClock; import android.os.SystemClock;
import android.util.Log; import android.util.Log;
import android.util.Pair;
import com.google.common.base.Strings;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -64,7 +65,6 @@ public class Account extends AbstractEntity implements AvatarService.Avatarable
public static final int OPTION_FIXED_USERNAME = 9; public static final int OPTION_FIXED_USERNAME = 9;
private static final String KEY_PGP_SIGNATURE = "pgp_signature"; private static final String KEY_PGP_SIGNATURE = "pgp_signature";
private static final String KEY_PGP_ID = "pgp_id"; private static final String KEY_PGP_ID = "pgp_id";
public final HashSet<Pair<String, String>> inProgressDiscoFetches = new HashSet<>();
protected final JSONObject keys; protected final JSONObject keys;
private final Roster roster = new Roster(this); private final Roster roster = new Roster(this);
private final Collection<Jid> blocklist = new CopyOnWriteArraySet<>(); private final Collection<Jid> blocklist = new CopyOnWriteArraySet<>();
@ -148,7 +148,7 @@ public class Account extends AbstractEntity implements AvatarService.Avatarable
} }
public boolean httpUploadAvailable(long filesize) { public boolean httpUploadAvailable(long filesize) {
return xmppConnection != null && (xmppConnection.getFeatures().httpUpload(filesize) || xmppConnection.getFeatures().p1S3FileTransfer()); return xmppConnection != null && xmppConnection.getFeatures().httpUpload(filesize);
} }
public boolean httpUploadAvailable() { public boolean httpUploadAvailable() {
@ -249,7 +249,7 @@ public class Account extends AbstractEntity implements AvatarService.Avatarable
} }
public String getHostname() { public String getHostname() {
return this.hostname == null ? "" : this.hostname; return Strings.nullToEmpty(this.hostname);
} }
public void setHostname(String hostname) { public void setHostname(String hostname) {
@ -637,6 +637,7 @@ public class Account extends AbstractEntity implements AvatarService.Avatarable
REGISTRATION_INVALID_TOKEN(true,false), REGISTRATION_INVALID_TOKEN(true,false),
REGISTRATION_PASSWORD_TOO_WEAK(true, false), REGISTRATION_PASSWORD_TOO_WEAK(true, false),
TLS_ERROR, TLS_ERROR,
TLS_ERROR_DOMAIN,
INCOMPATIBLE_SERVER, INCOMPATIBLE_SERVER,
TOR_NOT_AVAILABLE, TOR_NOT_AVAILABLE,
DOWNGRADE_ATTACK, DOWNGRADE_ATTACK,
@ -703,6 +704,8 @@ public class Account extends AbstractEntity implements AvatarService.Avatarable
return R.string.account_status_regis_invalid_token; return R.string.account_status_regis_invalid_token;
case TLS_ERROR: case TLS_ERROR:
return R.string.account_status_tls_error; return R.string.account_status_tls_error;
case TLS_ERROR_DOMAIN:
return R.string.account_status_tls_error_domain;
case INCOMPATIBLE_SERVER: case INCOMPATIBLE_SERVER:
return R.string.account_status_incompatible_server; return R.string.account_status_incompatible_server;
case TOR_NOT_AVAILABLE: case TOR_NOT_AVAILABLE:

View File

@ -588,8 +588,7 @@ public class Contact implements ListItem, Blockable {
} }
public RtpCapability.Capability getRtpCapability() { public RtpCapability.Capability getRtpCapability() {
return this.rtpCapability == null ? RtpCapability.Capability.NONE : this.rtpCapability;
return this.rtpCapability;
} }
public static final class Options { public static final class Options {

View File

@ -28,6 +28,7 @@ import eu.siacs.conversations.persistance.DatabaseBackend;
import eu.siacs.conversations.services.AvatarService; import eu.siacs.conversations.services.AvatarService;
import eu.siacs.conversations.services.QuickConversationsService; import eu.siacs.conversations.services.QuickConversationsService;
import eu.siacs.conversations.utils.JidHelper; import eu.siacs.conversations.utils.JidHelper;
import eu.siacs.conversations.utils.MessageUtils;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.chatstate.ChatState;
@ -143,7 +144,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
} }
final String contact = conversation.getJid().getDomain().toEscapedString(); final String contact = conversation.getJid().getDomain().toEscapedString();
final String account = conversation.getAccount().getServer(); final String account = conversation.getAccount().getServer();
if (Config.OMEMO_EXCEPTIONS.CONTACT_DOMAINS.contains(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) { if (Config.OMEMO_EXCEPTIONS.matchesContactDomain(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) {
return false; return false;
} }
return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false); return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false);
@ -258,9 +259,22 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
public Message findMessageWithFileAndUuid(final String uuid) { public Message findMessageWithFileAndUuid(final String uuid) {
synchronized (this.messages) { synchronized (this.messages) {
for (final Message message : this.messages) { for (final Message message : this.messages) {
final Transferable transferable = message.getTransferable();
final boolean unInitiatedButKnownSize = MessageUtils.unInitiatedButKnownSize(message);
if (message.getUuid().equals(uuid) if (message.getUuid().equals(uuid)
&& message.getEncryption() != Message.ENCRYPTION_PGP && message.getEncryption() != Message.ENCRYPTION_PGP
&& (message.isFileOrImage() || message.treatAsDownloadable())) { && (message.isFileOrImage() || message.treatAsDownloadable() || unInitiatedButKnownSize || (transferable != null && transferable.getStatus() != Transferable.STATUS_UPLOADING))) {
return message;
}
}
}
return null;
}
public Message findMessageWithUuid(final String uuid) {
synchronized (this.messages) {
for (final Message message : this.messages) {
if (message.getUuid().equals(uuid)) {
return message; return message;
} }
} }
@ -788,7 +802,7 @@ public class Conversation extends AbstractEntity implements Blockable, Comparabl
if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) { if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) {
String otherBody; String otherBody;
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
otherBody = message.getFileParams().url.toString(); otherBody = message.getFileParams().url;
} else { } else {
otherBody = message.body; otherBody = message.body;
} }

View File

@ -8,12 +8,11 @@ import android.util.Log;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Longs;
import org.json.JSONException; import org.json.JSONException;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -22,6 +21,7 @@ import java.util.concurrent.CopyOnWriteArraySet;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.crypto.axolotl.FingerprintStatus; import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
import eu.siacs.conversations.http.URL;
import eu.siacs.conversations.services.AvatarService; import eu.siacs.conversations.services.AvatarService;
import eu.siacs.conversations.ui.util.PresenceSelector; import eu.siacs.conversations.ui.util.PresenceSelector;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
@ -547,7 +547,7 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
} else { } else {
String body, otherBody; String body, otherBody;
if (this.hasFileOnRemoteHost()) { if (this.hasFileOnRemoteHost()) {
body = getFileParams().url.toString(); body = getFileParams().url;
otherBody = message.body == null ? null : message.body.trim(); otherBody = message.body == null ? null : message.body.trim();
} else { } else {
body = this.body; body = this.body;
@ -794,12 +794,11 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
if (relativeFilePath != null) { if (relativeFilePath != null) {
extension = MimeUtils.extractRelevantExtension(relativeFilePath); extension = MimeUtils.extractRelevantExtension(relativeFilePath);
} else { } else {
try { final String url = URL.tryParse(body.split("\n")[0]);
final URL url = new URL(body.split("\n")[0]); if (url == null) {
extension = MimeUtils.extractRelevantExtension(url);
} catch (MalformedURLException e) {
return null; return null;
} }
extension = MimeUtils.extractRelevantExtension(url);
} }
return MimeUtils.guessMimeTypeFromExtension(extension); return MimeUtils.guessMimeTypeFromExtension(extension);
} }
@ -840,8 +839,8 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
case 1: case 1:
try { try {
fileParams.size = Long.parseLong(parts[0]); fileParams.size = Long.parseLong(parts[0]);
} catch (NumberFormatException e) { } catch (final NumberFormatException e) {
fileParams.url = parseUrl(parts[0]); fileParams.url = URL.tryParse(parts[0]);
} }
break; break;
case 5: case 5:
@ -850,11 +849,11 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
fileParams.width = parseInt(parts[2]); fileParams.width = parseInt(parts[2]);
fileParams.height = parseInt(parts[3]); fileParams.height = parseInt(parts[3]);
case 2: case 2:
fileParams.url = parseUrl(parts[0]); fileParams.url = URL.tryParse(parts[0]);
fileParams.size = parseLong(parts[1]); fileParams.size = Longs.tryParse(parts[1]);
break; break;
case 3: case 3:
fileParams.size = parseLong(parts[0]); fileParams.size = Longs.tryParse(parts[0]);
fileParams.width = parseInt(parts[1]); fileParams.width = parseInt(parts[1]);
fileParams.height = parseInt(parts[2]); fileParams.height = parseInt(parts[2]);
break; break;
@ -863,14 +862,6 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
return fileParams; return fileParams;
} }
private static long parseLong(String value) {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return 0;
}
}
private static int parseInt(String value) { private static int parseInt(String value) {
try { try {
return Integer.parseInt(value); return Integer.parseInt(value);
@ -879,14 +870,6 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
} }
} }
private static URL parseUrl(String value) {
try {
return new URL(value);
} catch (MalformedURLException e) {
return null;
}
}
public void untie() { public void untie() {
this.mNextMessage = null; this.mNextMessage = null;
this.mPreviousMessage = null; this.mPreviousMessage = null;
@ -900,6 +883,11 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
return type == TYPE_FILE || type == TYPE_IMAGE || type == TYPE_PRIVATE_FILE; return type == TYPE_FILE || type == TYPE_IMAGE || type == TYPE_PRIVATE_FILE;
} }
public boolean isTypeText() {
return type == TYPE_TEXT || type == TYPE_PRIVATE;
}
public boolean hasFileOnRemoteHost() { public boolean hasFileOnRemoteHost() {
return isFileOrImage() && getFileParams().url != null; return isFileOrImage() && getFileParams().url != null;
} }
@ -908,12 +896,16 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
return isFileOrImage() && getFileParams().url == null; return isFileOrImage() && getFileParams().url == null;
} }
public class FileParams { public static class FileParams {
public URL url; public String url;
public long size = 0; public Long size = null;
public int width = 0; public int width = 0;
public int height = 0; public int height = 0;
public int runtime = 0; public int runtime = 0;
public long getSize() {
return size == null ? 0 : size;
}
} }
public void setFingerprint(String fingerprint) { public void setFingerprint(String fingerprint) {
@ -992,13 +984,28 @@ public class Message extends AbstractEntity implements AvatarService.Avatarable
} }
if (conversation.getMode() == Conversation.MODE_MULTI) { if (conversation.getMode() == Conversation.MODE_MULTI) {
final Jid nextCounterpart = conversation.getNextCounterpart(); final Jid nextCounterpart = conversation.getNextCounterpart();
if (nextCounterpart != null) { return configurePrivateMessage(conversation, message, nextCounterpart, isFile);
message.setCounterpart(nextCounterpart); }
message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart)); return false;
}
public static boolean configurePrivateMessage(final Message message, final Jid counterpart) {
final Conversation conversation;
if (message.conversation instanceof Conversation) {
conversation = (Conversation) message.conversation;
} else {
return false;
}
return configurePrivateMessage(conversation, message, counterpart, false);
}
private static boolean configurePrivateMessage(final Conversation conversation, final Message message, final Jid counterpart, final boolean isFile) {
if (counterpart == null) {
return false;
}
message.setCounterpart(counterpart);
message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart));
message.setType(isFile ? Message.TYPE_PRIVATE_FILE : Message.TYPE_PRIVATE); message.setType(isFile ? Message.TYPE_PRIVATE_FILE : Message.TYPE_PRIVATE);
return true; return true;
} }
} }
return false;
}
}

View File

@ -22,7 +22,7 @@ public interface Transferable {
int getStatus(); int getStatus();
long getFileSize(); Long getFileSize();
int getProgress(); int getProgress();

View File

@ -18,8 +18,8 @@ public class TransferablePlaceholder implements Transferable {
} }
@Override @Override
public long getFileSize() { public Long getFileSize() {
return 0; return null;
} }
@Override @Override

View File

@ -12,6 +12,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
import eu.siacs.conversations.BuildConfig;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.AxolotlService;
@ -65,7 +66,6 @@ public abstract class AbstractGenerator {
Namespace.JINGLE_MESSAGE Namespace.JINGLE_MESSAGE
}; };
protected XmppConnectionService mXmppConnectionService; protected XmppConnectionService mXmppConnectionService;
private String mVersion = null;
AbstractGenerator(XmppConnectionService service) { AbstractGenerator(XmppConnectionService service) {
this.mXmppConnectionService = service; this.mXmppConnectionService = service;
@ -77,18 +77,11 @@ public abstract class AbstractGenerator {
} }
String getIdentityVersion() { String getIdentityVersion() {
if (mVersion == null) { return BuildConfig.VERSION_NAME;
this.mVersion = PhoneHelper.getVersionName(mXmppConnectionService);
}
return this.mVersion;
} }
String getIdentityName() { String getIdentityName() {
return mXmppConnectionService.getString(R.string.app_name); return BuildConfig.APP_NAME;
}
public String getUserAgent() {
return mXmppConnectionService.getString(R.string.app_name) + '/' + getIdentityVersion();
} }
String getIdentityType() { String getIdentityType() {

View File

@ -408,20 +408,6 @@ public class IqGenerator extends AbstractGenerator {
return packet; return packet;
} }
public IqPacket requestP1S3Slot(Jid host, String md5) {
IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
packet.setTo(host);
packet.query(Namespace.P1_S3_FILE_TRANSFER).setAttribute("md5", md5);
return packet;
}
public IqPacket requestP1S3Url(Jid host, String fileId) {
IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
packet.setTo(host);
packet.query(Namespace.P1_S3_FILE_TRANSFER).setAttribute("fileid", fileId);
return packet;
}
private static String convertFilename(String name) { private static String convertFilename(String name) {
int pos = name.indexOf('.'); int pos = name.indexOf('.');
if (pos != -1) { if (pos != -1) {

View File

@ -1,6 +1,5 @@
package eu.siacs.conversations.generator; package eu.siacs.conversations.generator;
import java.net.URL;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -14,7 +13,6 @@ import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Conversational; import eu.siacs.conversations.entities.Conversational;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.http.P1S3UrlStreamHandler;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
@ -103,18 +101,9 @@ public class MessageGenerator extends AbstractGenerator {
MessagePacket packet = preparePacket(message); MessagePacket packet = preparePacket(message);
String content; String content;
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
Message.FileParams fileParams = message.getFileParams(); final Message.FileParams fileParams = message.getFileParams();
final URL url = fileParams.url; content = fileParams.url;
if (P1S3UrlStreamHandler.PROTOCOL_NAME.equals(url.getProtocol())) {
Element x = packet.addChild("x", Namespace.P1_S3_FILE_TRANSFER);
final String file = url.getFile();
x.setAttribute("name", file.charAt(0) == '/' ? file.substring(1) : file);
x.setAttribute("fileid", url.getHost());
return packet;
} else {
content = url.toString();
packet.addChild("x", Namespace.OOB).addChild("url").setContent(content); packet.addChild("x", Namespace.OOB).addChild("url").setContent(content);
}
} else { } else {
content = message.getBody(); content = message.getBody();
} }
@ -126,16 +115,9 @@ public class MessageGenerator extends AbstractGenerator {
MessagePacket packet = preparePacket(message); MessagePacket packet = preparePacket(message);
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
Message.FileParams fileParams = message.getFileParams(); Message.FileParams fileParams = message.getFileParams();
final URL url = fileParams.url; final String url = fileParams.url;
if (P1S3UrlStreamHandler.PROTOCOL_NAME.equals(url.getProtocol())) { packet.setBody(url);
Element x = packet.addChild("x", Namespace.P1_S3_FILE_TRANSFER); packet.addChild("x", Namespace.OOB).addChild("url").setContent(url);
final String file = url.getFile();
x.setAttribute("name", file.charAt(0) == '/' ? file.substring(1) : file);
x.setAttribute("fileid", url.getHost());
} else {
packet.setBody(url.toString());
packet.addChild("x", Namespace.OOB).addChild("url").setContent(url.toString());
}
} else { } else {
if (Config.supportUnencrypted()) { if (Config.supportUnencrypted()) {
packet.setBody(PGP_FALLBACK_MESSAGE); packet.setBody(PGP_FALLBACK_MESSAGE);

View File

@ -25,12 +25,19 @@ public class PresenceGenerator extends AbstractGenerator {
return packet; return packet;
} }
public PresencePacket requestPresenceUpdatesFrom(Contact contact) { public PresencePacket requestPresenceUpdatesFrom(final Contact contact) {
return requestPresenceUpdatesFrom(contact, null);
}
public PresencePacket requestPresenceUpdatesFrom(final Contact contact, final String preAuth) {
PresencePacket packet = subscription("subscribe", contact); PresencePacket packet = subscription("subscribe", contact);
String displayName = contact.getAccount().getDisplayName(); String displayName = contact.getAccount().getDisplayName();
if (!TextUtils.isEmpty(displayName)) { if (!TextUtils.isEmpty(displayName)) {
packet.addChild("nick", Namespace.NICK).setContent(displayName); packet.addChild("nick", Namespace.NICK).setContent(displayName);
} }
if (preAuth != null) {
packet.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
}
return packet; return packet;
} }

View File

@ -0,0 +1,41 @@
package eu.siacs.conversations.http;
import java.util.regex.Pattern;
import okhttp3.HttpUrl;
public final class AesGcmURL {
/**
* This matches a 48 or 44 byte IV + KEY hex combo, like used in http/aesgcm upload anchors
*/
public static final Pattern IV_KEY = Pattern.compile("([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44}");
public static final String PROTOCOL_NAME = "aesgcm";
private AesGcmURL() {
}
public static String toAesGcmUrl(HttpUrl url) {
if (url.isHttps()) {
return PROTOCOL_NAME + url.toString().substring(5);
} else {
return url.toString();
}
}
public static HttpUrl of(final String url) {
final int end = url.indexOf("://");
if (end < 0) {
throw new IllegalArgumentException("Scheme not found");
}
final String protocol = url.substring(0, end);
if (PROTOCOL_NAME.equals(protocol)) {
return HttpUrl.get("https" + url.substring(PROTOCOL_NAME.length()));
} else {
return HttpUrl.get(url);
}
}
}

View File

@ -1,23 +0,0 @@
package eu.siacs.conversations.http;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.regex.Pattern;
public class AesGcmURLStreamHandler extends URLStreamHandler {
/**
* This matches a 48 or 44 byte IV + KEY hex combo, like used in http/aesgcm upload anchors
*/
public static final Pattern IV_KEY = Pattern.compile("([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44}");
public static final String PROTOCOL_NAME = "aesgcm";
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new URL("https"+url.toString().substring(url.getProtocol().length())).openConnection();
}
}

View File

@ -1,18 +0,0 @@
package eu.siacs.conversations.http;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
public class CustomURLStreamHandlerFactory implements URLStreamHandlerFactory {
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if (AesGcmURLStreamHandler.PROTOCOL_NAME.equals(protocol)) {
return new AesGcmURLStreamHandler();
} else if (P1S3UrlStreamHandler.PROTOCOL_NAME.equals(protocol)) {
return new P1S3UrlStreamHandler();
} else {
return null;
}
}
}

View File

@ -1,42 +1,81 @@
package eu.siacs.conversations.http; package eu.siacs.conversations.http;
import android.os.Build;
import android.util.Log; import android.util.Log;
import org.apache.http.conn.ssl.StrictHostnameVerifier; import org.apache.http.conn.ssl.StrictHostnameVerifier;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.UnknownHostException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import eu.siacs.conversations.BuildConfig;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.AbstractConnectionManager; import eu.siacs.conversations.services.AbstractConnectionManager;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.TLSSocketFactory; import eu.siacs.conversations.utils.TLSSocketFactory;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
public class HttpConnectionManager extends AbstractConnectionManager { public class HttpConnectionManager extends AbstractConnectionManager {
private final List<HttpDownloadConnection> downloadConnections = new ArrayList<>(); private final List<HttpDownloadConnection> downloadConnections = new ArrayList<>();
private final List<HttpUploadConnection> uploadConnections = new ArrayList<>(); private final List<HttpUploadConnection> uploadConnections = new ArrayList<>();
public static final Executor EXECUTOR = Executors.newFixedThreadPool(4);
public static final OkHttpClient OK_HTTP_CLIENT;
static {
OK_HTTP_CLIENT = new OkHttpClient.Builder()
.addInterceptor(chain -> {
final Request original = chain.request();
final Request modified = original.newBuilder()
.header("User-Agent", getUserAgent())
.build();
return chain.proceed(modified);
})
.build();
}
public static String getUserAgent() {
return String.format("%s/%s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME);
}
public HttpConnectionManager(XmppConnectionService service) { public HttpConnectionManager(XmppConnectionService service) {
super(service); super(service);
} }
public static Proxy getProxy() throws IOException { public static Proxy getProxy() {
return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getByAddress(new byte[]{127, 0, 0, 1}), 9050)); final InetAddress localhost;
try {
localhost = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
} catch (final UnknownHostException e) {
throw new IllegalStateException(e);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(localhost, 9050));
} else {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(localhost, 8118));
}
} }
public void createNewDownloadConnection(Message message) { public void createNewDownloadConnection(Message message) {
@ -71,15 +110,6 @@ public class HttpConnectionManager extends AbstractConnectionManager {
} }
} }
public boolean checkConnection(Message message) {
final Account account = message.getConversation().getAccount();
final URL url = message.getFileParams().url;
if (url.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME) && account.getStatus() != Account.State.ONLINE) {
return false;
}
return mXmppConnectionService.hasInternetConnection();
}
void finishConnection(HttpDownloadConnection connection) { void finishConnection(HttpDownloadConnection connection) {
synchronized (this.downloadConnections) { synchronized (this.downloadConnections) {
this.downloadConnections.remove(connection); this.downloadConnections.remove(connection);
@ -92,9 +122,25 @@ public class HttpConnectionManager extends AbstractConnectionManager {
} }
} }
void setupTrustManager(final HttpsURLConnection connection, final boolean interactive) { OkHttpClient buildHttpClient(final HttpUrl url, final Account account, boolean interactive) {
return buildHttpClient(url, account, 30, interactive);
}
OkHttpClient buildHttpClient(final HttpUrl url, final Account account, int readTimeout, boolean interactive) {
final String slotHostname = url.host();
final boolean onionSlot = slotHostname.endsWith(".onion");
final OkHttpClient.Builder builder = OK_HTTP_CLIENT.newBuilder();
builder.writeTimeout(30, TimeUnit.SECONDS);
builder.readTimeout(readTimeout, TimeUnit.SECONDS);
setupTrustManager(builder, interactive);
if (mXmppConnectionService.useTorToConnect() || account.isOnion() || onionSlot) {
builder.proxy(HttpConnectionManager.getProxy()).build();
}
return builder.build();
}
private void setupTrustManager(final OkHttpClient.Builder builder, final boolean interactive) {
final X509TrustManager trustManager; final X509TrustManager trustManager;
final HostnameVerifier hostnameVerifier = mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier(), interactive);
if (interactive) { if (interactive) {
trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive(); trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive();
} else { } else {
@ -102,9 +148,27 @@ public class HttpConnectionManager extends AbstractConnectionManager {
} }
try { try {
final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[]{trustManager}, mXmppConnectionService.getRNG()); final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[]{trustManager}, mXmppConnectionService.getRNG());
connection.setSSLSocketFactory(sf); builder.sslSocketFactory(sf, trustManager);
connection.setHostnameVerifier(hostnameVerifier); builder.hostnameVerifier(new StrictHostnameVerifier());
} catch (final KeyManagementException | NoSuchAlgorithmException ignored) { } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
} }
} }
public static InputStream open(final String url, final boolean tor) throws IOException {
return open(HttpUrl.get(url), tor);
}
public static InputStream open(final HttpUrl httpUrl, final boolean tor) throws IOException {
final OkHttpClient.Builder builder = OK_HTTP_CLIENT.newBuilder();
if (tor) {
builder.proxy(HttpConnectionManager.getProxy()).build();
}
final OkHttpClient client = builder.build();
final Request request = new Request.Builder().get().url(httpUrl).build();
final ResponseBody body = client.newCall(request).execute().body();
if (body == null) {
throw new IOException("No response body found");
}
return body.byteStream();
}
} }

View File

@ -1,29 +1,23 @@
package eu.siacs.conversations.http; package eu.siacs.conversations.http;
import android.os.PowerManager;
import android.util.Log; import android.util.Log;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import com.google.common.primitives.Longs;
import java.io.BufferedInputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.util.Locale;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CancellationException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.Transferable; import eu.siacs.conversations.entities.Transferable;
@ -33,28 +27,30 @@ import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.FileWriterException; import eu.siacs.conversations.utils.FileWriterException;
import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.utils.MimeUtils;
import eu.siacs.conversations.utils.WakeLockHelper; import okhttp3.Call;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static eu.siacs.conversations.http.HttpConnectionManager.EXECUTOR;
public class HttpDownloadConnection implements Transferable { public class HttpDownloadConnection implements Transferable {
private final Message message; private final Message message;
private final boolean mUseTor;
private final HttpConnectionManager mHttpConnectionManager; private final HttpConnectionManager mHttpConnectionManager;
private final XmppConnectionService mXmppConnectionService; private final XmppConnectionService mXmppConnectionService;
private URL mUrl; private HttpUrl mUrl;
private DownloadableFile file; private DownloadableFile file;
private int mStatus = Transferable.STATUS_UNKNOWN; private int mStatus = Transferable.STATUS_UNKNOWN;
private boolean acceptedAutomatically = false; private boolean acceptedAutomatically = false;
private int mProgress = 0; private int mProgress = 0;
private boolean canceled = false; private Call mostRecentCall;
private Method method = Method.HTTP_UPLOAD;
HttpDownloadConnection(Message message, HttpConnectionManager manager) { HttpDownloadConnection(Message message, HttpConnectionManager manager) {
this.message = message; this.message = message;
this.mHttpConnectionManager = manager; this.mHttpConnectionManager = manager;
this.mXmppConnectionService = manager.getXmppConnectionService(); this.mXmppConnectionService = manager.getXmppConnectionService();
this.mUseTor = mXmppConnectionService.useTorToConnect();
} }
@Override @Override
@ -86,13 +82,13 @@ public class HttpDownloadConnection implements Transferable {
try { try {
final Message.FileParams fileParams = message.getFileParams(); final Message.FileParams fileParams = message.getFileParams();
if (message.hasFileOnRemoteHost()) { if (message.hasFileOnRemoteHost()) {
mUrl = CryptoHelper.toHttpsUrl(fileParams.url); mUrl = AesGcmURL.of(fileParams.url);
} else if (message.isOOb() && fileParams.url != null && fileParams.size > 0) { } else if (message.isOOb() && fileParams.url != null && fileParams.size != null) {
mUrl = fileParams.url; mUrl = AesGcmURL.of(fileParams.url);
} else { } else {
mUrl = CryptoHelper.toHttpsUrl(new URL(message.getBody().split("\n")[0])); mUrl = AesGcmURL.of(message.getBody().split("\n")[0]);
} }
final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.getPath()); final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.encodedPath());
if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) { if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) {
this.message.setEncryption(Message.ENCRYPTION_PGP); this.message.setEncryption(Message.ENCRYPTION_PGP);
} else if (message.getEncryption() != Message.ENCRYPTION_OTR } else if (message.getEncryption() != Message.ENCRYPTION_OTR
@ -109,22 +105,23 @@ public class HttpDownloadConnection implements Transferable {
if (this.message.getEncryption() == Message.ENCRYPTION_AXOLOTL && this.file.getKey() == null) { if (this.message.getEncryption() == Message.ENCRYPTION_AXOLOTL && this.file.getKey() == null) {
this.message.setEncryption(Message.ENCRYPTION_NONE); this.message.setEncryption(Message.ENCRYPTION_NONE);
} }
method = mUrl.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME) ? Method.P1_S3 : Method.HTTP_UPLOAD; //TODO add auth tag size to knownFileSize
long knownFileSize = message.getFileParams().size; final Long knownFileSize = message.getFileParams().size;
if (knownFileSize > 0 && interactive && method != Method.P1_S3) { Log.d(Config.LOGTAG,"knownFileSize: "+knownFileSize+", body="+message.getBody());
if (knownFileSize != null && interactive) {
this.file.setExpectedSize(knownFileSize); this.file.setExpectedSize(knownFileSize);
download(true); download(true);
} else { } else {
checkFileSize(interactive); checkFileSize(interactive);
} }
} catch (MalformedURLException e) { } catch (final IllegalArgumentException e) {
this.cancel(); this.cancel();
} }
} }
private void setupFile() { private void setupFile() {
final String reference = mUrl.getRef(); final String reference = mUrl.fragment();
if (reference != null && AesGcmURLStreamHandler.IV_KEY.matcher(reference).matches()) { if (reference != null && AesGcmURL.IV_KEY.matcher(reference).matches()) {
this.file = new DownloadableFile(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + message.getUuid()); this.file = new DownloadableFile(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + message.getUuid());
this.file.setKeyAndIv(CryptoHelper.hexToBytes(reference)); this.file.setKeyAndIv(CryptoHelper.hexToBytes(reference));
Log.d(Config.LOGTAG, "create temporary OMEMO encrypted file: " + this.file.getAbsolutePath() + "(" + message.getMimeType() + ")"); Log.d(Config.LOGTAG, "create temporary OMEMO encrypted file: " + this.file.getAbsolutePath() + "(" + message.getMimeType() + ")");
@ -133,17 +130,20 @@ public class HttpDownloadConnection implements Transferable {
} }
} }
private void download(boolean interactive) { private void download(final boolean interactive) {
new Thread(new FileDownloader(interactive)).start(); EXECUTOR.execute(new FileDownloader(interactive));
} }
private void checkFileSize(boolean interactive) { private void checkFileSize(final boolean interactive) {
new Thread(new FileSizeChecker(interactive)).start(); EXECUTOR.execute(new FileSizeChecker(interactive));
} }
@Override @Override
public void cancel() { public void cancel() {
this.canceled = true; final Call call = this.mostRecentCall;
if (call != null && !call.isCanceled()) {
call.cancel();
}
mHttpConnectionManager.finishConnection(this); mHttpConnectionManager.finishConnection(this);
message.setTransferable(null); message.setTransferable(null);
if (message.isFileOrImage()) { if (message.isFileOrImage()) {
@ -207,14 +207,19 @@ public class HttpDownloadConnection implements Transferable {
mHttpConnectionManager.updateConversationUi(true); mHttpConnectionManager.updateConversationUi(true);
} }
private void showToastForException(Exception e) { private void showToastForException(final Exception e) {
final Call call = mostRecentCall;
final boolean cancelled = call != null && call.isCanceled();
if (e == null || cancelled) {
return;
}
if (e instanceof java.net.UnknownHostException) { if (e instanceof java.net.UnknownHostException) {
mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found); mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
} else if (e instanceof java.net.ConnectException) { } else if (e instanceof java.net.ConnectException) {
mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect); mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
} else if (e instanceof FileWriterException) { } else if (e instanceof FileWriterException) {
mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file); mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file);
} else if (!(e instanceof CancellationException)) { } else {
mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found); mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
} }
} }
@ -230,11 +235,11 @@ public class HttpDownloadConnection implements Transferable {
} }
@Override @Override
public long getFileSize() { public Long getFileSize() {
if (this.file != null) { if (this.file != null) {
return this.file.getExpectedSize(); return this.file.getExpectedSize();
} else { } else {
return 0; return null;
} }
} }
@ -258,41 +263,13 @@ public class HttpDownloadConnection implements Transferable {
@Override @Override
public void run() { public void run() {
if (mUrl.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME)) {
retrieveUrl();
} else {
check(); check();
} }
}
private void retrieveUrl() { private void retrieveFailed(@Nullable final Exception e) {
changeStatus(STATUS_CHECKING);
final Account account = message.getConversation().getAccount();
IqPacket request = mXmppConnectionService.getIqGenerator().requestP1S3Url(account.getDomain(), mUrl.getHost());
mXmppConnectionService.sendIqPacket(message.getConversation().getAccount(), request, (a, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) {
String download = packet.query().getAttribute("download");
if (download != null) {
try {
mUrl = new URL(download);
check();
return;
} catch (MalformedURLException e) {
//fallthrough
}
}
}
Log.d(Config.LOGTAG, "unable to retrieve actual download url");
retrieveFailed(null);
});
}
private void retrieveFailed(@Nullable Exception e) {
changeStatus(STATUS_OFFER_CHECK_FILESIZE); changeStatus(STATUS_OFFER_CHECK_FILESIZE);
if (interactive) { if (interactive) {
if (e != null) {
showToastForException(e); showToastForException(e);
}
} else { } else {
HttpDownloadConnection.this.acceptedAutomatically = false; HttpDownloadConnection.this.acceptedAutomatically = false;
HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message); HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
@ -304,7 +281,7 @@ public class HttpDownloadConnection implements Transferable {
long size; long size;
try { try {
size = retrieveFileSize(); size = retrieveFileSize();
} catch (Exception e) { } catch (final Exception e) {
Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage()); Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
retrieveFailed(e); retrieveFailed(e);
return; return;
@ -328,46 +305,24 @@ public class HttpDownloadConnection implements Transferable {
} }
private long retrieveFileSize() throws IOException { private long retrieveFileSize() throws IOException {
try {
Log.d(Config.LOGTAG, "retrieve file size. interactive:" + interactive); Log.d(Config.LOGTAG, "retrieve file size. interactive:" + interactive);
changeStatus(STATUS_CHECKING); changeStatus(STATUS_CHECKING);
HttpURLConnection connection; final OkHttpClient client = mHttpConnectionManager.buildHttpClient(
final String hostname = mUrl.getHost(); mUrl,
final boolean onion = hostname != null && hostname.endsWith(".onion"); message.getConversation().getAccount(),
if (mUseTor || message.getConversation().getAccount().isOnion() || onion) { interactive
connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy()); );
} else { final Request request = new Request.Builder()
connection = (HttpURLConnection) mUrl.openConnection(); .url(URL.stripFragment(mUrl))
} .head()
if (method == Method.P1_S3) { .build();
connection.setRequestMethod("GET"); mostRecentCall = client.newCall(request);
connection.addRequestProperty("Range", "bytes=0-0"); try {
} else { final Response response = mostRecentCall.execute();
connection.setRequestMethod("HEAD"); throwOnInvalidCode(response);
} final String contentLength = response.header("Content-Length");
connection.setUseCaches(false); final String contentType = response.header("Content-Type");
Log.d(Config.LOGTAG, "url: " + connection.getURL().toString()); final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.encodedPath());
connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
if (connection instanceof HttpsURLConnection) {
mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
}
connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
connection.connect();
String contentLength;
if (method == Method.P1_S3) {
String contentRange = connection.getHeaderField("Content-Range");
String[] contentRangeParts = contentRange == null ? new String[0] : contentRange.split("/");
if (contentRangeParts.length != 2) {
contentLength = null;
} else {
contentLength = contentRangeParts[1];
}
} else {
contentLength = connection.getHeaderField("Content-Length");
}
final String contentType = connection.getContentType();
final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.getPath());
if (Strings.isNullOrEmpty(extension.getExtension()) && contentType != null) { if (Strings.isNullOrEmpty(extension.getExtension()) && contentType != null) {
final String fileExtension = MimeUtils.guessExtensionFromMimeType(contentType); final String fileExtension = MimeUtils.guessExtensionFromMimeType(contentType);
if (fileExtension != null) { if (fileExtension != null) {
@ -376,11 +331,14 @@ public class HttpDownloadConnection implements Transferable {
setupFile(); setupFile();
} }
} }
connection.disconnect(); if (Strings.isNullOrEmpty(contentLength)) {
if (contentLength == null) {
throw new IOException("no content-length found in HEAD response"); throw new IOException("no content-length found in HEAD response");
} }
return Long.parseLong(contentLength, 10); final long size = Long.parseLong(contentLength, 10);
if (size < 0) {
throw new IOException("Server reported negative file size");
}
return size;
} catch (IOException e) { } catch (IOException e) {
Log.d(Config.LOGTAG, "io exception during HEAD " + e.getMessage()); Log.d(Config.LOGTAG, "io exception during HEAD " + e.getMessage());
throw e; throw e;
@ -395,8 +353,6 @@ public class HttpDownloadConnection implements Transferable {
private final boolean interactive; private final boolean interactive;
private OutputStream os;
public FileDownloader(boolean interactive) { public FileDownloader(boolean interactive) {
this.interactive = interactive; this.interactive = interactive;
} }
@ -409,9 +365,10 @@ public class HttpDownloadConnection implements Transferable {
decryptIfNeeded(); decryptIfNeeded();
updateImageBounds(); updateImageBounds();
finish(); finish();
} catch (SSLHandshakeException e) { } catch (final SSLHandshakeException e) {
changeStatus(STATUS_OFFER); changeStatus(STATUS_OFFER);
} catch (Exception e) { } catch (final Exception e) {
Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": unable to download file", e);
if (interactive) { if (interactive) {
showToastForException(e); showToastForException(e);
} else { } else {
@ -423,108 +380,84 @@ public class HttpDownloadConnection implements Transferable {
} }
private void download() throws Exception { private void download() throws Exception {
InputStream is = null; final OkHttpClient client = mHttpConnectionManager.buildHttpClient(
HttpURLConnection connection = null; mUrl,
PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_download_" + message.getUuid()); message.getConversation().getAccount(),
try { interactive
wakeLock.acquire(); );
if (mUseTor || message.getConversation().getAccount().isOnion()) {
connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy()); final Request.Builder requestBuilder = new Request.Builder().url(URL.stripFragment(mUrl));
} else {
connection = (HttpURLConnection) mUrl.openConnection();
}
if (connection instanceof HttpsURLConnection) {
mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
}
connection.setUseCaches(false);
connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
final long expected = file.getExpectedSize(); final long expected = file.getExpectedSize();
final boolean tryResume = file.exists() && file.getSize() > 0 && file.getSize() < expected; final boolean tryResume = file.exists() && file.getSize() > 0 && file.getSize() < expected;
long resumeSize = 0; final long resumeSize;
if (tryResume) { if (tryResume) {
resumeSize = file.getSize(); resumeSize = file.getSize();
Log.d(Config.LOGTAG, "http download trying resume after " + resumeSize + " of " + expected); Log.d(Config.LOGTAG, "http download trying resume after " + resumeSize + " of " + expected);
connection.setRequestProperty("Range", "bytes=" + resumeSize + "-"); requestBuilder.addHeader("Range", String.format(Locale.ENGLISH, "bytes=%d-", resumeSize));
} else {
resumeSize = 0;
} }
connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000); final Request request = requestBuilder.build();
connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000); mostRecentCall = client.newCall(request);
connection.connect(); final Response response = mostRecentCall.execute();
is = new BufferedInputStream(connection.getInputStream()); throwOnInvalidCode(response);
final String contentRange = connection.getHeaderField("Content-Range"); final String contentRange = response.header("Content-Range");
boolean serverResumed = tryResume && contentRange != null && contentRange.startsWith("bytes " + resumeSize + "-"); final boolean serverResumed = tryResume && contentRange != null && contentRange.startsWith("bytes " + resumeSize + "-");
final InputStream inputStream = response.body().byteStream();
final OutputStream outputStream;
long transmitted = 0; long transmitted = 0;
if (tryResume && serverResumed) { if (tryResume && serverResumed) {
Log.d(Config.LOGTAG, "server resumed"); Log.d(Config.LOGTAG, "server resumed");
transmitted = file.getSize(); transmitted = file.getSize();
updateProgress(Math.round(((double) transmitted / expected) * 100)); updateProgress(Math.round(((double) transmitted / expected) * 100));
os = AbstractConnectionManager.createOutputStream(file, true, false); outputStream = AbstractConnectionManager.createOutputStream(file, true, false);
if (os == null) {
throw new FileWriterException();
}
} else { } else {
long reportedContentLengthOnGet; final String contentLength = response.header("Content-Length");
try { final long size = Strings.isNullOrEmpty(contentLength) ? 0 : Longs.tryParse(contentLength);
reportedContentLengthOnGet = Long.parseLong(connection.getHeaderField("Content-Length")); if (expected != size) {
} catch (NumberFormatException | NullPointerException e) { Log.d(Config.LOGTAG, "content-length reported on GET (" + size + ") did not match Content-Length reported on HEAD (" + expected + ")");
reportedContentLengthOnGet = 0;
}
if (expected != reportedContentLengthOnGet) {
Log.d(Config.LOGTAG, "content-length reported on GET (" + reportedContentLengthOnGet + ") did not match Content-Length reported on HEAD (" + expected + ")");
} }
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
if (!file.exists() && !file.createNewFile()) { if (!file.exists() && !file.createNewFile()) {
throw new FileWriterException(); throw new FileWriterException();
} }
os = AbstractConnectionManager.createOutputStream(file, false, false); outputStream = AbstractConnectionManager.createOutputStream(file, false, false);
} }
int count; int count;
byte[] buffer = new byte[4096]; final byte[] buffer = new byte[4096];
while ((count = is.read(buffer)) != -1) { while ((count = inputStream.read(buffer)) != -1) {
transmitted += count; transmitted += count;
try { try {
os.write(buffer, 0, count); outputStream.write(buffer, 0, count);
} catch (IOException e) { } catch (IOException e) {
throw new FileWriterException(); throw new FileWriterException();
} }
updateProgress(Math.round(((double) transmitted / expected) * 100)); updateProgress(Math.round(((double) transmitted / expected) * 100));
if (canceled) {
throw new CancellationException();
}
}
try {
os.flush();
} catch (IOException e) {
throw new FileWriterException();
}
} catch (CancellationException | IOException e) {
Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": http download failed", e);
throw e;
} finally {
FileBackend.close(os);
FileBackend.close(is);
if (connection != null) {
connection.disconnect();
}
WakeLockHelper.release(wakeLock);
} }
outputStream.flush();
} }
private void updateImageBounds() { private void updateImageBounds() {
final boolean privateMessage = message.isPrivateMessage(); final boolean privateMessage = message.isPrivateMessage();
message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : Message.TYPE_FILE); message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : Message.TYPE_FILE);
final URL url; final String url;
final String ref = mUrl.getRef(); final String ref = mUrl.fragment();
if (method == Method.P1_S3) { if (ref != null && AesGcmURL.IV_KEY.matcher(ref).matches()) {
url = message.getFileParams().url; url = AesGcmURL.toAesGcmUrl(mUrl);
} else if (ref != null && AesGcmURLStreamHandler.IV_KEY.matcher(ref).matches()) {
url = CryptoHelper.toAesGcmUrl(mUrl);
} else { } else {
url = mUrl; url = mUrl.toString();
} }
mXmppConnectionService.getFileBackend().updateFileParams(message, url); mXmppConnectionService.getFileBackend().updateFileParams(message, url);
mXmppConnectionService.updateMessage(message); mXmppConnectionService.updateMessage(message);
} }
} }
private static void throwOnInvalidCode(final Response response) throws IOException {
final int code = response.code();
if (code < 200 || code >= 300) {
throw new IOException(String.format(Locale.ENGLISH, "HTTP Status code was %d", code));
}
}
} }

View File

@ -1,33 +1,36 @@
package eu.siacs.conversations.http; package eu.siacs.conversations.http;
import android.os.PowerManager;
import android.util.Log; import android.util.Log;
import java.io.FileInputStream; import com.google.common.util.concurrent.FutureCallback;
import java.io.InputStream; import com.google.common.util.concurrent.Futures;
import java.io.OutputStream; import com.google.common.util.concurrent.ListenableFuture;
import java.net.HttpURLConnection; import com.google.common.util.concurrent.MoreExecutors;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection; import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.Transferable; import eu.siacs.conversations.entities.Transferable;
import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.services.AbstractConnectionManager; import eu.siacs.conversations.services.AbstractConnectionManager;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.Checksum;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.WakeLockHelper; import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUploadConnection implements Transferable { public class HttpUploadConnection implements Transferable, AbstractConnectionManager.ProgressListener {
static final List<String> WHITE_LISTED_HEADERS = Arrays.asList( static final List<String> WHITE_LISTED_HEADERS = Arrays.asList(
"Authorization", "Authorization",
@ -37,26 +40,22 @@ public class HttpUploadConnection implements Transferable {
private final HttpConnectionManager mHttpConnectionManager; private final HttpConnectionManager mHttpConnectionManager;
private final XmppConnectionService mXmppConnectionService; private final XmppConnectionService mXmppConnectionService;
private final SlotRequester mSlotRequester;
private final Method method; private final Method method;
private final boolean mUseTor;
private boolean cancelled = false;
private boolean delayed = false; private boolean delayed = false;
private DownloadableFile file; private DownloadableFile file;
private final Message message; private final Message message;
private String mime;
private SlotRequester.Slot slot; private SlotRequester.Slot slot;
private byte[] key = null; private byte[] key = null;
private long transmitted = 0; private long transmitted = 0;
private Call mostRecentCall;
private ListenableFuture<SlotRequester.Slot> slotFuture;
public HttpUploadConnection(Message message, Method method, HttpConnectionManager httpConnectionManager) { public HttpUploadConnection(Message message, Method method, HttpConnectionManager httpConnectionManager) {
this.message = message; this.message = message;
this.method = method; this.method = method;
this.mHttpConnectionManager = httpConnectionManager; this.mHttpConnectionManager = httpConnectionManager;
this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService(); this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
this.mSlotRequester = new SlotRequester(this.mXmppConnectionService);
this.mUseTor = mXmppConnectionService.useTorToConnect();
} }
@Override @Override
@ -70,8 +69,8 @@ public class HttpUploadConnection implements Transferable {
} }
@Override @Override
public long getFileSize() { public Long getFileSize() {
return file == null ? 0 : file.getExpectedSize(); return file == null ? null : file.getExpectedSize();
} }
@Override @Override
@ -84,11 +83,24 @@ public class HttpUploadConnection implements Transferable {
@Override @Override
public void cancel() { public void cancel() {
this.cancelled = true; final ListenableFuture<SlotRequester.Slot> slotFuture = this.slotFuture;
if (slotFuture != null && !slotFuture.isDone()) {
if (slotFuture.cancel(true)) {
Log.d(Config.LOGTAG,"cancelled slot requester");
}
}
final Call call = this.mostRecentCall;
if (call != null && !call.isCanceled()) {
call.cancel();
Log.d(Config.LOGTAG,"cancelled HTTP request");
}
} }
private void fail(String errorMessage) { private void fail(String errorMessage) {
finish(); finish();
final Call call = this.mostRecentCall;
final Future<SlotRequester.Slot> slotFuture = this.slotFuture;
final boolean cancelled = (call != null && call.isCanceled()) || (slotFuture != null && slotFuture.isCancelled());
mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage); mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
} }
@ -100,10 +112,11 @@ public class HttpUploadConnection implements Transferable {
public void init(boolean delay) { public void init(boolean delay) {
final Account account = message.getConversation().getAccount(); final Account account = message.getConversation().getAccount();
this.file = mXmppConnectionService.getFileBackend().getFile(message, false); this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
final String mime;
if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) { if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
this.mime = "application/pgp-encrypted"; mime = "application/pgp-encrypted";
} else { } else {
this.mime = this.file.getMimeType(); mime = this.file.getMimeType();
} }
final long originalFileSize = file.getSize(); final long originalFileSize = file.getSize();
this.delayed = delay; this.delayed = delay;
@ -114,108 +127,62 @@ public class HttpUploadConnection implements Transferable {
mXmppConnectionService.getRNG().nextBytes(this.key); mXmppConnectionService.getRNG().nextBytes(this.key);
this.file.setKeyAndIv(this.key); this.file.setKeyAndIv(this.key);
} }
final String md5;
if (method == Method.P1_S3) {
try {
md5 = Checksum.md5(AbstractConnectionManager.upgrade(file, new FileInputStream(file)));
} catch (Exception e) {
Log.d(Config.LOGTAG, account.getJid().asBareJid()+": unable to calculate md5()", e);
fail(e.getMessage());
return;
}
} else {
md5 = null;
}
this.file.setExpectedSize(originalFileSize + (file.getKey() != null ? 16 : 0)); this.file.setExpectedSize(originalFileSize + (file.getKey() != null ? 16 : 0));
message.resetFileParams(); message.resetFileParams();
this.mSlotRequester.request(method, account, file, mime, md5, new SlotRequester.OnSlotRequested() { this.slotFuture = new SlotRequester(mXmppConnectionService).request(method, account, file, mime);
Futures.addCallback(this.slotFuture, new FutureCallback<SlotRequester.Slot>() {
@Override @Override
public void success(SlotRequester.Slot slot) { public void onSuccess(@NullableDecl SlotRequester.Slot result) {
if (!cancelled) { HttpUploadConnection.this.slot = result;
HttpUploadConnection.this.slot = slot; try {
new Thread(HttpUploadConnection.this::upload).start(); HttpUploadConnection.this.upload();
} catch (final Exception e) {
fail(e.getMessage());
} }
} }
@Override @Override
public void failure(String message) { public void onFailure(@NotNull final Throwable throwable) {
fail(message); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to request slot", throwable);
fail(throwable.getMessage());
} }
}); }, MoreExecutors.directExecutor());
message.setTransferable(this); message.setTransferable(this);
mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND); mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
} }
private void upload() { private void upload() {
OutputStream os = null; final OkHttpClient client = mHttpConnectionManager.buildHttpClient(
InputStream fileInputStream = null; slot.put,
HttpURLConnection connection = null; message.getConversation().getAccount(),
PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid()); 0,
try { true
fileInputStream = new FileInputStream(file); );
final String slotHostname = slot.getPutUrl().getHost(); final RequestBody requestBody = AbstractConnectionManager.requestBody(file, this);
final boolean onionSlot = slotHostname != null && slotHostname.endsWith(".onion"); final Request request = new Request.Builder()
final int expectedFileSize = (int) file.getExpectedSize(); .url(slot.put)
final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s .put(requestBody)
wakeLock.acquire(readTimeout); .headers(slot.headers)
Log.d(Config.LOGTAG, "uploading to " + slot.getPutUrl().toString()+ " w/ read timeout of "+readTimeout+"s"); .build();
Log.d(Config.LOGTAG, "uploading file to " + slot.put);
this.mostRecentCall = client.newCall(request);
this.mostRecentCall.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, IOException e) {
Log.d(Config.LOGTAG, "http upload failed", e);
fail(e.getMessage());
}
if (mUseTor || message.getConversation().getAccount().isOnion() || onionSlot) { @Override
connection = (HttpURLConnection) slot.getPutUrl().openConnection(HttpConnectionManager.getProxy()); public void onResponse(@NotNull Call call, @NotNull Response response) {
} else { final int code = response.code();
connection = (HttpURLConnection) slot.getPutUrl().openConnection();
}
if (connection instanceof HttpsURLConnection) {
mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
}
connection.setUseCaches(false);
connection.setRequestMethod("PUT");
connection.setFixedLengthStreamingMode(expectedFileSize);
connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getUserAgent());
if(slot.getHeaders() != null) {
for(HashMap.Entry<String,String> entry : slot.getHeaders().entrySet()) {
connection.setRequestProperty(entry.getKey(),entry.getValue());
}
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
connection.setReadTimeout(readTimeout * 1000);
connection.connect();
final InputStream innerInputStream = AbstractConnectionManager.upgrade(file, fileInputStream);
os = connection.getOutputStream();
transmitted = 0;
int count;
byte[] buffer = new byte[4096];
while (((count = innerInputStream.read(buffer)) != -1) && !cancelled) {
transmitted += count;
os.write(buffer, 0, count);
mHttpConnectionManager.updateConversationUi(false);
}
os.flush();
os.close();
int code = connection.getResponseCode();
InputStream is = connection.getErrorStream();
if (is != null) {
try (Scanner scanner = new Scanner(is)) {
scanner.useDelimiter("\\Z");
Log.d(Config.LOGTAG, "body: " + scanner.next());
}
}
if (code == 200 || code == 201) { if (code == 200 || code == 201) {
Log.d(Config.LOGTAG, "finished uploading file"); Log.d(Config.LOGTAG, "finished uploading file");
final URL get; final String get;
if (key != null) { if (key != null) {
if (method == Method.P1_S3) { get = AesGcmURL.toAesGcmUrl(slot.get.newBuilder().fragment(CryptoHelper.bytesToHex(key)).build());
get = new URL(slot.getGetUrl().toString()+"#"+CryptoHelper.bytesToHex(key));
} else { } else {
get = CryptoHelper.toAesGcmUrl(new URL(slot.getGetUrl().toString() + "#" + CryptoHelper.bytesToHex(key))); get = slot.get.toString();
}
} else {
get = slot.getGetUrl();
} }
mXmppConnectionService.getFileBackend().updateFileParams(message, get); mXmppConnectionService.getFileBackend().updateFileParams(message, get);
mXmppConnectionService.getFileBackend().updateMediaScanner(file); mXmppConnectionService.getFileBackend().updateMediaScanner(file);
@ -228,21 +195,17 @@ public class HttpUploadConnection implements Transferable {
Log.d(Config.LOGTAG, "http upload failed because response code was " + code); Log.d(Config.LOGTAG, "http upload failed because response code was " + code);
fail("http upload failed because response code was " + code); fail("http upload failed because response code was " + code);
} }
} catch (Exception e) {
e.printStackTrace();
Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
fail(e.getMessage());
} finally {
FileBackend.close(fileInputStream);
FileBackend.close(os);
if (connection != null) {
connection.disconnect();
}
WakeLockHelper.release(wakeLock);
} }
});
} }
public Message getMessage() { public Message getMessage() {
return message; return message;
} }
@Override
public void onProgress(final long progress) {
this.transmitted = progress;
mHttpConnectionManager.updateConversationUi(false);
}
} }

View File

@ -33,7 +33,7 @@ import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.XmppConnection;
public enum Method { public enum Method {
P1_S3, HTTP_UPLOAD, HTTP_UPLOAD_LEGACY; HTTP_UPLOAD, HTTP_UPLOAD_LEGACY;
public static Method determine(Account account) { public static Method determine(Account account) {
XmppConnection.Features features = account.getXmppConnection() == null ? null : account.getXmppConnection().getFeatures(); XmppConnection.Features features = account.getXmppConnection() == null ? null : account.getXmppConnection().getFeatures();
@ -44,8 +44,6 @@ public enum Method {
return HTTP_UPLOAD_LEGACY; return HTTP_UPLOAD_LEGACY;
} else if (features.httpUpload(0)) { } else if (features.httpUpload(0)) {
return HTTP_UPLOAD; return HTTP_UPLOAD;
} else if (features.p1S3FileTransfer()) {
return P1_S3;
} else { } else {
return HTTP_UPLOAD; return HTTP_UPLOAD;
} }

View File

@ -1,62 +0,0 @@
/*
* Copyright (c) 2018, Daniel Gultsch All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.siacs.conversations.http;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import eu.siacs.conversations.xml.Element;
public class P1S3UrlStreamHandler extends URLStreamHandler {
public static final String PROTOCOL_NAME = "p1s3";
@Override
protected URLConnection openConnection(URL url) {
throw new IllegalStateException("Unable to open connection with stub protocol");
}
public static URL of(String fileId, String filename) throws MalformedURLException {
if (fileId == null || filename == null) {
throw new MalformedURLException("Paramaters must not be null");
}
return new URL(PROTOCOL_NAME+"://" + fileId + "/" + filename);
}
public static URL of(Element x) {
try {
return of(x.getAttribute("fileid"),x.getAttribute("name"));
} catch (MalformedURLException e) {
return null;
}
}
}

View File

@ -29,21 +29,23 @@
package eu.siacs.conversations.http; package eu.siacs.conversations.http;
import android.util.Log; import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.net.MalformedURLException; import java.util.Map;
import java.net.URL;
import java.util.HashMap;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.parser.IqParser; import eu.siacs.conversations.parser.IqParser;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.IqResponseException;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import okhttp3.Headers;
import okhttp3.HttpUrl;
public class SlotRequester { public class SlotRequester {
@ -53,51 +55,52 @@ public class SlotRequester {
this.service = service; this.service = service;
} }
public void request(Method method, Account account, DownloadableFile file, String mime, String md5, OnSlotRequested callback) { public ListenableFuture<Slot> request(Method method, Account account, DownloadableFile file, String mime) {
if (method == Method.HTTP_UPLOAD) { if (method == Method.HTTP_UPLOAD_LEGACY) {
Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD); final Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY);
requestHttpUpload(account, host, file, mime, callback); return requestHttpUploadLegacy(account, host, file, mime);
} else if (method == Method.HTTP_UPLOAD_LEGACY) {
Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY);
requestHttpUploadLegacy(account, host, file, mime, callback);
} else { } else {
requestP1S3(account, account.getDomain(), file.getName(), md5, callback); final Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD);
return requestHttpUpload(account, host, file, mime);
} }
} }
private void requestHttpUploadLegacy(Account account, Jid host, DownloadableFile file, String mime, OnSlotRequested callback) { private ListenableFuture<Slot> requestHttpUploadLegacy(Account account, Jid host, DownloadableFile file, String mime) {
IqPacket request = service.getIqGenerator().requestHttpUploadLegacySlot(host, file, mime); final SettableFuture<Slot> future = SettableFuture.create();
final IqPacket request = service.getIqGenerator().requestHttpUploadLegacySlot(host, file, mime);
service.sendIqPacket(account, request, (a, packet) -> { service.sendIqPacket(account, request, (a, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Element slotElement = packet.findChild("slot", Namespace.HTTP_UPLOAD_LEGACY); final Element slotElement = packet.findChild("slot", Namespace.HTTP_UPLOAD_LEGACY);
if (slotElement != null) { if (slotElement != null) {
try { try {
final String putUrl = slotElement.findChildContent("put"); final String putUrl = slotElement.findChildContent("put");
final String getUrl = slotElement.findChildContent("get"); final String getUrl = slotElement.findChildContent("get");
if (getUrl != null && putUrl != null) { if (getUrl != null && putUrl != null) {
Slot slot = new Slot(new URL(putUrl)); final Slot slot = new Slot(
slot.getUrl = new URL(getUrl); HttpUrl.get(putUrl),
slot.headers = new HashMap<>(); HttpUrl.get(getUrl),
slot.headers.put("Content-Type", mime == null ? "application/octet-stream" : mime); Headers.of("Content-Type", mime == null ? "application/octet-stream" : mime)
callback.success(slot); );
future.set(slot);
return; return;
} }
} catch (MalformedURLException e) { } catch (final IllegalArgumentException e) {
//fall through future.setException(e);
return;
} }
} }
} }
Log.d(Config.LOGTAG, account.getJid().toString() + ": invalid response to slot request " + packet); future.setException(new IqResponseException(IqParser.extractErrorMessage(packet)));
callback.failure(IqParser.extractErrorMessage(packet));
}); });
return future;
} }
private void requestHttpUpload(Account account, Jid host, DownloadableFile file, String mime, OnSlotRequested callback) { private ListenableFuture<Slot> requestHttpUpload(Account account, Jid host, DownloadableFile file, String mime) {
IqPacket request = service.getIqGenerator().requestHttpUploadSlot(host, file, mime); final SettableFuture<Slot> future = SettableFuture.create();
final IqPacket request = service.getIqGenerator().requestHttpUploadSlot(host, file, mime);
service.sendIqPacket(account, request, (a, packet) -> { service.sendIqPacket(account, request, (a, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) { if (packet.getType() == IqPacket.TYPE.RESULT) {
Element slotElement = packet.findChild("slot", Namespace.HTTP_UPLOAD); final Element slotElement = packet.findChild("slot", Namespace.HTTP_UPLOAD);
if (slotElement != null) { if (slotElement != null) {
try { try {
final Element put = slotElement.findChild("put"); final Element put = slotElement.findChild("put");
@ -105,86 +108,47 @@ public class SlotRequester {
final String putUrl = put == null ? null : put.getAttribute("url"); final String putUrl = put == null ? null : put.getAttribute("url");
final String getUrl = get == null ? null : get.getAttribute("url"); final String getUrl = get == null ? null : get.getAttribute("url");
if (getUrl != null && putUrl != null) { if (getUrl != null && putUrl != null) {
Slot slot = new Slot(new URL(putUrl)); final ImmutableMap.Builder<String, String> headers = new ImmutableMap.Builder<>();
slot.getUrl = new URL(getUrl); for (final Element child : put.getChildren()) {
slot.headers = new HashMap<>();
for (Element child : put.getChildren()) {
if ("header".equals(child.getName())) { if ("header".equals(child.getName())) {
final String name = child.getAttribute("name"); final String name = child.getAttribute("name");
final String value = child.getContent(); final String value = child.getContent();
if (HttpUploadConnection.WHITE_LISTED_HEADERS.contains(name) && value != null && !value.trim().contains("\n")) { if (HttpUploadConnection.WHITE_LISTED_HEADERS.contains(name) && value != null && !value.trim().contains("\n")) {
slot.headers.put(name, value.trim()); headers.put(name, value.trim());
} }
} }
} }
slot.headers.put("Content-Type", mime == null ? "application/octet-stream" : mime); headers.put("Content-Type", mime == null ? "application/octet-stream" : mime);
callback.success(slot); final Slot slot = new Slot(HttpUrl.get(putUrl), HttpUrl.get(getUrl), headers.build());
future.set(slot);
return; return;
} }
} catch (MalformedURLException e) { } catch (final IllegalArgumentException e) {
//fall through future.setException(e);
}
}
}
Log.d(Config.LOGTAG, account.getJid().toString() + ": invalid response to slot request " + packet);
callback.failure(IqParser.extractErrorMessage(packet));
});
}
private void requestP1S3(final Account account, Jid host, String filename, String md5, OnSlotRequested callback) {
IqPacket request = service.getIqGenerator().requestP1S3Slot(host, md5);
service.sendIqPacket(account, request, (a, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) {
String putUrl = packet.query(Namespace.P1_S3_FILE_TRANSFER).getAttribute("upload");
String id = packet.query().getAttribute("fileid");
try {
if (putUrl != null && id != null) {
Slot slot = new Slot(new URL(putUrl));
slot.getUrl = P1S3UrlStreamHandler.of(id, filename);
slot.headers = new HashMap<>();
slot.headers.put("Content-MD5", md5);
slot.headers.put("Content-Type", " "); //required to force it to empty. otherwise library will set something
callback.success(slot);
return; return;
} }
} catch (MalformedURLException e) {
//fall through;
} }
} }
callback.failure("unable to request slot"); future.setException(new IqResponseException(IqParser.extractErrorMessage(packet)));
}); });
Log.d(Config.LOGTAG, "requesting slot with p1. md5=" + md5); return future;
}
public interface OnSlotRequested {
void success(Slot slot);
void failure(String message);
} }
public static class Slot { public static class Slot {
private final URL putUrl; public final HttpUrl put;
private URL getUrl; public final HttpUrl get;
private HashMap<String, String> headers; public final Headers headers;
private Slot(URL putUrl) { private Slot(HttpUrl put, HttpUrl get, Headers headers) {
this.putUrl = putUrl; this.put = put;
this.get = get;
this.headers = headers;
} }
public URL getPutUrl() { private Slot(HttpUrl put, HttpUrl getUrl, Map<String, String> headers) {
return putUrl; this.put = put;
} this.get = getUrl;
this.headers = Headers.of(headers);
public URL getGetUrl() {
return getUrl;
}
public HashMap<String, String> getHeaders() {
return headers;
} }
} }
} }

View File

@ -0,0 +1,32 @@
package eu.siacs.conversations.http;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import okhttp3.HttpUrl;
public class URL {
public static final List<String> WELL_KNOWN_SCHEMES = Arrays.asList("http", "https", AesGcmURL.PROTOCOL_NAME);
public static String tryParse(String url) {
final URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
return null;
}
if (WELL_KNOWN_SCHEMES.contains(uri.getScheme())) {
return uri.toString();
} else {
return null;
}
}
public static HttpUrl stripFragment(final HttpUrl url) {
return url.newBuilder().fragment(null).build();
}
}

View File

@ -3,7 +3,6 @@ package eu.siacs.conversations.parser;
import android.util.Log; import android.util.Log;
import android.util.Pair; import android.util.Pair;
import java.net.URL;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -33,7 +32,6 @@ import eu.siacs.conversations.entities.ReadByMarker;
import eu.siacs.conversations.entities.ReceiptRequest; import eu.siacs.conversations.entities.ReceiptRequest;
import eu.siacs.conversations.entities.RtpSessionStatus; import eu.siacs.conversations.entities.RtpSessionStatus;
import eu.siacs.conversations.http.HttpConnectionManager; import eu.siacs.conversations.http.HttpConnectionManager;
import eu.siacs.conversations.http.P1S3UrlStreamHandler;
import eu.siacs.conversations.services.MessageArchiveService; import eu.siacs.conversations.services.MessageArchiveService;
import eu.siacs.conversations.services.QuickConversationsService; import eu.siacs.conversations.services.QuickConversationsService;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
@ -408,8 +406,6 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted"); final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0"); final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
final Element oob = packet.findChild("x", Namespace.OOB); final Element oob = packet.findChild("x", Namespace.OOB);
final Element xP1S3 = packet.findChild("x", Namespace.P1_S3_FILE_TRANSFER);
final URL xP1S3url = xP1S3 == null ? null : P1S3UrlStreamHandler.of(xP1S3);
final String oobUrl = oob != null ? oob.findChildContent("url") : null; final String oobUrl = oob != null ? oob.findChildContent("url") : null;
final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id"); final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX); final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
@ -464,7 +460,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
} }
if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null || xP1S3 != null) && !isMucStatusMessage) { if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString()); final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false); final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI; final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
@ -488,13 +484,11 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
if (conversation.getMucOptions().isSelf(counterpart)) { if (conversation.getMucOptions().isSelf(counterpart)) {
status = Message.STATUS_SEND_RECEIVED; status = Message.STATUS_SEND_RECEIVED;
isCarbon = true; //not really carbon but received from another resource isCarbon = true; //not really carbon but received from another resource
//TODO this would be the place to change the body after something like mod_pastebin if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
return; return;
} else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) { } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
LocalizedContent localizedBody = packet.getBody(); if (body != null) {
if (localizedBody != null) { Message message = conversation.findSentMessageWithBody(body.content);
Message message = conversation.findSentMessageWithBody(localizedBody.content);
if (message != null) { if (message != null) {
mXmppConnectionService.markMessage(message, status); mXmppConnectionService.markMessage(message, status);
return; return;
@ -506,13 +500,7 @@ public class MessageParser extends AbstractParser implements OnMessagePacketRece
} }
} }
final Message message; final Message message;
if (xP1S3url != null) { if (pgpEncrypted != null && Config.supportOpenPgp()) {
message = new Message(conversation, xP1S3url.toString(), Message.ENCRYPTION_NONE, status);
message.setOob(true);
if (CryptoHelper.isPgpEncryptedUrl(xP1S3url.toString())) {
message.setEncryption(Message.ENCRYPTION_DECRYPTED);
}
} else if (pgpEncrypted != null && Config.supportOpenPgp()) {
message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status); message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
} else if (axolotlEncrypted != null && Config.supportOmemo()) { } else if (axolotlEncrypted != null && Config.supportOmemo()) {
Jid origin; Jid origin;

View File

@ -2,6 +2,8 @@ package eu.siacs.conversations.parser;
import android.util.Log; import android.util.Log;
import org.openintents.openpgp.util.OpenPgpUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -313,9 +315,10 @@ public class PresenceParser extends AbstractParser implements
PgpEngine pgp = mXmppConnectionService.getPgpEngine(); PgpEngine pgp = mXmppConnectionService.getPgpEngine();
Element x = packet.findChild("x", "jabber:x:signed"); Element x = packet.findChild("x", "jabber:x:signed");
if (pgp != null && x != null) { if (pgp != null && x != null) {
Element status = packet.findChild("status"); final String status = packet.findChildContent("status");
String msg = status != null ? status.getContent() : ""; final long keyId = pgp.fetchKeyId(account, status, x.getContent());
if (contact.setPgpKeyId(pgp.fetchKeyId(account, msg, x.getContent()))) { if (keyId != 0 && contact.setPgpKeyId(keyId)) {
Log.d(Config.LOGTAG,account.getJid().asBareJid()+": found OpenPGP key id for "+contact.getJid()+" "+OpenPgpUtils.convertKeyIdToHex(keyId));
mXmppConnectionService.syncRoster(account); mXmppConnectionService.syncRoster(account);
} }
} }

View File

@ -11,6 +11,8 @@ import android.os.SystemClock;
import android.util.Base64; import android.util.Base64;
import android.util.Log; import android.util.Log;
import com.google.common.base.Stopwatch;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.whispersystems.libsignal.IdentityKey; import org.whispersystems.libsignal.IdentityKey;
@ -62,7 +64,9 @@ import eu.siacs.conversations.xmpp.mam.MamReference;
public class DatabaseBackend extends SQLiteOpenHelper { public class DatabaseBackend extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "history"; private static final String DATABASE_NAME = "history";
private static final int DATABASE_VERSION = 49; private static final int DATABASE_VERSION = 50;
private static boolean requiresMessageIndexRebuild = false;
private static DatabaseBackend instance = null; private static DatabaseBackend instance = null;
private static final String CREATE_CONTATCS_STATEMENT = "create table " private static final String CREATE_CONTATCS_STATEMENT = "create table "
+ Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, " + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
@ -165,16 +169,17 @@ public class DatabaseBackend extends SQLiteOpenHelper {
+ "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE" + "UNIQUE(" + Resolver.Result.DOMAIN + ") ON CONFLICT REPLACE"
+ ");"; + ");";
private static final String CREATE_MESSAGE_TIME_INDEX = "create INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")"; private static final String CREATE_MESSAGE_TIME_INDEX = "CREATE INDEX message_time_index ON " + Message.TABLENAME + "(" + Message.TIME_SENT + ")";
private static final String CREATE_MESSAGE_CONVERSATION_INDEX = "create INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")"; private static final String CREATE_MESSAGE_CONVERSATION_INDEX = "CREATE INDEX message_conversation_index ON " + Message.TABLENAME + "(" + Message.CONVERSATION + ")";
private static final String CREATE_MESSAGE_DELETED_INDEX = "create index message_deleted_index ON " + Message.TABLENAME + "(" + Message.DELETED + ")"; private static final String CREATE_MESSAGE_DELETED_INDEX = "CREATE INDEX message_deleted_index ON " + Message.TABLENAME + "(" + Message.DELETED + ")";
private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX = "create INDEX message_file_path_index ON " + Message.TABLENAME + "(" + Message.RELATIVE_FILE_PATH + ")"; private static final String CREATE_MESSAGE_RELATIVE_FILE_PATH_INDEX = "CREATE INDEX message_file_path_index ON " + Message.TABLENAME + "(" + Message.RELATIVE_FILE_PATH + ")";
private static final String CREATE_MESSAGE_TYPE_INDEX = "create INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")"; private static final String CREATE_MESSAGE_TYPE_INDEX = "CREATE INDEX message_type_index ON " + Message.TABLENAME + "(" + Message.TYPE + ")";
private static final String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING FTS4(uuid TEXT PRIMARY KEY, body TEXT)"; private static final String CREATE_MESSAGE_INDEX_TABLE = "CREATE VIRTUAL TABLE messages_index USING fts4 (uuid,body,notindexed=\"uuid\",content=\"" + Message.TABLENAME + "\",tokenize='unicode61')";
private static final String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index (uuid,body) VALUES (new.uuid,new.body); END;"; private static final String CREATE_MESSAGE_INSERT_TRIGGER = "CREATE TRIGGER after_message_insert AFTER INSERT ON " + Message.TABLENAME + " BEGIN INSERT INTO messages_index(rowid,uuid,body) VALUES(NEW.rowid,NEW.uuid,NEW.body); END;";
private static final String CREATE_MESSAGE_UPDATE_TRIGGER = "CREATE TRIGGER after_message_update UPDATE of uuid,body ON " + Message.TABLENAME + " BEGIN update messages_index set body=new.body,uuid=new.uuid WHERE uuid=old.uuid; END;"; private static final String CREATE_MESSAGE_UPDATE_TRIGGER = "CREATE TRIGGER after_message_update UPDATE OF uuid,body ON " + Message.TABLENAME + " BEGIN UPDATE messages_index SET body=NEW.body,uuid=NEW.uuid WHERE rowid=OLD.rowid; END;";
private static final String COPY_PREEXISTING_ENTRIES = "INSERT into messages_index(uuid,body) select uuid,body FROM " + Message.TABLENAME + ";"; private static final String CREATE_MESSAGE_DELETE_TRIGGER = "CREATE TRIGGER after_message_delete AFTER DELETE ON " + Message.TABLENAME + " BEGIN DELETE FROM messages_index WHERE rowid=OLD.rowid; END;";
private static final String COPY_PREEXISTING_ENTRIES = "INSERT INTO messages_index(messages_index) VALUES('rebuild');";
private DatabaseBackend(Context context) { private DatabaseBackend(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); super(context, DATABASE_NAME, null, DATABASE_VERSION);
@ -187,6 +192,17 @@ public class DatabaseBackend extends SQLiteOpenHelper {
return values; return values;
} }
public static boolean requiresMessageIndexRebuild() {
return requiresMessageIndexRebuild;
}
public void rebuildMessagesIndex() {
final SQLiteDatabase db = getWritableDatabase();
final Stopwatch stopwatch = Stopwatch.createStarted();
db.execSQL(COPY_PREEXISTING_ENTRIES);
Log.d(Config.LOGTAG,"rebuilt message index in "+ stopwatch.stop().toString());
}
public static synchronized DatabaseBackend getInstance(Context context) { public static synchronized DatabaseBackend getInstance(Context context) {
if (instance == null) { if (instance == null) {
instance = new DatabaseBackend(context); instance = new DatabaseBackend(context);
@ -263,6 +279,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
db.execSQL(CREATE_MESSAGE_INDEX_TABLE); db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER); db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER); db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
} }
@Override @Override
@ -515,16 +532,10 @@ public class DatabaseBackend extends SQLiteOpenHelper {
db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0"); db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.MARKABLE + " NUMBER DEFAULT 0");
} }
if (oldVersion < 41 && newVersion >= 41) { if (oldVersion < 39 && newVersion >= 39) {
db.execSQL(CREATE_MESSAGE_INDEX_TABLE); db.execSQL(CREATE_RESOLVER_RESULTS_TABLE);
db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
db.execSQL(COPY_PREEXISTING_ENTRIES);
} }
if (oldVersion < 42 && newVersion >= 42) {
db.execSQL("DROP TRIGGER IF EXISTS after_message_delete");
}
if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) { if (QuickConversationsService.isQuicksy() && oldVersion < 43 && newVersion >= 43) {
List<Account> accounts = getAccounts(db); List<Account> accounts = getAccounts(db);
for (Account account : accounts) { for (Account account : accounts) {
@ -564,7 +575,29 @@ public class DatabaseBackend extends SQLiteOpenHelper {
db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.PRESENCE_NAME + " TEXT"); db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.PRESENCE_NAME + " TEXT");
} }
if (oldVersion < 49 && newVersion >= 49) { if (oldVersion < 49 && newVersion >= 49) {
db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.RTP_CAPABILITY + " TEXT"); // dirty workaround for failed migration
db.execSQL("IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + Contact.TABLENAME + "' AND COLUMN_NAME = '" + Contact.RTP_CAPABILITY + "') THEN"
+ "ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN " + Contact.RTP_CAPABILITY + " TEXT");
}
if (oldVersion < 50 && newVersion >= 50) {
db.beginTransaction();
db.execSQL("DROP TRIGGER IF EXISTS after_message_insert;");
db.execSQL("DROP TRIGGER IF EXISTS after_message_update;");
db.execSQL("DROP TRIGGER IF EXISTS after_message_delete;");
db.execSQL("DROP TABLE IF EXISTS messages_index;");
// a hack that should not be necessary, but
// there was at least one occurence when SQLite failed at this
db.execSQL("DROP TABLE IF EXISTS messages_index_docsize;");
db.execSQL("DROP TABLE IF EXISTS messages_index_segdir;");
db.execSQL("DROP TABLE IF EXISTS messages_index_segments;");
db.execSQL("DROP TABLE IF EXISTS messages_index_stat;");
db.execSQL(CREATE_MESSAGE_INDEX_TABLE);
db.execSQL(CREATE_MESSAGE_INSERT_TRIGGER);
db.execSQL(CREATE_MESSAGE_UPDATE_TRIGGER);
db.execSQL(CREATE_MESSAGE_DELETE_TRIGGER);
db.setTransactionSuccessful();
db.endTransaction();
requiresMessageIndexRebuild = true;
} }
} }
@ -791,7 +824,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
final SQLiteDatabase db = this.getReadableDatabase(); final SQLiteDatabase db = this.getReadableDatabase();
final StringBuilder SQL = new StringBuilder(); final StringBuilder SQL = new StringBuilder();
final String[] selectionArgs; final String[] selectionArgs;
SQL.append("SELECT " + Message.TABLENAME + ".*," + Conversation.TABLENAME + '.' + Conversation.CONTACTJID + ',' + Conversation.TABLENAME + '.' + Conversation.ACCOUNT + ',' + Conversation.TABLENAME + '.' + Conversation.MODE + " FROM " + Message.TABLENAME + " join " + Conversation.TABLENAME + " on " + Message.TABLENAME + '.' + Message.CONVERSATION + '=' + Conversation.TABLENAME + '.' + Conversation.UUID + " join messages_index ON messages_index.uuid=messages.uuid where " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + ',' + Message.ENCRYPTION_PGP + ',' + Message.ENCRYPTION_DECRYPTION_FAILED + ',' + Message.ENCRYPTION_AXOLOTL_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + ',' + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ?"); SQL.append("SELECT " + Message.TABLENAME + ".*," + Conversation.TABLENAME + "." + Conversation.CONTACTJID + "," + Conversation.TABLENAME + "." + Conversation.ACCOUNT + "," + Conversation.TABLENAME + "." + Conversation.MODE + " FROM " + Message.TABLENAME + " JOIN " + Conversation.TABLENAME + " ON " + Message.TABLENAME + "." + Message.CONVERSATION + "=" + Conversation.TABLENAME + "." + Conversation.UUID + " JOIN messages_index ON messages_index.rowid=messages.rowid WHERE " + Message.ENCRYPTION + " NOT IN(" + Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE + "," + Message.ENCRYPTION_PGP + "," + Message.ENCRYPTION_DECRYPTION_FAILED + "," + Message.ENCRYPTION_AXOLOTL_FAILED + ") AND " + Message.TYPE + " IN(" + Message.TYPE_TEXT + "," + Message.TYPE_PRIVATE + ") AND messages_index.body MATCH ?");
if (uuid == null) { if (uuid == null) {
selectionArgs = new String[]{FtsUtils.toMatchString(term)}; selectionArgs = new String[]{FtsUtils.toMatchString(term)};
} else { } else {
@ -1042,8 +1075,7 @@ public class DatabaseBackend extends SQLiteOpenHelper {
long start = SystemClock.elapsedRealtime(); long start = SystemClock.elapsedRealtime();
final SQLiteDatabase db = this.getWritableDatabase(); final SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction(); db.beginTransaction();
String[] args = {conversation.getUuid()}; final String[] args = {conversation.getUuid()};
db.delete("messages_index", "uuid in (select uuid from messages where conversationUuid=?)", args);
int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args); int num = db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
db.setTransactionSuccessful(); db.setTransactionSuccessful();
db.endTransaction(); db.endTransaction();
@ -1054,7 +1086,6 @@ public class DatabaseBackend extends SQLiteOpenHelper {
final String[] args = {String.valueOf(timestamp)}; final String[] args = {String.valueOf(timestamp)};
SQLiteDatabase db = this.getReadableDatabase(); SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction(); db.beginTransaction();
db.delete("messages_index", "uuid in (select uuid from messages where timeSent<?)", args);
db.delete(Message.TABLENAME, "timeSent<?", args); db.delete(Message.TABLENAME, "timeSent<?", args);
db.setTransactionSuccessful(); db.setTransactionSuccessful();
db.endTransaction(); db.endTransaction();

View File

@ -29,7 +29,11 @@ import android.util.Log;
import android.util.LruCache; import android.util.LruCache;
import androidx.annotation.RequiresApi; import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.core.content.FileProvider; import androidx.core.content.FileProvider;
import androidx.exifinterface.media.ExifInterface;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.Closeable; import java.io.Closeable;
@ -43,7 +47,6 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.net.URL;
import java.security.DigestOutputStream; import java.security.DigestOutputStream;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -64,7 +67,6 @@ import eu.siacs.conversations.ui.RecordingActivity;
import eu.siacs.conversations.ui.util.Attachment; import eu.siacs.conversations.ui.util.Attachment;
import eu.siacs.conversations.utils.Compatibility; import eu.siacs.conversations.utils.Compatibility;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.ExifHelper;
import eu.siacs.conversations.utils.FileUtils; import eu.siacs.conversations.utils.FileUtils;
import eu.siacs.conversations.utils.FileWriterException; import eu.siacs.conversations.utils.FileWriterException;
import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.utils.MimeUtils;
@ -223,8 +225,12 @@ public class FileBackend {
} }
private static boolean hasAlpha(final Bitmap bitmap) { private static boolean hasAlpha(final Bitmap bitmap) {
for (int x = 0; x < bitmap.getWidth(); ++x) { final int w = bitmap.getWidth();
for (int y = 0; y < bitmap.getWidth(); ++y) { final int h = bitmap.getHeight();
final int yStep = Math.max(1, w / 100);
final int xStep = Math.max(1, h / 100);
for (int x = 0; x < w; x += xStep) {
for (int y = 0; y < h; y += yStep) {
if (Color.alpha(bitmap.getPixel(x, y)) < 255) { if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
return true; return true;
} }
@ -291,12 +297,7 @@ public class FileBackend {
if (dimensions != null) { if (dimensions != null) {
return dimensions; return dimensions;
} }
final int rotation; final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
rotation = extractRotationFromMediaRetriever(metadataRetriever);
} else {
rotation = 0;
}
boolean rotated = rotation == 90 || rotation == 270; boolean rotated = rotation == 90 || rotation == 270;
int height; int height;
try { try {
@ -317,7 +318,6 @@ public class FileBackend {
return rotated ? new Dimensions(width, height) : new Dimensions(height, width); return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
} }
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) { private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
try { try {
@ -417,9 +417,9 @@ public class FileBackend {
} }
} }
public static void updateFileParams(Message message, URL url, long size) { public static void updateFileParams(Message message, String url, long size) {
final StringBuilder body = new StringBuilder(); final StringBuilder body = new StringBuilder();
body.append(url.toString()).append('|').append(size); body.append(url).append('|').append(size);
message.setBody(body.toString()); message.setBody(body.toString());
} }
@ -596,12 +596,12 @@ public class FileBackend {
} }
} }
public boolean useImageAsIs(Uri uri) { public boolean useImageAsIs(final Uri uri) {
String path = getOriginalPath(uri); final String path = getOriginalPath(uri);
if (path == null || isPathBlacklisted(path)) { if (path == null || isPathBlacklisted(path)) {
return false; return false;
} }
File file = new File(path); final File file = new File(path);
long size = file.length(); long size = file.length();
if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) { if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
return false; return false;
@ -609,12 +609,15 @@ public class FileBackend {
BitmapFactory.Options options = new BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
try { try {
BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options); final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(inputStream, null, options);
close(inputStream);
if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) { if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
return false; return false;
} }
return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase())); return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
Log.d(Config.LOGTAG, "unable to get image dimensions", e);
return false; return false;
} }
} }
@ -626,36 +629,38 @@ public class FileBackend {
private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException { private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath()); Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
OutputStream os = null;
InputStream is = null;
try { try {
file.createNewFile(); file.createNewFile();
os = new FileOutputStream(file); } catch (IOException e) {
is = mXmppConnectionService.getContentResolver().openInputStream(uri); throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
byte[] buffer = new byte[1024]; }
int length; try (final OutputStream os = new FileOutputStream(file);
while ((length = is.read(buffer)) > 0) { final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(uri)) {
if (is == null) {
throw new FileCopyException(R.string.error_file_not_found);
}
try { try {
os.write(buffer, 0, length); ByteStreams.copy(is, os);
} catch (IOException e) { } catch (IOException e) {
throw new FileWriterException(); throw new FileWriterException();
} }
}
try { try {
os.flush(); os.flush();
} catch (IOException e) { } catch (IOException e) {
throw new FileWriterException(); throw new FileWriterException();
} }
} catch (FileNotFoundException e) { } catch (final FileNotFoundException e) {
cleanup(file);
throw new FileCopyException(R.string.error_file_not_found); throw new FileCopyException(R.string.error_file_not_found);
} catch (FileWriterException e) { } catch (final FileWriterException e) {
cleanup(file);
throw new FileCopyException(R.string.error_unable_to_create_temporary_file); throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
} catch (IOException e) { } catch (final SecurityException e) {
e.printStackTrace(); cleanup(file);
throw new FileCopyException(R.string.error_security_exception);
} catch (final IOException e) {
cleanup(file);
throw new FileCopyException(R.string.error_io_exception); throw new FileCopyException(R.string.error_io_exception);
} finally {
close(os);
close(is);
} }
} }
@ -704,8 +709,11 @@ public class FileBackend {
return pos > 0 ? filename.substring(pos + 1) : null; return pos > 0 ? filename.substring(pos + 1) : null;
} }
private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException, NotAnImageFileException { private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException, ImageCompressionException {
file.getParentFile().mkdirs(); final File parent = file.getParentFile();
if (parent != null && parent.mkdirs()) {
Log.d(Config.LOGTAG, "created parent directory");
}
InputStream is = null; InputStream is = null;
OutputStream os = null; OutputStream os = null;
try { try {
@ -716,18 +724,22 @@ public class FileBackend {
if (is == null) { if (is == null) {
throw new FileCopyException(R.string.error_not_an_image_file); throw new FileCopyException(R.string.error_not_an_image_file);
} }
Bitmap originalBitmap; final Bitmap originalBitmap;
BitmapFactory.Options options = new BitmapFactory.Options(); final BitmapFactory.Options options = new BitmapFactory.Options();
int inSampleSize = (int) Math.pow(2, sampleSize); final int inSampleSize = (int) Math.pow(2, sampleSize);
Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize); Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
options.inSampleSize = inSampleSize; options.inSampleSize = inSampleSize;
originalBitmap = BitmapFactory.decodeStream(is, null, options); originalBitmap = BitmapFactory.decodeStream(is, null, options);
is.close(); is.close();
if (originalBitmap == null) { if (originalBitmap == null) {
throw new NotAnImageFileException(); throw new ImageCompressionException("Source file was not an image");
}
if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
originalBitmap.recycle();
throw new ImageCompressionException("Source file had alpha channel");
} }
Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE); Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
int rotation = getRotation(image); final int rotation = getRotation(image);
scaledBitmap = rotate(scaledBitmap, rotation); scaledBitmap = rotate(scaledBitmap, rotation);
boolean targetSizeReached = false; boolean targetSizeReached = false;
int quality = Config.IMAGE_QUALITY; int quality = Config.IMAGE_QUALITY;
@ -743,14 +755,16 @@ public class FileBackend {
quality -= 5; quality -= 5;
} }
scaledBitmap.recycle(); scaledBitmap.recycle();
} catch (FileNotFoundException e) { } catch (final FileNotFoundException e) {
cleanup(file);
throw new FileCopyException(R.string.error_file_not_found); throw new FileCopyException(R.string.error_file_not_found);
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); cleanup(file);
throw new FileCopyException(R.string.error_io_exception); throw new FileCopyException(R.string.error_io_exception);
} catch (SecurityException e) { } catch (SecurityException e) {
cleanup(file);
throw new FileCopyException(R.string.error_security_exception_during_image_copy); throw new FileCopyException(R.string.error_security_exception_during_image_copy);
} catch (OutOfMemoryError e) { } catch (final OutOfMemoryError e) {
++sampleSize; ++sampleSize;
if (sampleSize <= 3) { if (sampleSize <= 3) {
copyImageToPrivateStorage(file, image, sampleSize); copyImageToPrivateStorage(file, image, sampleSize);
@ -763,12 +777,20 @@ public class FileBackend {
} }
} }
public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException, NotAnImageFileException { private static void cleanup(final File file) {
try {
file.delete();
} catch (Exception e) {
}
}
public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException, ImageCompressionException {
Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath()); Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
copyImageToPrivateStorage(file, image, 0); copyImageToPrivateStorage(file, image, 0);
} }
public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException, NotAnImageFileException { public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException, ImageCompressionException {
switch (Config.IMAGE_FORMAT) { switch (Config.IMAGE_FORMAT) {
case JPEG: case JPEG:
message.setRelativeFilePath(message.getUuid() + ".jpg"); message.setRelativeFilePath(message.getUuid() + ".jpg");
@ -784,31 +806,49 @@ public class FileBackend {
updateFileParams(message); updateFileParams(message);
} }
public boolean unusualBounds(Uri image) { public boolean unusualBounds(final Uri image) {
try { try {
BitmapFactory.Options options = new BitmapFactory.Options(); final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options); final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(image);
BitmapFactory.decodeStream(inputStream, null, options);
close(inputStream);
float ratio = (float) options.outHeight / options.outWidth; float ratio = (float) options.outHeight / options.outWidth;
return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f); return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
} catch (Exception e) { } catch (final Exception e) {
Log.w(Config.LOGTAG, "unable to detect image bounds", e);
return false; return false;
} }
} }
private int getRotation(File file) { private int getRotation(final File file) {
return getRotation(Uri.parse("file://" + file.getAbsolutePath())); try (final InputStream inputStream = new FileInputStream(file)) {
return getRotation(inputStream);
} catch (Exception e) {
return 0;
}
} }
private int getRotation(Uri image) { private int getRotation(final Uri image) {
InputStream is = null; try (final InputStream is = mXmppConnectionService.getContentResolver().openInputStream(image)) {
try { return is == null ? 0 : getRotation(is);
is = mXmppConnectionService.getContentResolver().openInputStream(image); } catch (final Exception e) {
return ExifHelper.getOrientation(is); return 0;
} catch (FileNotFoundException e) { }
}
private static int getRotation(final InputStream inputStream) throws IOException {
final ExifInterface exif = new ExifInterface(inputStream);
final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return 0; return 0;
} finally {
close(is);
} }
} }
@ -829,11 +869,11 @@ public class FileBackend {
} else if (mime.startsWith("video/")) { } else if (mime.startsWith("video/")) {
thumbnail = getVideoPreview(file, size); thumbnail = getVideoPreview(file, size);
} else { } else {
Bitmap fullsize = getFullSizeImagePreview(file, size); final Bitmap fullSize = getFullSizeImagePreview(file, size);
if (fullsize == null) { if (fullSize == null) {
throw new FileNotFoundException(); throw new FileNotFoundException();
} }
thumbnail = resize(fullsize, size); thumbnail = resize(fullSize, size);
thumbnail = rotate(thumbnail, getRotation(file)); thumbnail = rotate(thumbnail, getRotation(file));
if (mime.equals("image/gif")) { if (mime.equals("image/gif")) {
Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true); Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
@ -1281,9 +1321,11 @@ public class FileBackend {
} }
private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException { private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
BitmapFactory.Options options = new BitmapFactory.Options(); final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options); final InputStream inputStream = mXmppConnectionService.getContentResolver().openInputStream(image);
BitmapFactory.decodeStream(inputStream, null, options);
close(inputStream);
return calcSampleSize(options, size); return calcSampleSize(options, size);
} }
@ -1291,7 +1333,7 @@ public class FileBackend {
updateFileParams(message, null); updateFileParams(message, null);
} }
public void updateFileParams(Message message, URL url) { public void updateFileParams(Message message, String url) {
DownloadableFile file = getFile(message); DownloadableFile file = getFile(message);
final String mime = file.getMimeType(); final String mime = file.getMimeType();
final boolean privateMessage = message.isPrivateMessage(); final boolean privateMessage = message.isPrivateMessage();
@ -1301,7 +1343,7 @@ public class FileBackend {
final boolean pdf = "application/pdf".equals(mime); final boolean pdf = "application/pdf".equals(mime);
final StringBuilder body = new StringBuilder(); final StringBuilder body = new StringBuilder();
if (url != null) { if (url != null) {
body.append(url.toString()); body.append(url);
} }
body.append('|').append(file.getSize()); body.append('|').append(file.getSize());
if (image || video || (pdf && Compatibility.runsTwentyOne())) { if (image || video || (pdf && Compatibility.runsTwentyOne())) {
@ -1439,18 +1481,23 @@ public class FileBackend {
} }
} }
public static class NotAnImageFileException extends Exception { public static class ImageCompressionException extends Exception {
ImageCompressionException(String message) {
super(message);
} }
}
public static class FileCopyException extends Exception { public static class FileCopyException extends Exception {
private final int resId; private final int resId;
private FileCopyException(int resId) { private FileCopyException(@StringRes int resId) {
this.resId = resId; this.resId = resId;
} }
public int getResId() { public @StringRes
int getResId() {
return resId; return resId;
} }
} }

View File

@ -5,6 +5,8 @@ import android.os.PowerManager;
import android.os.SystemClock; import android.os.SystemClock;
import android.util.Log; import android.util.Log;
import androidx.core.content.ContextCompat;
import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.io.CipherInputStream; import org.bouncycastle.crypto.io.CipherInputStream;
import org.bouncycastle.crypto.io.CipherOutputStream; import org.bouncycastle.crypto.io.CipherOutputStream;
@ -13,22 +15,25 @@ import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.KeyParameter;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import javax.crypto.NoSuchPaddingException; import javax.annotation.Nullable;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.utils.Compatibility; import eu.siacs.conversations.utils.Compatibility;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import static eu.siacs.conversations.entities.Transferable.VALID_CRYPTO_EXTENSIONS; import static eu.siacs.conversations.entities.Transferable.VALID_CRYPTO_EXTENSIONS;
@ -42,7 +47,7 @@ public class AbstractConnectionManager {
this.mXmppConnectionService = service; this.mXmppConnectionService = service;
} }
public static InputStream upgrade(DownloadableFile file, InputStream is) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, NoSuchProviderException { public static InputStream upgrade(DownloadableFile file, InputStream is) {
if (file.getKey() != null && file.getIv() != null) { if (file.getKey() != null && file.getIv() != null) {
AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine()); AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
cipher.init(true, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv())); cipher.init(true, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv()));
@ -52,6 +57,43 @@ public class AbstractConnectionManager {
} }
} }
//For progress tracking see:
//https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/Progress.java
public static RequestBody requestBody(final DownloadableFile file, final ProgressListener progressListener) {
return new RequestBody() {
@Override
public long contentLength() {
return file.getSize() + (file.getKey() != null ? 16 : 0);
}
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse(file.getMimeType());
}
@Override
public void writeTo(final BufferedSink sink) throws IOException {
long transmitted = 0;
try (final Source source = Okio.source(upgrade(file, new FileInputStream(file)))) {
long read;
while ((read = source.read(sink.buffer(), 8196)) != -1) {
transmitted += read;
sink.flush();
progressListener.onProgress(transmitted);
}
}
}
};
}
public interface ProgressListener {
void onProgress(long progress);
}
public static OutputStream createOutputStream(DownloadableFile file, boolean append, boolean decrypt) { public static OutputStream createOutputStream(DownloadableFile file, boolean append, boolean decrypt) {
FileOutputStream os; FileOutputStream os;
try { try {
@ -78,7 +120,8 @@ public class AbstractConnectionManager {
} }
public long getAutoAcceptFileSize() { public long getAutoAcceptFileSize() {
return this.mXmppConnectionService.getLongPreference("auto_accept_file_size", R.integer.auto_accept_filesize); final long autoAcceptFileSize = this.mXmppConnectionService.getLongPreference("auto_accept_file_size", R.integer.auto_accept_filesize);
return autoAcceptFileSize <= 0 ? -1 : autoAcceptFileSize;
} }
public boolean hasStoragePermission() { public boolean hasStoragePermission() {
@ -94,8 +137,8 @@ public class AbstractConnectionManager {
} }
} }
public PowerManager.WakeLock createWakeLock(String name) { public PowerManager.WakeLock createWakeLock(final String name) {
PowerManager powerManager = (PowerManager) mXmppConnectionService.getSystemService(Context.POWER_SERVICE); final PowerManager powerManager = ContextCompat.getSystemService(mXmppConnectionService, PowerManager.class);
return powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name); return powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
} }
@ -117,6 +160,7 @@ public class AbstractConnectionManager {
} }
public static Extension of(String path) { public static Extension of(String path) {
//TODO accept List<String> pathSegments
final int pos = path.lastIndexOf('/'); final int pos = path.lastIndexOf('/');
final String filename = path.substring(pos + 1).toLowerCase(); final String filename = path.substring(pos + 1).toLowerCase();
final String[] parts = filename.split("\\."); final String[] parts = filename.split("\\.");

View File

@ -3,19 +3,19 @@ package eu.siacs.conversations.services;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.util.Log; import android.util.Log;
import androidx.annotation.RequiresApi; import androidx.annotation.NonNull;
import net.ypresto.androidtranscoder.MediaTranscoder; import com.otaliastudios.transcoder.Transcoder;
import net.ypresto.androidtranscoder.format.MediaFormatStrategy; import com.otaliastudios.transcoder.TranscoderListener;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.Objects;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -26,11 +26,10 @@ import eu.siacs.conversations.entities.DownloadableFile;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.UiCallback; import eu.siacs.conversations.ui.UiCallback;
import eu.siacs.conversations.utils.Android360pFormatStrategy;
import eu.siacs.conversations.utils.Android720pFormatStrategy;
import eu.siacs.conversations.utils.MimeUtils; import eu.siacs.conversations.utils.MimeUtils;
import eu.siacs.conversations.utils.TranscoderStrategies;
public class AttachFileToConversationRunnable implements Runnable, MediaTranscoder.Listener { public class AttachFileToConversationRunnable implements Runnable, TranscoderListener {
private final XmppConnectionService mXmppConnectionService; private final XmppConnectionService mXmppConnectionService;
private final Message message; private final Message message;
@ -54,7 +53,7 @@ public class AttachFileToConversationRunnable implements Runnable, MediaTranscod
} }
boolean isVideoMessage() { boolean isVideoMessage() {
return this.isVideoMessage && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2; return this.isVideoMessage;
} }
private void processAsFile() { private void processAsFile() {
@ -89,20 +88,23 @@ public class AttachFileToConversationRunnable implements Runnable, MediaTranscod
} }
} }
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void processAsVideo() throws FileNotFoundException { private void processAsVideo() throws FileNotFoundException {
Log.d(Config.LOGTAG, "processing file as video"); Log.d(Config.LOGTAG, "processing file as video");
mXmppConnectionService.startForcingForegroundNotification(); mXmppConnectionService.startForcingForegroundNotification();
message.setRelativeFilePath(message.getUuid() + ".mp4"); message.setRelativeFilePath(message.getUuid() + ".mp4");
final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message); final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
final MediaFormatStrategy formatStrategy = "720".equals(getVideoCompression()) ? new Android720pFormatStrategy() : new Android360pFormatStrategy(); if (Objects.requireNonNull(file.getParentFile()).mkdirs()) {
file.getParentFile().mkdirs(); Log.d(Config.LOGTAG, "created parent directory for video file");
final ParcelFileDescriptor parcelFileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
if (parcelFileDescriptor == null) {
throw new FileNotFoundException("Parcel File Descriptor was null");
} }
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Future<Void> future = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), formatStrategy, this); final boolean highQuality = "720".equals(getVideoCompression());
final Future<Void> future = Transcoder.into(file.getAbsolutePath()).
addDataSource(mXmppConnectionService, uri)
.setVideoTrackStrategy(highQuality ? TranscoderStrategies.VIDEO_720P : TranscoderStrategies.VIDEO_360P)
.setAudioTrackStrategy(highQuality ? TranscoderStrategies.AUDIO_HQ : TranscoderStrategies.AUDIO_MQ)
.setListener(this)
.transcode();
try { try {
future.get(); future.get();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -127,7 +129,7 @@ public class AttachFileToConversationRunnable implements Runnable, MediaTranscod
} }
@Override @Override
public void onTranscodeCompleted() { public void onTranscodeCompleted(int successCode) {
mXmppConnectionService.stopForcingForegroundNotification(); mXmppConnectionService.stopForcingForegroundNotification();
final File file = mXmppConnectionService.getFileBackend().getFile(message); final File file = mXmppConnectionService.getFileBackend().getFile(message);
long convertedFileSize = mXmppConnectionService.getFileBackend().getFile(message).getSize(); long convertedFileSize = mXmppConnectionService.getFileBackend().getFile(message).getSize();
@ -157,9 +159,9 @@ public class AttachFileToConversationRunnable implements Runnable, MediaTranscod
} }
@Override @Override
public void onTranscodeFailed(Exception e) { public void onTranscodeFailed(@NonNull @NotNull Throwable exception) {
mXmppConnectionService.stopForcingForegroundNotification(); mXmppConnectionService.stopForcingForegroundNotification();
Log.d(Config.LOGTAG,"video transcoding failed",e); Log.d(Config.LOGTAG, "video transcoding failed", exception);
processAsFile(); processAsFile();
} }

View File

@ -50,14 +50,9 @@ public class ChannelDiscoveryService {
} }
void initializeMuclumbusService() { void initializeMuclumbusService() {
final OkHttpClient.Builder builder = new OkHttpClient.Builder(); final OkHttpClient.Builder builder = HttpConnectionManager.OK_HTTP_CLIENT.newBuilder();
if (service.useTorToConnect()) { if (service.useTorToConnect()) {
try {
builder.proxy(HttpConnectionManager.getProxy()); builder.proxy(HttpConnectionManager.getProxy());
} catch (IOException e) {
throw new RuntimeException("Unable to use Tor proxy", e);
}
} }
Retrofit retrofit = new Retrofit.Builder() Retrofit retrofit = new Retrofit.Builder()
.client(builder.build()) .client(builder.build())
@ -73,7 +68,7 @@ public class ChannelDiscoveryService {
} }
void discover(@NonNull final String query, Method method, OnChannelSearchResultsFound onChannelSearchResultsFound) { void discover(@NonNull final String query, Method method, OnChannelSearchResultsFound onChannelSearchResultsFound) {
List<Room> result = cache.getIfPresent(key(method, query)); final List<Room> result = cache.getIfPresent(key(method, query));
if (result != null) { if (result != null) {
onChannelSearchResultsFound.onChannelSearchResultsFound(result); onChannelSearchResultsFound.onChannelSearchResultsFound(result);
return; return;

View File

@ -31,6 +31,7 @@ import android.app.NotificationManager;
import android.app.Service; import android.app.Service;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri; import android.net.Uri;
import android.os.Handler; import android.os.Handler;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
@ -40,19 +41,20 @@ import android.util.SparseArray;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.CharStreams;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.MessageDigest; import java.security.MessageDigest;
@ -60,12 +62,10 @@ import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateParsingException; import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -73,16 +73,14 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.DomainHostnameVerifier; import eu.siacs.conversations.crypto.XmppDomainVerifier;
import eu.siacs.conversations.entities.MTMDecision; import eu.siacs.conversations.entities.MTMDecision;
import eu.siacs.conversations.http.HttpConnectionManager;
import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.MemorizingActivity; import eu.siacs.conversations.ui.MemorizingActivity;
@ -98,12 +96,12 @@ import eu.siacs.conversations.ui.MemorizingActivity;
*/ */
public class MemorizingTrustManager { public class MemorizingTrustManager {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
final static String DECISION_INTENT = "de.duenndns.ssl.DECISION"; final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
public final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId"; public final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
public final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert"; public final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
public final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId"; public final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found."; final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found.";
private static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"); private static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"); private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
@ -111,7 +109,6 @@ public class MemorizingTrustManager {
private static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z"); private static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z"); private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName()); private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName());
private final static int NOTIFICATION_ID = 100509;
static String KEYSTORE_DIR = "KeyStore"; static String KEYSTORE_DIR = "KeyStore";
static String KEYSTORE_FILE = "KeyStore.bks"; static String KEYSTORE_FILE = "KeyStore.bks";
private static int decisionId = 0; private static int decisionId = 0;
@ -165,20 +162,6 @@ public class MemorizingTrustManager {
this.defaultTrustManager = getTrustManager(null); this.defaultTrustManager = getTrustManager(null);
} }
/**
* Changes the path for the KeyStore file.
* <p>
* The actual filename relative to the app's directory will be
* <code>app_<i>dirname</i>/<i>filename</i></code>.
*
* @param dirname directory to store the KeyStore.
* @param filename file name for the KeyStore.
*/
public static void setKeyStoreFile(String dirname, String filename) {
KEYSTORE_DIR = dirname;
KEYSTORE_FILE = filename;
}
private static boolean isIp(final String server) { private static boolean isIp(final String server) {
return server != null && ( return server != null && (
PATTERN_IPV4.matcher(server).matches() PATTERN_IPV4.matcher(server).matches()
@ -214,9 +197,7 @@ public class MemorizingTrustManager {
MessageDigest md = MessageDigest.getInstance(digest); MessageDigest md = MessageDigest.getInstance(digest);
md.update(cert.getEncoded()); md.update(cert.getEncoded());
return hexString(md.digest()); return hexString(md.digest());
} catch (java.security.cert.CertificateEncodingException e) { } catch (CertificateEncodingException | NoSuchAlgorithmException e) {
return e.getMessage();
} catch (java.security.NoSuchAlgorithmException e) {
return e.getMessage(); return e.getMessage();
} }
} }
@ -237,7 +218,7 @@ public class MemorizingTrustManager {
} }
} }
void init(Context m) { void init(final Context m) {
master = m; master = m;
masterHandler = new Handler(m.getMainLooper()); masterHandler = new Handler(m.getMainLooper());
notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE);
@ -260,36 +241,6 @@ public class MemorizingTrustManager {
appKeyStore = loadAppKeyStore(); appKeyStore = loadAppKeyStore();
} }
/**
* Binds an Activity to the MTM for displaying the query dialog.
* <p>
* This is useful if your connection is run from a service that is
* triggered by user interaction -- in such cases the activity is
* visible and the user tends to ignore the service notification.
* <p>
* You should never have a hidden activity bound to MTM! Use this
* function in onResume() and @see unbindDisplayActivity in onPause().
*
* @param act Activity to be bound
*/
public void bindDisplayActivity(AppCompatActivity act) {
foregroundAct = act;
}
/**
* Removes an Activity from the MTM display stack.
* <p>
* Always call this function when the Activity added with
* {@link #bindDisplayActivity(AppCompatActivity)} is hidden.
*
* @param act Activity to be unbound
*/
public void unbindDisplayActivity(AppCompatActivity act) {
// do not remove if it was overridden by a different activity
if (foregroundAct == act)
foregroundAct = null;
}
/** /**
* Get a list of all certificate aliases stored in MTM. * Get a list of all certificate aliases stored in MTM.
* *
@ -304,21 +255,6 @@ public class MemorizingTrustManager {
} }
} }
/**
* Get a certificate for a given alias.
*
* @param alias the certificate's alias as returned by {@link #getCertificates()}.
* @return the certificate associated with the alias or <tt>null</tt> if none found.
*/
public Certificate getCertificate(String alias) {
try {
return appKeyStore.getCertificate(alias);
} catch (KeyStoreException e) {
// this should never happen, however...
throw new RuntimeException(e);
}
}
/** /**
* Removes the given certificate from MTMs key store. * Removes the given certificate from MTMs key store.
* *
@ -337,32 +273,6 @@ public class MemorizingTrustManager {
keyStoreUpdated(); keyStoreUpdated();
} }
/**
* Creates a new hostname verifier supporting user interaction.
*
* <p>This method creates a new {@link HostnameVerifier} that is bound to
* the given instance of {@link MemorizingTrustManager}, and leverages an
* existing {@link HostnameVerifier}. The returned verifier performs the
* following steps, returning as soon as one of them succeeds:
* /p>
* <ol>
* <li>Success, if the wrapped defaultVerifier accepts the certificate.</li>
* <li>Success, if the server certificate is stored in the keystore under the given hostname.</li>
* <li>Ask the user and return accordingly.</li>
* <li>Failure on exception.</li>
* </ol>
*
* @param defaultVerifier the {@link HostnameVerifier} that should perform the actual check
* @return a new hostname verifier using the MTM's key store
* @throws IllegalArgumentException if the defaultVerifier parameter is null
*/
public DomainHostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier, final boolean interactive) {
if (defaultVerifier == null)
throw new IllegalArgumentException("The default verifier may not be null");
return new MemorizingHostnameVerifier(defaultVerifier, interactive);
}
X509TrustManager getTrustManager(KeyStore ks) { X509TrustManager getTrustManager(KeyStore ks) {
try { try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
@ -449,16 +359,8 @@ public class MemorizingTrustManager {
} }
} }
private boolean isExpiredException(Throwable e) {
do {
if (e instanceof CertificateExpiredException)
return true;
e = e.getCause();
} while (e != null);
return false;
}
public void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive) private void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive)
throws CertificateException { throws CertificateException {
LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")"); LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
try { try {
@ -467,13 +369,8 @@ public class MemorizingTrustManager {
appTrustManager.checkServerTrusted(chain, authType); appTrustManager.checkServerTrusted(chain, authType);
else else
appTrustManager.checkClientTrusted(chain, authType); appTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ae) { } catch (final CertificateException ae) {
LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae); LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae);
// if the cert is stored in our appTrustManager, we ignore expiredness
if (isExpiredException(ae)) {
LOGGER.log(Level.INFO, "checkCertTrusted: accepting expired certificate from keystore");
return;
}
if (isCertKnown(chain[0])) { if (isCertKnown(chain[0])) {
LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore"); LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore");
return; return;
@ -486,15 +383,18 @@ public class MemorizingTrustManager {
defaultTrustManager.checkServerTrusted(chain, authType); defaultTrustManager.checkServerTrusted(chain, authType);
else else
defaultTrustManager.checkClientTrusted(chain, authType); defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException e) { } catch (final CertificateException e) {
boolean trustSystemCAs = !PreferenceManager.getDefaultSharedPreferences(master).getBoolean("dont_trust_system_cas", false); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(master);
if (domain != null && isServer && trustSystemCAs && !isIp(domain)) { final boolean trustSystemCAs = !preferences.getBoolean("dont_trust_system_cas", false);
if (domain != null && isServer && trustSystemCAs && !isIp(domain) && !domain.endsWith(".onion")) {
final String hash = getBase64Hash(chain[0], "SHA-256"); final String hash = getBase64Hash(chain[0], "SHA-256");
final List<String> fingerprints = getPoshFingerprints(domain); final List<String> fingerprints = getPoshFingerprints(domain);
if (hash != null && fingerprints.size() > 0) { if (hash != null && fingerprints.size() > 0) {
if (fingerprints.contains(hash)) { if (fingerprints.contains(hash)) {
Log.d("mtm", "trusted cert fingerprint of " + domain + " via posh"); Log.d("mtm", "trusted cert fingerprint of " + domain + " via posh");
return; return;
} else {
Log.d("mtm", "fingerprint " + hash + " not found in " + fingerprints);
} }
if (getPoshCacheFile(domain).delete()) { if (getPoshCacheFile(domain).delete()) {
Log.d("mtm", "deleted posh file for " + domain + " after not being able to verify"); Log.d("mtm", "deleted posh file for " + domain + " after not being able to verify");
@ -511,7 +411,7 @@ public class MemorizingTrustManager {
} }
private List<String> getPoshFingerprints(String domain) { private List<String> getPoshFingerprints(String domain) {
List<String> cached = getPoshFingerprintsFromCache(domain); final List<String> cached = getPoshFingerprintsFromCache(domain);
if (cached == null) { if (cached == null) {
return getPoshFingerprintsFromServer(domain); return getPoshFingerprintsFromServer(domain);
} else { } else {
@ -525,19 +425,13 @@ public class MemorizingTrustManager {
private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) { private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
Log.d("mtm", "downloading json for " + domain + " from " + url); Log.d("mtm", "downloading json for " + domain + " from " + url);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(master);
final boolean useTor = QuickConversationsService.isConversations() && preferences.getBoolean("use_tor", master.getResources().getBoolean(R.bool.use_tor));
try { try {
List<String> results = new ArrayList<>(); final List<String> results = new ArrayList<>();
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); final InputStream inputStream = HttpConnectionManager.open(url, useTor);
connection.setConnectTimeout(5000); final String body = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
connection.setReadTimeout(5000); final JSONObject jsonObject = new JSONObject(body);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
builder.append(inputLine);
}
JSONObject jsonObject = new JSONObject(builder.toString());
in.close();
int expires = jsonObject.getInt("expires"); int expires = jsonObject.getInt("expires");
if (expires <= 0) { if (expires <= 0) {
return new ArrayList<>(); return new ArrayList<>();
@ -554,17 +448,15 @@ public class MemorizingTrustManager {
if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) { if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
return getPoshFingerprintsFromServer(domain, redirect, expires, false); return getPoshFingerprintsFromServer(domain, redirect, expires, false);
} }
JSONArray fingerprints = jsonObject.getJSONArray("fingerprints"); final JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
for (int i = 0; i < fingerprints.length(); i++) { for (int i = 0; i < fingerprints.length(); i++) {
JSONObject fingerprint = fingerprints.getJSONObject(i); final JSONObject fingerprint = fingerprints.getJSONObject(i);
String sha256 = fingerprint.getString("sha-256"); final String sha256 = fingerprint.getString("sha-256");
if (sha256 != null) {
results.add(sha256); results.add(sha256);
} }
}
writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis()); writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
return results; return results;
} catch (Exception e) { } catch (final Exception e) {
Log.d("mtm", "error fetching posh " + e.getMessage()); Log.d("mtm", "error fetching posh " + e.getMessage());
return new ArrayList<>(); return new ArrayList<>();
} }
@ -575,7 +467,7 @@ public class MemorizingTrustManager {
} }
private void writeFingerprintsToCache(String domain, List<String> results, long expires) { private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
File file = getPoshCacheFile(domain); final File file = getPoshCacheFile(domain);
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
try { try {
file.createNewFile(); file.createNewFile();
@ -592,20 +484,11 @@ public class MemorizingTrustManager {
} }
private List<String> getPoshFingerprintsFromCache(String domain) { private List<String> getPoshFingerprintsFromCache(String domain) {
File file = getPoshCacheFile(domain); final File file = getPoshCacheFile(domain);
try { try {
InputStream is = new FileInputStream(file); final InputStream inputStream = new FileInputStream(file);
BufferedReader buf = new BufferedReader(new InputStreamReader(is)); final String json = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
final JSONObject jsonObject = new JSONObject(json);
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line).append("\n");
line = buf.readLine();
}
JSONObject jsonObject = new JSONObject(sb.toString());
is.close();
long expires = jsonObject.getLong("expires"); long expires = jsonObject.getLong("expires");
long expiresIn = expires - System.currentTimeMillis(); long expiresIn = expires - System.currentTimeMillis();
if (expiresIn < 0) { if (expiresIn < 0) {
@ -614,15 +497,13 @@ public class MemorizingTrustManager {
} else { } else {
Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s"); Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
} }
List<String> result = new ArrayList<>(); final List<String> result = new ArrayList<>();
JSONArray jsonArray = jsonObject.getJSONArray("fingerprints"); final JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
for (int i = 0; i < jsonArray.length(); ++i) { for (int i = 0; i < jsonArray.length(); ++i) {
result.add(jsonArray.getString(i)); result.add(jsonArray.getString(i));
} }
return result; return result;
} catch (FileNotFoundException e) { } catch (final IOException e) {
return null;
} catch (IOException e) {
return null; return null;
} catch (JSONException e) { } catch (JSONException e) {
file.delete(); file.delete();
@ -632,7 +513,7 @@ public class MemorizingTrustManager {
private X509Certificate[] getAcceptedIssuers() { private X509Certificate[] getAcceptedIssuers() {
LOGGER.log(Level.FINE, "getAcceptedIssuers()"); LOGGER.log(Level.FINE, "getAcceptedIssuers()");
return defaultTrustManager.getAcceptedIssuers(); return defaultTrustManager == null ? new X509Certificate[0] : defaultTrustManager.getAcceptedIssuers();
} }
private int createDecisionId(MTMDecision d) { private int createDecisionId(MTMDecision d) {
@ -645,14 +526,24 @@ public class MemorizingTrustManager {
return myId; return myId;
} }
private void certDetails(StringBuffer si, X509Certificate c) { private void certDetails(final StringBuffer si, final X509Certificate c, final boolean showValidFor) {
SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
si.append("\n"); si.append("\n");
si.append(c.getSubjectDN().toString()); if (showValidFor) {
try {
si.append("Valid for: ");
si.append(Joiner.on(", ").join(XmppDomainVerifier.parseValidDomains(c).all()));
} catch (final CertificateParsingException e) {
si.append("Unable to parse Certificate");
}
si.append("\n"); si.append("\n");
si.append(validityDateFormater.format(c.getNotBefore())); } else {
si.append(c.getSubjectDN());
}
si.append("\n");
si.append(DATE_FORMAT.format(c.getNotBefore()));
si.append(" - "); si.append(" - ");
si.append(validityDateFormater.format(c.getNotAfter())); si.append(DATE_FORMAT.format(c.getNotAfter()));
si.append("\nSHA-256: "); si.append("\nSHA-256: ");
si.append(certHash(c, "SHA-256")); si.append(certHash(c, "SHA-256"));
si.append("\nSHA-1: "); si.append("\nSHA-1: ");
@ -665,7 +556,7 @@ public class MemorizingTrustManager {
private String certChainMessage(final X509Certificate[] chain, CertificateException cause) { private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
Throwable e = cause; Throwable e = cause;
LOGGER.log(Level.FINE, "certChainMessage for " + e); LOGGER.log(Level.FINE, "certChainMessage for " + e);
StringBuffer si = new StringBuffer(); final StringBuffer si = new StringBuffer();
if (e.getCause() != null) { if (e.getCause() != null) {
e = e.getCause(); e = e.getCause();
// HACK: there is no sane way to check if the error is a "trust anchor // HACK: there is no sane way to check if the error is a "trust anchor
@ -680,46 +571,13 @@ public class MemorizingTrustManager {
si.append(master.getString(R.string.mtm_connect_anyway)); si.append(master.getString(R.string.mtm_connect_anyway));
si.append("\n\n"); si.append("\n\n");
si.append(master.getString(R.string.mtm_cert_details)); si.append(master.getString(R.string.mtm_cert_details));
for (X509Certificate c : chain) { si.append('\n');
certDetails(si, c); for(int i = 0; i < chain.length; ++i) {
certDetails(si, chain[i], i == 0);
} }
return si.toString(); return si.toString();
} }
private String hostNameMessage(X509Certificate cert, String hostname) {
StringBuffer si = new StringBuffer();
si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
si.append("\n\n");
try {
Collection<List<?>> sans = cert.getSubjectAlternativeNames();
if (sans == null) {
si.append(cert.getSubjectDN());
si.append("\n");
} else for (List<?> altName : sans) {
Object name = altName.get(1);
if (name instanceof String) {
si.append("[");
si.append(altName.get(0));
si.append("] ");
si.append(name);
si.append("\n");
}
}
} catch (CertificateParsingException e) {
e.printStackTrace();
si.append("<Parsing error: ");
si.append(e.getLocalizedMessage());
si.append(">\n");
}
si.append("\n");
si.append(master.getString(R.string.mtm_connect_anyway));
si.append("\n\n");
si.append(master.getString(R.string.mtm_cert_details));
certDetails(si, cert);
return si.toString();
}
/** /**
* Returns the top-most entry of the activity stack. * Returns the top-most entry of the activity stack.
* *
@ -777,17 +635,6 @@ public class MemorizingTrustManager {
} }
} }
boolean interactHostname(X509Certificate cert, String hostname) {
switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
case MTMDecision.DECISION_ALWAYS:
storeCert(hostname, cert);
case MTMDecision.DECISION_ONCE:
return true;
default:
return false;
}
}
public X509TrustManager getNonInteractive(String domain) { public X509TrustManager getNonInteractive(String domain) {
return new NonInteractiveMemorizingTrustManager(domain); return new NonInteractiveMemorizingTrustManager(domain);
} }
@ -804,57 +651,6 @@ public class MemorizingTrustManager {
return new InteractiveMemorizingTrustManager(null); return new InteractiveMemorizingTrustManager(null);
} }
class MemorizingHostnameVerifier implements DomainHostnameVerifier {
private final HostnameVerifier defaultVerifier;
private final boolean interactive;
public MemorizingHostnameVerifier(HostnameVerifier wrapped, boolean interactive) {
this.defaultVerifier = wrapped;
this.interactive = interactive;
}
@Override
public boolean verify(String domain, String hostname, SSLSession session) {
LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
// if the default verifier accepts the hostname, we are done
if (defaultVerifier instanceof DomainHostnameVerifier) {
if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
return true;
}
} else {
if (defaultVerifier.verify(domain, session)) {
return true;
}
}
// otherwise, we check if the hostname is an alias for this cert in our keystore
try {
X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
//Log.d(TAG, "cert: " + cert);
if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
return true;
} else {
LOGGER.log(Level.FINE, "server " + domain + " provided wrong certificate, asking user.");
if (interactive) {
return interactHostname(cert, domain);
} else {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean verify(String domain, SSLSession sslSession) {
return verify(domain, null, sslSession);
}
}
private class NonInteractiveMemorizingTrustManager implements X509TrustManager { private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
private final String domain; private final String domain;

View File

@ -209,7 +209,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
void executePendingQueries(final Account account) { void executePendingQueries(final Account account) {
List<Query> pending = new ArrayList<>(); final List<Query> pending = new ArrayList<>();
synchronized (this.pendingQueries) { synchronized (this.pendingQueries) {
for (Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext(); ) { for (Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext(); ) {
Query query = iterator.next(); Query query = iterator.next();
@ -390,8 +390,17 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
void kill(Conversation conversation) { void kill(final Conversation conversation) {
final ArrayList<Query> toBeKilled = new ArrayList<>(); final ArrayList<Query> toBeKilled = new ArrayList<>();
synchronized (this.pendingQueries) {
for (final Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext(); ) {
final Query query = iterator.next();
if (query.getConversation() == conversation) {
iterator.remove();
Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": killed pending MAM query for archived conversation");
}
}
}
synchronized (this.queries) { synchronized (this.queries) {
for (final Query q : queries) { for (final Query q : queries) {
if (q.conversation == conversation) { if (q.conversation == conversation) {
@ -399,7 +408,7 @@ public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
} }
} }
} }
for (Query q : toBeKilled) { for (final Query q : toBeKilled) {
kill(q); kill(q);
} }
} }

View File

@ -12,10 +12,12 @@ import android.content.res.Resources;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.media.AudioAttributes; import android.media.AudioAttributes;
import android.media.Ringtone;
import android.media.RingtoneManager; import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.SystemClock; import android.os.SystemClock;
import android.os.Vibrator;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.style.StyleSpan; import android.text.style.StyleSpan;
@ -32,6 +34,9 @@ import androidx.core.app.RemoteInput;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.IconCompat; import androidx.core.graphics.drawable.IconCompat;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -43,6 +48,10 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -70,12 +79,13 @@ import eu.siacs.conversations.xmpp.jingle.Media;
public class NotificationService { public class NotificationService {
private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
public static final Object CATCHUP_LOCK = new Object(); public static final Object CATCHUP_LOCK = new Object();
private static final int LED_COLOR = 0xff00ff00; private static final int LED_COLOR = 0xff00ff00;
private static final int CALL_DAT = 120; private static final long[] CALL_PATTERN = {0, 500, 300, 600};
private static final long[] CALL_PATTERN = {0, 3 * CALL_DAT, CALL_DAT, CALL_DAT, 3 * CALL_DAT, CALL_DAT, CALL_DAT};
private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations"; private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024; private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
@ -92,6 +102,10 @@ public class NotificationService {
private boolean mIsInForeground; private boolean mIsInForeground;
private long mLastNotification; private long mLastNotification;
private static final String INCOMING_CALLS_NOTIFICATION_CHANNEL = "incoming_calls_channel";
private Ringtone currentlyPlayingRingtone = null;
private ScheduledFuture<?> vibrationFuture;
NotificationService(final XmppConnectionService service) { NotificationService(final XmppConnectionService service) {
this.mXmppConnectionService = service; this.mXmppConnectionService = service;
} }
@ -129,6 +143,7 @@ public class NotificationService {
} }
notificationManager.deleteNotificationChannel("export"); notificationManager.deleteNotificationChannel("export");
notificationManager.deleteNotificationChannel("incoming_calls");
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information))); notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages))); notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
@ -136,7 +151,7 @@ public class NotificationService {
final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground", final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
c.getString(R.string.foreground_service_channel_name), c.getString(R.string.foreground_service_channel_name),
NotificationManager.IMPORTANCE_MIN); NotificationManager.IMPORTANCE_MIN);
foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description)); foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description, c.getString(R.string.app_name)));
foregroundServiceChannel.setShowBadge(false); foregroundServiceChannel.setShowBadge(false);
foregroundServiceChannel.setGroup("status"); foregroundServiceChannel.setGroup("status");
notificationManager.createNotificationChannel(foregroundServiceChannel); notificationManager.createNotificationChannel(foregroundServiceChannel);
@ -162,20 +177,16 @@ public class NotificationService {
exportChannel.setGroup("status"); exportChannel.setGroup("status");
notificationManager.createNotificationChannel(exportChannel); notificationManager.createNotificationChannel(exportChannel);
final NotificationChannel incomingCallsChannel = new NotificationChannel("incoming_calls", final NotificationChannel incomingCallsChannel = new NotificationChannel(INCOMING_CALLS_NOTIFICATION_CHANNEL,
c.getString(R.string.incoming_calls_channel_name), c.getString(R.string.incoming_calls_channel_name),
NotificationManager.IMPORTANCE_HIGH); NotificationManager.IMPORTANCE_HIGH);
incomingCallsChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE), new AudioAttributes.Builder() incomingCallsChannel.setSound(null, null);
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
.build());
incomingCallsChannel.setShowBadge(false); incomingCallsChannel.setShowBadge(false);
incomingCallsChannel.setLightColor(LED_COLOR); incomingCallsChannel.setLightColor(LED_COLOR);
incomingCallsChannel.enableLights(true); incomingCallsChannel.enableLights(true);
incomingCallsChannel.setGroup("calls"); incomingCallsChannel.setGroup("calls");
incomingCallsChannel.setBypassDnd(true); incomingCallsChannel.setBypassDnd(true);
incomingCallsChannel.enableVibration(true); incomingCallsChannel.enableVibration(false);
incomingCallsChannel.setVibrationPattern(CALL_PATTERN);
notificationManager.createNotificationChannel(incomingCallsChannel); notificationManager.createNotificationChannel(incomingCallsChannel);
final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls", final NotificationChannel ongoingCallsChannel = new NotificationChannel("ongoing_calls",
@ -358,8 +369,8 @@ public class NotificationService {
public void pushFailedDelivery(final Message message) { public void pushFailedDelivery(final Message message) {
final Conversation conversation = (Conversation) message.getConversation(); final Conversation conversation = (Conversation) message.getConversation();
final boolean isScreenOn = mXmppConnectionService.isInteractive(); final boolean isScreenLocked = !mXmppConnectionService.isScreenLocked();
if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) { if (this.mIsInForeground && isScreenLocked && this.mOpenConversation == message.getConversation()) {
Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing failed delivery notification because conversation is open"); Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing failed delivery notification because conversation is open");
return; return;
} }
@ -387,14 +398,56 @@ public class NotificationService {
notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification); notify(DELIVERY_FAILED_NOTIFICATION_ID, summaryNotification);
} }
public void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) { public synchronized void startRinging(final AbstractJingleConnection.Id id, final Set<Media> media) {
showIncomingCallNotification(id, media);
final NotificationManager notificationManager = (NotificationManager) mXmppConnectionService.getSystemService(Context.NOTIFICATION_SERVICE);
final int currentInterruptionFilter;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager != null) {
currentInterruptionFilter = notificationManager.getCurrentInterruptionFilter();
} else {
currentInterruptionFilter = 1; //INTERRUPTION_FILTER_ALL
}
if (currentInterruptionFilter != 1) {
Log.d(Config.LOGTAG, "do not ring or vibrate because interruption filter has been set to " + currentInterruptionFilter);
return;
}
final ScheduledFuture<?> currentVibrationFuture = this.vibrationFuture;
this.vibrationFuture = SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(
new VibrationRunnable(),
0,
3,
TimeUnit.SECONDS
);
if (currentVibrationFuture != null) {
currentVibrationFuture.cancel(true);
}
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
final Resources resources = mXmppConnectionService.getResources();
final String ringtonePreference = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
if (Strings.isNullOrEmpty(ringtonePreference)) {
Log.d(Config.LOGTAG, "ringtone has been set to none");
return;
}
final Uri uri = Uri.parse(ringtonePreference);
this.currentlyPlayingRingtone = RingtoneManager.getRingtone(mXmppConnectionService, uri);
if (this.currentlyPlayingRingtone == null) {
Log.d(Config.LOGTAG, "unable to find ringtone for uri " + uri);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
this.currentlyPlayingRingtone.setLooping(true);
}
this.currentlyPlayingRingtone.play();
}
private void showIncomingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) {
final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class); final Intent fullScreenIntent = new Intent(mXmppConnectionService, RtpSessionActivity.class);
fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString()); fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_ACCOUNT, id.account.getJid().asBareJid().toEscapedString());
fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString()); fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_WITH, id.with.toEscapedString());
fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId); fullScreenIntent.putExtra(RtpSessionActivity.EXTRA_SESSION_ID, id.sessionId);
fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); fullScreenIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "incoming_calls"); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, INCOMING_CALLS_NOTIFICATION_CHANNEL);
if (media.contains(Media.VIDEO)) { if (media.contains(Media.VIDEO)) {
builder.setSmallIcon(R.drawable.ic_videocam_white_24dp); builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call)); builder.setContentTitle(mXmppConnectionService.getString(R.string.rtp_state_incoming_video_call));
@ -435,15 +488,24 @@ public class NotificationService {
notify(INCOMING_CALL_NOTIFICATION_ID, notification); notify(INCOMING_CALL_NOTIFICATION_ID, notification);
} }
public Notification getOngoingCallNotification(final AbstractJingleConnection.Id id, final Set<Media> media) { public Notification getOngoingCallNotification(final XmppConnectionService.OngoingCall ongoingCall) {
final AbstractJingleConnection.Id id = ongoingCall.id;
final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls"); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mXmppConnectionService, "ongoing_calls");
if (media.contains(Media.VIDEO)) { if (ongoingCall.media.contains(Media.VIDEO)) {
builder.setSmallIcon(R.drawable.ic_videocam_white_24dp); builder.setSmallIcon(R.drawable.ic_videocam_white_24dp);
if (ongoingCall.reconnecting) {
builder.setContentTitle(mXmppConnectionService.getString(R.string.reconnecting_video_call));
} else {
builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call)); builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_video_call));
}
} else { } else {
builder.setSmallIcon(R.drawable.ic_call_white_24dp); builder.setSmallIcon(R.drawable.ic_call_white_24dp);
if (ongoingCall.reconnecting) {
builder.setContentTitle(mXmppConnectionService.getString(R.string.reconnecting_call));
} else {
builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call)); builder.setContentTitle(mXmppConnectionService.getString(R.string.ongoing_call));
} }
}
builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName()); builder.setContentText(id.account.getRoster().getContact(id.with).getDisplayName());
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setPriority(NotificationCompat.PRIORITY_HIGH);
@ -468,9 +530,27 @@ public class NotificationService {
} }
public void cancelIncomingCallNotification() { public void cancelIncomingCallNotification() {
stopSoundAndVibration();
cancel(INCOMING_CALL_NOTIFICATION_ID); cancel(INCOMING_CALL_NOTIFICATION_ID);
} }
public boolean stopSoundAndVibration() {
int stopped = 0;
if (this.currentlyPlayingRingtone != null) {
if (this.currentlyPlayingRingtone.isPlaying()) {
Log.d(Config.LOGTAG, "stop playing ring tone");
++stopped;
}
this.currentlyPlayingRingtone.stop();
}
if (this.vibrationFuture != null && !this.vibrationFuture.isCancelled()) {
Log.d(Config.LOGTAG, "stop vibration");
this.vibrationFuture.cancel(true);
++stopped;
}
return stopped > 0;
}
public static void cancelIncomingCallNotification(final Context context) { public static void cancelIncomingCallNotification(final Context context) {
final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
try { try {
@ -486,8 +566,8 @@ public class NotificationService {
Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off"); Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
return; return;
} }
final boolean isScreenOn = mXmppConnectionService.isInteractive(); final boolean isScreenLocked = mXmppConnectionService.isScreenLocked();
if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) { if (this.mIsInForeground && !isScreenLocked && this.mOpenConversation == message.getConversation()) {
Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open"); Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
return; return;
} }
@ -495,7 +575,7 @@ public class NotificationService {
pushToStack(message); pushToStack(message);
final Conversational conversation = message.getConversation(); final Conversational conversation = message.getConversation();
final Account account = conversation.getAccount(); final Account account = conversation.getAccount();
final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn) final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || isScreenLocked)
&& !account.inGracePeriod() && !account.inGracePeriod()
&& !this.inMiniGracePeriod(account); && !this.inMiniGracePeriod(account);
updateNotification(doNotify, Collections.singletonList(conversation.getUuid())); updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
@ -636,17 +716,7 @@ public class NotificationService {
} }
} }
private void modifyIncomingCall(Builder mBuilder) { private void modifyIncomingCall(final Builder mBuilder) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
final Resources resources = mXmppConnectionService.getResources();
final String ringtone = preferences.getString("call_ringtone", resources.getString(R.string.incoming_call_ringtone));
mBuilder.setVibrate(CALL_PATTERN);
final Uri uri = Uri.parse(ringtone);
try {
mBuilder.setSound(fixRingtoneUri(uri));
} catch (SecurityException e) {
Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
}
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
setNotificationColor(mBuilder); setNotificationColor(mBuilder);
mBuilder.setLights(LED_COLOR, 2000, 3000); mBuilder.setLights(LED_COLOR, 2000, 3000);
@ -730,17 +800,18 @@ public class NotificationService {
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
.setShowsUserInterface(false) .setShowsUserInterface(false)
.build(); .build();
String replyLabel = mXmppConnectionService.getString(R.string.reply); final String replyLabel = mXmppConnectionService.getString(R.string.reply);
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder( final String lastMessageUuid = Iterables.getLast(messages).getUuid();
final NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
R.drawable.ic_send_text_offline, R.drawable.ic_send_text_offline,
replyLabel, replyLabel,
createReplyIntent(conversation, false)) createReplyIntent(conversation, lastMessageUuid, false))
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
.setShowsUserInterface(false) .setShowsUserInterface(false)
.addRemoteInput(remoteInput).build(); .addRemoteInput(remoteInput).build();
NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply, final NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
replyLabel, replyLabel,
createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build(); createReplyIntent(conversation, lastMessageUuid, true)).addRemoteInput(remoteInput).build();
mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction)); mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
int addedActionsCount = 1; int addedActionsCount = 1;
mBuilder.addAction(markReadAction); mBuilder.addAction(markReadAction);
@ -1006,13 +1077,14 @@ public class NotificationService {
return PendingIntent.getService(mXmppConnectionService, 0, intent, 0); return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
} }
private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) { private PendingIntent createReplyIntent(final Conversation conversation, final String lastMessageUuid, final boolean dismissAfterReply) {
final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class); final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION); intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
intent.putExtra("uuid", conversation.getUuid()); intent.putExtra("uuid", conversation.getUuid());
intent.putExtra("dismiss_notification", dismissAfterReply); intent.putExtra("dismiss_notification", dismissAfterReply);
intent.putExtra("last_message_uuid", lastMessageUuid);
final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14); final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
return PendingIntent.getService(mXmppConnectionService, id, intent, 0); return PendingIntent.getService(mXmppConnectionService, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
} }
private PendingIntent createReadPendingIntent(Conversation conversation) { private PendingIntent createReadPendingIntent(Conversation conversation) {
@ -1253,4 +1325,13 @@ public class NotificationService {
Log.d(Config.LOGTAG, "unable to cancel notification", e); Log.d(Config.LOGTAG, "unable to cancel notification", e);
} }
} }
private class VibrationRunnable implements Runnable {
@Override
public void run() {
final Vibrator vibrator = (Vibrator) mXmppConnectionService.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(CALL_PATTERN, -1);
}
}
} }

View File

@ -4,6 +4,7 @@ import android.Manifest;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
@ -19,6 +20,8 @@ import android.database.ContentObserver;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.media.AudioManager; import android.media.AudioManager;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Binder; import android.os.Binder;
@ -54,7 +57,6 @@ import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection; import org.openintents.openpgp.util.OpenPgpServiceConnection;
import java.io.File; import java.io.File;
import java.net.URL;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.security.Security; import java.security.Security;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
@ -73,6 +75,8 @@ import java.util.Set;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -103,7 +107,6 @@ import eu.siacs.conversations.generator.AbstractGenerator;
import eu.siacs.conversations.generator.IqGenerator; import eu.siacs.conversations.generator.IqGenerator;
import eu.siacs.conversations.generator.MessageGenerator; import eu.siacs.conversations.generator.MessageGenerator;
import eu.siacs.conversations.generator.PresenceGenerator; import eu.siacs.conversations.generator.PresenceGenerator;
import eu.siacs.conversations.http.CustomURLStreamHandlerFactory;
import eu.siacs.conversations.http.HttpConnectionManager; import eu.siacs.conversations.http.HttpConnectionManager;
import eu.siacs.conversations.parser.AbstractParser; import eu.siacs.conversations.parser.AbstractParser;
import eu.siacs.conversations.parser.IqParser; import eu.siacs.conversations.parser.IqParser;
@ -135,6 +138,7 @@ import eu.siacs.conversations.utils.TorServiceUtils;
import eu.siacs.conversations.utils.WakeLockHelper; import eu.siacs.conversations.utils.WakeLockHelper;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.LocalizedContent;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.OnBindListener; import eu.siacs.conversations.xmpp.OnBindListener;
@ -152,6 +156,7 @@ import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection; import eu.siacs.conversations.xmpp.jingle.AbstractJingleConnection;
import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager; import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
import eu.siacs.conversations.xmpp.jingle.Media; import eu.siacs.conversations.xmpp.jingle.Media;
import eu.siacs.conversations.xmpp.jingle.RtpEndUserState; import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
import eu.siacs.conversations.xmpp.mam.MamReference; import eu.siacs.conversations.xmpp.mam.MamReference;
@ -180,13 +185,10 @@ public class XmppConnectionService extends Service {
private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp"; private static final String SETTING_LAST_ACTIVITY_TS = "last_activity_timestamp";
static {
URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
}
public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1); public final CountDownLatch restoredFromDatabaseLatch = new CountDownLatch(1);
private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor("FileAdding"); private final static Executor FILE_OBSERVER_EXECUTOR = Executors.newSingleThreadExecutor();
private final SerialSingleThreadExecutor mVideoCompressionExecutor = new SerialSingleThreadExecutor("VideoCompression"); private final static Executor FILE_ATTACHMENT_EXECUTOR = Executors.newSingleThreadExecutor();
private final static SerialSingleThreadExecutor VIDEO_COMPRESSION_EXECUTOR = new SerialSingleThreadExecutor("VideoCompression");
private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter"); private final SerialSingleThreadExecutor mDatabaseWriterExecutor = new SerialSingleThreadExecutor("DatabaseWriter");
private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader"); private final SerialSingleThreadExecutor mDatabaseReaderExecutor = new SerialSingleThreadExecutor("DatabaseReader");
private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor"); private final SerialSingleThreadExecutor mNotificationExecutor = new SerialSingleThreadExecutor("NotificationExecutor");
@ -251,10 +253,23 @@ public class XmppConnectionService extends Service {
private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() { private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
@Override @Override
public boolean onMessageAcknowledged(Account account, String uuid) { public boolean onMessageAcknowledged(final Account account, final Jid to, final String id) {
if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
mJingleConnectionManager.updateProposedSessionDiscovered(
account,
to,
sessionId,
JingleConnectionManager.DeviceDiscoveryState.SEARCHING_ACKNOWLEDGED
);
}
final Jid bare = to.asBareJid();
for (final Conversation conversation : getConversations()) { for (final Conversation conversation : getConversations()) {
if (conversation.getAccount() == account) { if (conversation.getAccount() == account && conversation.getJid().asBareJid().equals(bare)) {
Message message = conversation.findUnsentMessageWithUuid(uuid); final Message message = conversation.findUnsentMessageWithUuid(id);
if (message != null) { if (message != null) {
message.setStatus(Message.STATUS_SEND); message.setStatus(Message.STATUS_SEND);
message.setErrorMessage(null); message.setErrorMessage(null);
@ -330,7 +345,7 @@ public class XmppConnectionService extends Service {
synchronized (account.inProgressConferencePings) { synchronized (account.inProgressConferencePings) {
account.inProgressConferencePings.clear(); account.inProgressConferencePings.clear();
} }
mJingleConnectionManager.notifyRebound(); mJingleConnectionManager.notifyRebound(account);
mQuickConversationsService.considerSyncBackground(false); mQuickConversationsService.considerSyncBackground(false);
fetchRosterFromServer(account); fetchRosterFromServer(account);
@ -356,6 +371,7 @@ public class XmppConnectionService extends Service {
} }
connectMultiModeConversations(account); connectMultiModeConversations(account);
syncDirtyContacts(account); syncDirtyContacts(account);
} }
}; };
private final AtomicLong mLastExpiryRun = new AtomicLong(0); private final AtomicLong mLastExpiryRun = new AtomicLong(0);
@ -458,7 +474,6 @@ public class XmppConnectionService extends Service {
private OpenPgpServiceConnection pgpServiceConnection; private OpenPgpServiceConnection pgpServiceConnection;
private PgpEngine mPgpEngine = null; private PgpEngine mPgpEngine = null;
private WakeLock wakeLock; private WakeLock wakeLock;
private PowerManager pm;
private LruCache<String, Bitmap> mBitmapCache; private LruCache<String, Bitmap> mBitmapCache;
private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver(); private final BroadcastReceiver mInternalEventReceiver = new InternalEventReceiver();
private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver(); private final BroadcastReceiver mInternalScreenEventReceiver = new InternalEventReceiver();
@ -551,14 +566,14 @@ public class XmppConnectionService extends Service {
Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart()); Log.d(Config.LOGTAG, "counterpart=" + message.getCounterpart());
final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback); final AttachFileToConversationRunnable runnable = new AttachFileToConversationRunnable(this, uri, type, message, callback);
if (runnable.isVideoMessage()) { if (runnable.isVideoMessage()) {
mVideoCompressionExecutor.execute(runnable); VIDEO_COMPRESSION_EXECUTOR.execute(runnable);
} else { } else {
mFileAddingExecutor.execute(runnable); FILE_ATTACHMENT_EXECUTOR.execute(runnable);
} }
} }
public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) { public void attachImageToConversation(final Conversation conversation, final Uri uri, final String type, final UiCallback<Message> callback) {
final String mimeType = MimeUtils.guessMimeTypeFromUri(this, uri); final String mimeType = MimeUtils.guessMimeTypeFromUriAndMime(this, uri, type);
final String compressPictures = getCompressPicturesPreference(); final String compressPictures = getCompressPicturesPreference();
if ("never".equals(compressPictures) if ("never".equals(compressPictures)
@ -580,10 +595,11 @@ public class XmppConnectionService extends Service {
message.setType(Message.TYPE_IMAGE); message.setType(Message.TYPE_IMAGE);
} }
Log.d(Config.LOGTAG, "attachImage: type=" + message.getType()); Log.d(Config.LOGTAG, "attachImage: type=" + message.getType());
mFileAddingExecutor.execute(() -> { FILE_ATTACHMENT_EXECUTOR.execute(() -> {
try { try {
getFileBackend().copyImageToPrivateStorage(message, uri); getFileBackend().copyImageToPrivateStorage(message, uri);
} catch (FileBackend.NotAnImageFileException e) { } catch (FileBackend.ImageCompressionException e) {
Log.d(Config.LOGTAG, "unable to compress image. fall back to file transfer", e);
attachFileToConversation(conversation, uri, mimeType, callback); attachFileToConversation(conversation, uri, mimeType, callback);
return; return;
} catch (final FileBackend.FileCopyException e) { } catch (final FileBackend.FileCopyException e) {
@ -645,6 +661,7 @@ public class XmppConnectionService extends Service {
if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) { if (Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
resetAllAttemptCounts(true, false); resetAllAttemptCounts(true, false);
} }
Resolver.clearCache();
} }
break; break;
case Intent.ACTION_SHUTDOWN: case Intent.ACTION_SHUTDOWN:
@ -674,6 +691,7 @@ public class XmppConnectionService extends Service {
} }
case TorServiceUtils.ACTION_STATUS: case TorServiceUtils.ACTION_STATUS:
final String status = intent.getStringExtra(TorServiceUtils.EXTRA_STATUS); final String status = intent.getStringExtra(TorServiceUtils.EXTRA_STATUS);
//TODO port and host are in 'extras' - but this may not be a reliable source?
if ("ON".equals(status)) { if ("ON".equals(status)) {
handleOrbotStartedEvent(); handleOrbotStartedEvent();
return START_STICKY; return START_STICKY;
@ -708,6 +726,7 @@ public class XmppConnectionService extends Service {
} }
final CharSequence body = remoteInput.getCharSequence("text_reply"); final CharSequence body = remoteInput.getCharSequence("text_reply");
final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false); final boolean dismissNotification = intent.getBooleanExtra("dismiss_notification", false);
final String lastMessageUuid = intent.getStringExtra("last_message_uuid");
if (body == null || body.length() <= 0) { if (body == null || body.length() <= 0) {
break; break;
} }
@ -716,7 +735,7 @@ public class XmppConnectionService extends Service {
restoredFromDatabaseLatch.await(); restoredFromDatabaseLatch.await();
final Conversation c = findConversationByUuid(uuid); final Conversation c = findConversationByUuid(uuid);
if (c != null) { if (c != null) {
directReply(c, body.toString(), dismissNotification); directReply(c, body.toString(), lastMessageUuid, dismissNotification);
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
Log.d(Config.LOGTAG, "unable to process direct reply"); Log.d(Config.LOGTAG, "unable to process direct reply");
@ -758,8 +777,9 @@ public class XmppConnectionService extends Service {
break; break;
case Intent.ACTION_SCREEN_ON: case Intent.ACTION_SCREEN_ON:
deactivateGracePeriod(); deactivateGracePeriod();
case Intent.ACTION_USER_PRESENT:
case Intent.ACTION_SCREEN_OFF: case Intent.ACTION_SCREEN_OFF:
if (awayWhenScreenOff()) { if (awayWhenScreenLocked()) {
refreshAllPresences(); refreshAllPresences();
} }
break; break;
@ -913,8 +933,12 @@ public class XmppConnectionService extends Service {
} }
} }
private void directReply(Conversation conversation, String body, final boolean dismissAfterReply) { private void directReply(final Conversation conversation, final String body, final String lastMessageUuid, final boolean dismissAfterReply) {
Message message = new Message(conversation, body, conversation.getNextEncryption()); final Message inReplyTo = lastMessageUuid == null ? null : conversation.findMessageWithUuid(lastMessageUuid);
final Message message = new Message(conversation, body, conversation.getNextEncryption());
if (inReplyTo != null && inReplyTo.isPrivateMessage()) {
Message.configurePrivateMessage(message, inReplyTo.getCounterpart());
}
message.markUnread(); message.markUnread();
if (message.getEncryption() == Message.ENCRYPTION_PGP) { if (message.getEncryption() == Message.ENCRYPTION_PGP) {
getPgpEngine().encrypt(message, new UiCallback<Message>() { getPgpEngine().encrypt(message, new UiCallback<Message>() {
@ -959,7 +983,7 @@ public class XmppConnectionService extends Service {
return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent); return getBooleanPreference(SettingsActivity.TREAT_VIBRATE_AS_SILENT, R.bool.treat_vibrate_as_silent);
} }
private boolean awayWhenScreenOff() { private boolean awayWhenScreenLocked() {
return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off); return getBooleanPreference(SettingsActivity.AWAY_WHEN_SCREEN_IS_OFF, R.bool.away_when_screen_off);
} }
@ -970,29 +994,19 @@ public class XmppConnectionService extends Service {
private Presence.Status getTargetPresence() { private Presence.Status getTargetPresence() {
if (dndOnSilentMode() && isPhoneSilenced()) { if (dndOnSilentMode() && isPhoneSilenced()) {
return Presence.Status.DND; return Presence.Status.DND;
} else if (awayWhenScreenOff() && !isInteractive()) { } else if (awayWhenScreenLocked() && isScreenLocked()) {
return Presence.Status.AWAY; return Presence.Status.AWAY;
} else { } else {
return Presence.Status.ONLINE; return Presence.Status.ONLINE;
} }
} }
@SuppressLint("NewApi") public boolean isScreenLocked() {
@SuppressWarnings("deprecation") final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
public boolean isInteractive() { final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
try { final boolean locked = keyguardManager != null && keyguardManager.isKeyguardLocked();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final boolean interactive = powerManager != null && powerManager.isInteractive();
return locked || !interactive;
final boolean isScreenOn;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
isScreenOn = pm.isScreenOn();
} else {
isScreenOn = pm.isInteractive();
}
return isScreenOn;
} catch (RuntimeException e) {
return false;
}
} }
private boolean isPhoneSilenced() { private boolean isPhoneSilenced() {
@ -1070,11 +1084,20 @@ public class XmppConnectionService extends Service {
} }
public boolean hasInternetConnection() { public boolean hasInternetConnection() {
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
if (cm == null) {
return true; //if internet connection can not be checked it is probably best to just try
}
try { try {
final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET); final Network activeNetwork = cm.getActiveNetwork();
} catch (RuntimeException e) { final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
} else {
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
}
} catch (final RuntimeException e) {
Log.d(Config.LOGTAG, "unable to check for internet connection", e); Log.d(Config.LOGTAG, "unable to check for internet connection", e);
return true; //if internet connection can not be checked it is probably best to just try return true; //if internet connection can not be checked it is probably best to just try
} }
@ -1131,11 +1154,11 @@ public class XmppConnectionService extends Service {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
startContactObserver(); startContactObserver();
} }
mFileAddingExecutor.execute(fileBackend::deleteHistoricAvatarPath); FILE_OBSERVER_EXECUTOR.execute(fileBackend::deleteHistoricAvatarPath);
if (Compatibility.hasStoragePermission(this)) { if (Compatibility.hasStoragePermission(this)) {
Log.d(Config.LOGTAG, "starting file observer"); Log.d(Config.LOGTAG, "starting file observer");
mFileAddingExecutor.execute(this.fileObserver::startWatching); FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::startWatching);
mFileAddingExecutor.execute(this::checkForDeletedFiles); FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
} }
if (Config.supportOpenPgp()) { if (Config.supportOpenPgp()) {
this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() { this.pgpServiceConnection = new OpenPgpServiceConnection(this, "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
@ -1156,7 +1179,7 @@ public class XmppConnectionService extends Service {
this.pgpServiceConnection.bindToService(); this.pgpServiceConnection.bindToService();
} }
this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager pm = ContextCompat.getSystemService(this, PowerManager.class);
this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service"); this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Conversations:Service");
toggleForegroundService(); toggleForegroundService();
@ -1240,6 +1263,7 @@ public class XmppConnectionService extends Service {
public void onDestroy() { public void onDestroy() {
try { try {
unregisterReceiver(this.mInternalEventReceiver); unregisterReceiver(this.mInternalEventReceiver);
unregisterReceiver(this.mInternalScreenEventReceiver);
} catch (final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
//ignored //ignored
} }
@ -1250,15 +1274,16 @@ public class XmppConnectionService extends Service {
public void restartFileObserver() { public void restartFileObserver() {
Log.d(Config.LOGTAG, "restarting file observer"); Log.d(Config.LOGTAG, "restarting file observer");
mFileAddingExecutor.execute(this.fileObserver::restartWatching); FILE_OBSERVER_EXECUTOR.execute(this.fileObserver::restartWatching);
mFileAddingExecutor.execute(this::checkForDeletedFiles); FILE_OBSERVER_EXECUTOR.execute(this::checkForDeletedFiles);
} }
public void toggleScreenEventReceiver() { public void toggleScreenEventReceiver() {
if (awayWhenScreenOff() && !manuallyChangePresence()) { if (awayWhenScreenLocked() && !manuallyChangePresence()) {
final IntentFilter filter = new IntentFilter(); final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(this.mInternalScreenEventReceiver, filter); registerReceiver(this.mInternalScreenEventReceiver, filter);
} else { } else {
try { try {
@ -1273,8 +1298,8 @@ public class XmppConnectionService extends Service {
toggleForegroundService(false); toggleForegroundService(false);
} }
public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media) { public void setOngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
ongoingCall.set(new OngoingCall(id, media)); ongoingCall.set(new OngoingCall(id, media, reconnecting));
toggleForegroundService(false); toggleForegroundService(false);
} }
@ -1290,7 +1315,7 @@ public class XmppConnectionService extends Service {
final Notification notification; final Notification notification;
final int id; final int id;
if (ongoing != null) { if (ongoing != null) {
notification = this.mNotificationService.getOngoingCallNotification(ongoing.id, ongoing.media); notification = this.mNotificationService.getOngoingCallNotification(ongoing);
id = NotificationService.ONGOING_CALL_NOTIFICATION_ID; id = NotificationService.ONGOING_CALL_NOTIFICATION_ID;
startForeground(id, notification); startForeground(id, notification);
mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID); mNotificationService.cancel(NotificationService.FOREGROUND_NOTIFICATION_ID);
@ -1785,7 +1810,7 @@ public class XmppConnectionService extends Service {
IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString()); IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
sendIqPacket(account, request, (a, response) -> { sendIqPacket(account, request, (a, response) -> {
if (response.getType() == IqPacket.TYPE.ERROR) { if (response.getType() == IqPacket.TYPE.ERROR) {
Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getError()); Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
} }
}); });
} else if (connection.getFeatures().bookmarksConversion()) { } else if (connection.getFeatures().bookmarksConversion()) {
@ -1867,7 +1892,10 @@ public class XmppConnectionService extends Service {
long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore; long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms"); Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
Runnable runnable = () -> { Runnable runnable = () -> {
long deletionDate = getAutomaticMessageDeletionDate(); if (DatabaseBackend.requiresMessageIndexRebuild()) {
DatabaseBackend.getInstance(this).rebuildMessagesIndex();
}
final long deletionDate = getAutomaticMessageDeletionDate();
mLastExpiryRun.set(SystemClock.elapsedRealtime()); mLastExpiryRun.set(SystemClock.elapsedRealtime());
if (deletionDate > 0) { if (deletionDate > 0) {
Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate)); Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
@ -1907,7 +1935,7 @@ public class XmppConnectionService extends Service {
private void restoreMessages(Conversation conversation) { private void restoreMessages(Conversation conversation) {
conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE)); conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING)); conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message)); conversation.findUnreadMessages(mNotificationService::pushFromBacklog);
} }
public void loadPhoneContacts() { public void loadPhoneContacts() {
@ -2855,13 +2883,12 @@ public class XmppConnectionService extends Service {
} }
@Override @Override
public void onFetchFailed(final Conversation conversation, Element error) { public void onFetchFailed(final Conversation conversation, final String errorCondition) {
if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) { if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
return; return;
} }
if (error != null && "remote-server-not-found".equals(error.getName())) { if ("remote-server-not-found".equals(errorCondition)) {
synchronized (account.inProgressConferenceJoins) { synchronized (account.inProgressConferenceJoins) {
account.inProgressConferenceJoins.remove(conversation); account.inProgressConferenceJoins.remove(conversation);
} }
@ -3227,7 +3254,7 @@ public class XmppConnectionService extends Service {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch"); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
} else { } else {
if (callback != null) { if (callback != null) {
callback.onFetchFailed(conversation, packet.getError()); callback.onFetchFailed(conversation, packet.getErrorCondition());
} }
} }
} }
@ -3320,35 +3347,26 @@ public class XmppConnectionService extends Service {
public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) { public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
final Jid jid = user.asBareJid(); final Jid jid = user.asBareJid();
IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString()); final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() { sendIqPacket(conference.getAccount(), request, (account, response) -> {
@Override if (response.getType() == IqPacket.TYPE.RESULT) {
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) {
conference.getMucOptions().changeAffiliation(jid, affiliation); conference.getMucOptions().changeAffiliation(jid, affiliation);
getAvatarService().clear(conference); getAvatarService().clear(conference);
if (callback != null) {
callback.onAffiliationChangedSuccessful(jid); callback.onAffiliationChangedSuccessful(jid);
} else { } else {
callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation); Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
} }
} else if (callback != null) {
callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
} else {
Log.d(Config.LOGTAG, "unable to change affiliation");
} }
}); });
} }
public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
List<Jid> jids = new ArrayList<>();
for (MucOptions.User user : conference.getMucOptions().getUsers()) {
if (user.getAffiliation() == before && user.getRealJid() != null) {
jids.add(user.getRealJid());
}
}
IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
}
public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) { public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString()); IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
Log.d(Config.LOGTAG, request.toString());
sendIqPacket(conference.getAccount(), request, (account, packet) -> { sendIqPacket(conference.getAccount(), request, (account, packet) -> {
if (packet.getType() != IqPacket.TYPE.RESULT) { if (packet.getType() != IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick); Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
@ -3431,15 +3449,23 @@ public class XmppConnectionService extends Service {
} }
} }
public void createContact(Contact contact, boolean autoGrant) { public void createContact(final Contact contact, final boolean autoGrant) {
createContact(contact, autoGrant, null);
}
public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
if (autoGrant) { if (autoGrant) {
contact.setOption(Contact.Options.PREEMPTIVE_GRANT); contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
contact.setOption(Contact.Options.ASKING); contact.setOption(Contact.Options.ASKING);
} }
pushContactToServer(contact); pushContactToServer(contact, preAuth);
} }
public void pushContactToServer(final Contact contact) { public void pushContactToServer(final Contact contact) {
pushContactToServer(contact, null);
}
private void pushContactToServer(final Contact contact, final String preAuth) {
contact.resetOption(Contact.Options.DIRTY_DELETE); contact.resetOption(Contact.Options.DIRTY_DELETE);
contact.setOption(Contact.Options.DIRTY_PUSH); contact.setOption(Contact.Options.DIRTY_PUSH);
final Account account = contact.getAccount(); final Account account = contact.getAccount();
@ -3455,7 +3481,7 @@ public class XmppConnectionService extends Service {
sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact)); sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
} }
if (ask) { if (ask) {
sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact)); sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
} }
} else { } else {
syncRoster(contact.getAccount()); syncRoster(contact.getAccount());
@ -3522,7 +3548,7 @@ public class XmppConnectionService extends Service {
if (publicationResponse.getType() == IqPacket.TYPE.RESULT) { if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
callback.onAvatarPublicationSucceeded(); callback.onAvatarPublicationSucceeded();
} else { } else {
Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError()); Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject); callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
} }
}); });
@ -3903,9 +3929,13 @@ public class XmppConnectionService extends Service {
new Thread(() -> reconnectAccount(account, false, true)).start(); new Thread(() -> reconnectAccount(account, false, true)).start();
} }
public void invite(Conversation conversation, Jid contact) { public void invite(final Conversation conversation, final Jid contact) {
Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid()); Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
MessagePacket packet = mMessageGenerator.invite(conversation, contact); final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
}
final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
sendMessagePacket(conversation.getAccount(), packet); sendMessagePacket(conversation.getAccount(), packet);
} }
@ -3942,16 +3972,30 @@ public class XmppConnectionService extends Service {
return null; return null;
} }
public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) { public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
return markMessage(conversation, uuid, status, serverMessageId, null);
}
public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
if (uuid == null) { if (uuid == null) {
return false; return false;
} else { } else {
Message message = conversation.findSentMessageWithUuid(uuid); final Message message = conversation.findSentMessageWithUuid(uuid);
if (message != null) { if (message != null) {
if (message.getServerMsgId() == null) { if (message.getServerMsgId() == null) {
message.setServerMsgId(serverMessageId); message.setServerMsgId(serverMessageId);
} }
if (message.getEncryption() == Message.ENCRYPTION_NONE
&& message.isTypeText()
&& isBodyModified(message, body)) {
message.setBody(body.content);
if (body.count > 1) {
message.setBodyLanguage(body.language);
}
markMessage(message, status, null, true);
} else {
markMessage(message, status); markMessage(message, status);
}
return true; return true;
} else { } else {
return false; return false;
@ -3959,12 +4003,23 @@ public class XmppConnectionService extends Service {
} }
} }
private static boolean isBodyModified(final Message message, final LocalizedContent body) {
if (body == null || body.content == null) {
return false;
}
return !body.content.equals(message.getBody());
}
public void markMessage(Message message, int status) { public void markMessage(Message message, int status) {
markMessage(message, status, null); markMessage(message, status, null);
} }
public void markMessage(final Message message, final int status, final String errorMessage) { public void markMessage(final Message message, final int status, final String errorMessage) {
markMessage(message, status, errorMessage, false);
}
public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
final int oldStatus = message.getStatus(); final int oldStatus = message.getStatus();
if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) { if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
return; return;
@ -3974,7 +4029,7 @@ public class XmppConnectionService extends Service {
} }
message.setErrorMessage(errorMessage); message.setErrorMessage(errorMessage);
message.setStatus(status); message.setStatus(status);
databaseBackend.updateMessage(message, false); databaseBackend.updateMessage(message, includeBody);
updateConversationUi(); updateConversationUi();
if (oldStatus != status && status == Message.STATUS_SEND_FAILED) { if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
mNotificationService.pushFailedDelivery(message); mNotificationService.pushFailedDelivery(message);
@ -4279,7 +4334,7 @@ public class XmppConnectionService extends Service {
} }
public void sendMessagePacket(Account account, MessagePacket packet) { public void sendMessagePacket(Account account, MessagePacket packet) {
XmppConnection connection = account.getXmppConnection(); final XmppConnection connection = account.getXmppConnection();
if (connection != null) { if (connection != null) {
connection.sendMessagePacket(packet); connection.sendMessagePacket(packet);
} }
@ -4314,7 +4369,7 @@ public class XmppConnectionService extends Service {
} }
private void sendPresence(final Account account, final boolean includeIdleTimestamp) { private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
Presence.Status status; final Presence.Status status;
if (manuallyChangePresence()) { if (manuallyChangePresence()) {
status = account.getPresenceStatus(); status = account.getPresenceStatus();
} else { } else {
@ -4557,11 +4612,6 @@ public class XmppConnectionService extends Service {
syncRoster(account); syncRoster(account);
} }
} else { } else {
if (account.inProgressDiscoFetches.contains(key)) {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping duplicate disco request for " + key.second + " to " + jid);
return;
}
account.inProgressDiscoFetches.add(key);
final IqPacket request = new IqPacket(IqPacket.TYPE.GET); final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
request.setTo(jid); request.setTo(jid);
final String node = presence.getNode(); final String node = presence.getNode();
@ -4573,7 +4623,7 @@ public class XmppConnectionService extends Service {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
sendIqPacket(account, request, (a, response) -> { sendIqPacket(account, request, (a, response) -> {
if (response.getType() == IqPacket.TYPE.RESULT) { if (response.getType() == IqPacket.TYPE.RESULT) {
ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response); final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
if (presence.getVer().equals(discoveryResult.getVer())) { if (presence.getVer().equals(discoveryResult.getVer())) {
databaseBackend.insertDiscoveryResult(discoveryResult); databaseBackend.insertDiscoveryResult(discoveryResult);
injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult); injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
@ -4583,7 +4633,6 @@ public class XmppConnectionService extends Service {
} else { } else {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid); Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
} }
a.inProgressDiscoFetches.remove(key);
}); });
} }
} }
@ -4788,7 +4837,7 @@ public class XmppConnectionService extends Service {
public interface OnConferenceConfigurationFetched { public interface OnConferenceConfigurationFetched {
void onConferenceConfigurationFetched(Conversation conversation); void onConferenceConfigurationFetched(Conversation conversation);
void onFetchFailed(Conversation conversation, Element error); void onFetchFailed(Conversation conversation, String errorCondition);
} }
public interface OnConferenceJoined { public interface OnConferenceJoined {
@ -4820,12 +4869,14 @@ public class XmppConnectionService extends Service {
} }
public static class OngoingCall { public static class OngoingCall {
private final AbstractJingleConnection.Id id; public final AbstractJingleConnection.Id id;
private final Set<Media> media; public final Set<Media> media;
public final boolean reconnecting;
public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media) { public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
this.id = id; this.id = id;
this.media = media; this.media = media;
this.reconnecting = reconnecting;
} }
@Override @Override
@ -4833,12 +4884,12 @@ public class XmppConnectionService extends Service {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
OngoingCall that = (OngoingCall) o; OngoingCall that = (OngoingCall) o;
return Objects.equal(id, that.id); return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hashCode(id); return Objects.hashCode(id, media, reconnecting);
} }
} }
} }

View File

@ -5,12 +5,19 @@ import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
import static eu.siacs.conversations.ui.XmppActivity.configureActionBar; import static eu.siacs.conversations.ui.XmppActivity.configureActionBar;
public class AboutActivity extends AppCompatActivity { public class AboutActivity extends AppCompatActivity {
@Override
protected void onResume(){
super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
}
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);

View File

@ -5,22 +5,24 @@ import android.content.Intent;
import android.preference.Preference; import android.preference.Preference;
import android.util.AttributeSet; import android.util.AttributeSet;
import eu.siacs.conversations.BuildConfig;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.utils.PhoneHelper; import eu.siacs.conversations.utils.PhoneHelper;
public class AboutPreference extends Preference { public class AboutPreference extends Preference {
public AboutPreference(final Context context, final AttributeSet attrs, final int defStyle) { public AboutPreference(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
final String appName = context.getString(R.string.app_name); setSummaryAndTitle(context);
setSummary(appName +' '+ PhoneHelper.getVersionName(context));
setTitle(context.getString(R.string.title_activity_about_x, appName));
} }
public AboutPreference(final Context context, final AttributeSet attrs) { public AboutPreference(final Context context, final AttributeSet attrs) {
super(context, attrs); super(context, attrs);
final String appName = context.getString(R.string.app_name); setSummaryAndTitle(context);
setSummary(appName +' '+ PhoneHelper.getVersionName(context)); }
setTitle(context.getString(R.string.title_activity_about_x, appName));
private void setSummaryAndTitle(final Context context) {
setSummary(String.format("%s %s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME));
setTitle(context.getString(R.string.title_activity_about_x, BuildConfig.APP_NAME));
} }
@Override @Override

View File

@ -1,5 +1,6 @@
package eu.siacs.conversations.ui; package eu.siacs.conversations.ui;
import android.app.Activity;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -7,6 +8,7 @@ import android.os.Bundle;
import android.text.Editable; import android.text.Editable;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
@ -86,6 +88,13 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
} }
}; };
public static void open(final Activity activity, final Conversation conversation) {
Intent intent = new Intent(activity, ConferenceDetailsActivity.class);
intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
intent.putExtra("uuid", conversation.getUuid());
activity.startActivity(intent);
}
private final OnClickListener mNotifyStatusClickListener = new OnClickListener() { private final OnClickListener mNotifyStatusClickListener = new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@ -481,6 +490,7 @@ public class ConferenceDetailsActivity extends XmppActivity implements OnConvers
this.binding.mucSubject.setTextAppearance(this, subject.length() > (hasTitle ? 128 : 196) ? R.style.TextAppearance_Conversations_Body1_Linkified : R.style.TextAppearance_Conversations_Subhead); this.binding.mucSubject.setTextAppearance(this, subject.length() > (hasTitle ? 128 : 196) ? R.style.TextAppearance_Conversations_Body1_Linkified : R.style.TextAppearance_Conversations_Subhead);
this.binding.mucSubject.setAutoLinkMask(0); this.binding.mucSubject.setAutoLinkMask(0);
this.binding.mucSubject.setVisibility(View.VISIBLE); this.binding.mucSubject.setVisibility(View.VISIBLE);
this.binding.mucSubject.setMovementMethod(LinkMovementMethod.getInstance());
} else { } else {
this.binding.mucSubject.setVisibility(View.GONE); this.binding.mucSubject.setVisibility(View.GONE);
} }

View File

@ -45,6 +45,7 @@ import eu.siacs.conversations.databinding.ActivityContactDetailsBinding;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.ListItem; import eu.siacs.conversations.entities.ListItem;
import eu.siacs.conversations.services.AbstractQuickConversationsService;
import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate; import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate; import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
import eu.siacs.conversations.ui.adapter.MediaAdapter; import eu.siacs.conversations.ui.adapter.MediaAdapter;
@ -58,6 +59,7 @@ import eu.siacs.conversations.utils.AccountUtils;
import eu.siacs.conversations.utils.Compatibility; import eu.siacs.conversations.utils.Compatibility;
import eu.siacs.conversations.utils.Emoticons; import eu.siacs.conversations.utils.Emoticons;
import eu.siacs.conversations.utils.IrregularUnicodeDetector; import eu.siacs.conversations.utils.IrregularUnicodeDetector;
import eu.siacs.conversations.utils.PhoneNumberUtilWrapper;
import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.utils.UIHelper;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
@ -131,15 +133,31 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
} }
private void showAddToPhoneBookDialog() { private void showAddToPhoneBookDialog() {
final Jid jid = contact.getJid();
final boolean quicksyContact = AbstractQuickConversationsService.isQuicksy()
&& Config.QUICKSY_DOMAIN.equals(jid.getDomain())
&& jid.getLocal() != null;
final String value;
if (quicksyContact) {
value = PhoneNumberUtilWrapper.toFormattedPhoneNumber(this, jid);
} else {
value = jid.toEscapedString();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.action_add_phone_book)); builder.setTitle(getString(R.string.action_add_phone_book));
builder.setMessage(getString(R.string.add_phone_book_text, contact.getJid().toEscapedString())); builder.setMessage(getString(R.string.add_phone_book_text, value));
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
builder.setPositiveButton(getString(R.string.add), (dialog, which) -> { builder.setPositiveButton(getString(R.string.add), (dialog, which) -> {
final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT); final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(Contacts.CONTENT_ITEM_TYPE); intent.setType(Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(Intents.Insert.IM_HANDLE, contact.getJid().toEscapedString()); if (quicksyContact) {
intent.putExtra(Intents.Insert.PHONE, value);
} else {
intent.putExtra(Intents.Insert.IM_HANDLE, value);
intent.putExtra(Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER); intent.putExtra(Intents.Insert.IM_PROTOCOL, CommonDataKinds.Im.PROTOCOL_JABBER);
//TODO for modern use we want PROTOCOL_CUSTOM and an extra field with a value of 'XMPP'
// however we dont have such a field and thus have to use the legacy PROTOCOL_JABBER
}
intent.putExtra("finishActivityOnSaveCompleted", true); intent.putExtra("finishActivityOnSaveCompleted", true);
try { try {
startActivityForResult(intent, 0); startActivityForResult(intent, 0);
@ -233,6 +251,7 @@ public class ContactDetailsActivity extends OmemoActivity implements OnAccountUp
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) if (grantResults.length > 0)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) { if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) {

View File

@ -6,6 +6,8 @@ import android.os.Bundle;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import eu.siacs.conversations.ui.util.SettingsUtils;
public class ConversationActivity extends AppCompatActivity { public class ConversationActivity extends AppCompatActivity {
@Override @Override
@ -14,4 +16,10 @@ public class ConversationActivity extends AppCompatActivity {
startActivity(new Intent(this, ConversationsActivity.class)); startActivity(new Intent(this, ConversationsActivity.class));
finish(); finish();
} }
@Override
protected void onResume(){
super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
}
} }

View File

@ -135,6 +135,8 @@ import static eu.siacs.conversations.utils.PermissionUtils.allGranted;
import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied; import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
import static eu.siacs.conversations.utils.PermissionUtils.writeGranted; import static eu.siacs.conversations.utils.PermissionUtils.writeGranted;
import org.jetbrains.annotations.NotNull;
public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener, MessageAdapter.OnContactPictureLongClicked, MessageAdapter.OnContactPictureClicked { public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener, MessageAdapter.OnContactPictureLongClicked, MessageAdapter.OnContactPictureClicked {
@ -186,10 +188,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class); ConferenceDetailsActivity.open(getActivity(), conversation);
intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
intent.putExtra("uuid", conversation.getUuid());
startActivity(intent);
} }
}; };
private final OnClickListener leaveMuc = new OnClickListener() { private final OnClickListener leaveMuc = new OnClickListener() {
@ -689,14 +688,14 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
toggleInputMethod(); toggleInputMethod();
} }
private void attachImageToConversation(Conversation conversation, Uri uri) { private void attachImageToConversation(Conversation conversation, Uri uri, String type) {
if (conversation == null) { if (conversation == null) {
return; return;
} }
final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG); final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG);
prepareFileToast.show(); prepareFileToast.show();
activity.delegateUriPermissionsToService(uri); activity.delegateUriPermissionsToService(uri);
activity.xmppConnectionService.attachImageToConversation(conversation, uri, activity.xmppConnectionService.attachImageToConversation(conversation, uri, type,
new UiCallback<Message>() { new UiCallback<Message>() {
@Override @Override
@ -734,7 +733,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (body.length() == 0 || conversation == null) { if (body.length() == 0 || conversation == null) {
return; return;
} }
if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) { if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_TEXT)) {
return; return;
} }
final Message message; final Message message;
@ -757,6 +756,10 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
} }
private boolean trustKeysIfNeeded(final Conversation conversation, final int requestCode) {
return conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(requestCode);
}
protected boolean trustKeysIfNeeded(int requestCode) { protected boolean trustKeysIfNeeded(int requestCode) {
AxolotlService axolotlService = conversation.getAccount().getAxolotlService(); AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
final List<Jid> targets = axolotlService.getCryptoTargets(conversation); final List<Jid> targets = axolotlService.getCryptoTargets(conversation);
@ -824,6 +827,12 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
case REQUEST_TRUST_KEYS_ATTACHMENTS: case REQUEST_TRUST_KEYS_ATTACHMENTS:
commitAttachments(); commitAttachments();
break; break;
case REQUEST_START_AUDIO_CALL:
triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VOICE_CALL);
break;
case REQUEST_START_VIDEO_CALL:
triggerRtpSession(RtpSessionActivity.ACTION_MAKE_VIDEO_CALL);
break;
case ATTACHMENT_CHOICE_CHOOSE_IMAGE: case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
final List<Attachment> imageUris = Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE); final List<Attachment> imageUris = Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE);
mediaPreviewAdapter.addMediaPreviews(imageUris); mediaPreviewAdapter.addMediaPreviews(imageUris);
@ -847,9 +856,15 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
toggleInputMethod(); toggleInputMethod();
break; break;
case ATTACHMENT_CHOICE_LOCATION: case ATTACHMENT_CHOICE_LOCATION:
double latitude = data.getDoubleExtra("latitude", 0); final double latitude = data.getDoubleExtra("latitude", 0);
double longitude = data.getDoubleExtra("longitude", 0); final double longitude = data.getDoubleExtra("longitude", 0);
Uri geo = Uri.parse("geo:" + latitude + "," + longitude); final int accuracy = data.getIntExtra("accuracy", 0);
final Uri geo;
if (accuracy > 0) {
geo = Uri.parse(String.format("geo:%s,%s;u=%s", latitude, longitude, accuracy));
} else {
geo = Uri.parse(String.format("geo:%s,%s", latitude, longitude));
}
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), geo, Attachment.Type.LOCATION)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), geo, Attachment.Type.LOCATION));
toggleInputMethod(); toggleInputMethod();
break; break;
@ -870,7 +885,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (anyNeedsExternalStoragePermission(attachments) && !hasPermissions(REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (anyNeedsExternalStoragePermission(attachments) && !hasPermissions(REQUEST_COMMIT_ATTACHMENTS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
return; return;
} }
if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_ATTACHMENTS)) { if (trustKeysIfNeeded(conversation, REQUEST_TRUST_KEYS_ATTACHMENTS)) {
return; return;
} }
final PresenceSelector.OnPresenceSelected callback = () -> { final PresenceSelector.OnPresenceSelected callback = () -> {
@ -880,7 +895,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
attachLocationToConversation(conversation, attachment.getUri()); attachLocationToConversation(conversation, attachment.getUri());
} else if (attachment.getType() == Attachment.Type.IMAGE) { } else if (attachment.getType() == Attachment.Type.IMAGE) {
Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE"); Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE");
attachImageToConversation(conversation, attachment.getUri()); attachImageToConversation(conversation, attachment.getUri(), attachment.getMime());
} else { } else {
Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO"); Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO");
attachFileToConversation(conversation, attachment.getUri(), attachment.getMime()); attachFileToConversation(conversation, attachment.getUri(), attachment.getMime());
@ -986,7 +1001,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
menuCall.setVisible(false); menuCall.setVisible(false);
menuOngoingCall.setVisible(false); menuOngoingCall.setVisible(false);
} else { } else {
final XmppConnectionService service = activity.xmppConnectionService; final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
final Optional<OngoingRtpSession> ongoingRtpSession = service == null ? Optional.absent() : service.getJingleConnectionManager().getOngoingRtpConnection(conversation.getContact()); final Optional<OngoingRtpSession> ongoingRtpSession = service == null ? Optional.absent() : service.getJingleConnectionManager().getOngoingRtpConnection(conversation.getContact());
if (ongoingRtpSession.isPresent()) { if (ongoingRtpSession.isPresent()) {
menuOngoingCall.setVisible(true); menuOngoingCall.setVisible(true);
@ -994,8 +1009,9 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} else { } else {
menuOngoingCall.setVisible(false); menuOngoingCall.setVisible(false);
final RtpCapability.Capability rtpCapability = RtpCapability.check(conversation.getContact()); final RtpCapability.Capability rtpCapability = RtpCapability.check(conversation.getContact());
final boolean cameraAvailable = activity != null && activity.isCameraFeatureAvailable();
menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE); menuCall.setVisible(rtpCapability != RtpCapability.Capability.NONE);
menuVideoCall.setVisible(rtpCapability == RtpCapability.Capability.VIDEO); menuVideoCall.setVisible(rtpCapability == RtpCapability.Capability.VIDEO && cameraAvailable);
} }
menuContactDetails.setVisible(!this.conversation.withSelf()); menuContactDetails.setVisible(!this.conversation.withSelf());
menuMucDetails.setVisible(false); menuMucDetails.setVisible(false);
@ -1037,7 +1053,6 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList); messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList);
messageListAdapter.setOnContactPictureClicked(this); messageListAdapter.setOnContactPictureClicked(this);
messageListAdapter.setOnContactPictureLongClicked(this); messageListAdapter.setOnContactPictureLongClicked(this);
messageListAdapter.setOnQuoteListener(this::quoteText);
binding.messagesView.setAdapter(messageListAdapter); binding.messagesView.setAdapter(messageListAdapter);
registerForContextMenu(binding.messagesView); registerForContextMenu(binding.messagesView);
@ -1055,7 +1070,6 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()"); Log.d(Config.LOGTAG, "ConversationFragment.onDestroyView()");
messageListAdapter.setOnContactPictureClicked(null); messageListAdapter.setOnContactPictureClicked(null);
messageListAdapter.setOnContactPictureLongClicked(null); messageListAdapter.setOnContactPictureLongClicked(null);
messageListAdapter.setOnQuoteListener(null);
} }
private void quoteText(String text) { private void quoteText(String text) {
@ -1263,10 +1277,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
activity.switchToContactDetails(conversation.getContact()); activity.switchToContactDetails(conversation.getContact());
break; break;
case R.id.action_muc_details: case R.id.action_muc_details:
Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class); ConferenceDetailsActivity.open(getActivity(), conversation);
intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
intent.putExtra("uuid", conversation.getUuid());
startActivity(intent);
break; break;
case R.id.action_invite: case R.id.action_invite:
startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION); startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION);
@ -1366,7 +1377,6 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG).show(); Toast.makeText(getActivity(), R.string.only_one_call_at_a_time, Toast.LENGTH_LONG).show();
return; return;
} }
final Contact contact = conversation.getContact(); final Contact contact = conversation.getContact();
if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) { if (contact.getPresences().anySupport(Namespace.JINGLE_MESSAGE)) {
triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action); triggerRtpSession(contact.getAccount(), contact.getJid().asBareJid(), action);
@ -1573,11 +1583,12 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} else { } else {
res = R.string.no_storage_permission; res = R.string.no_storage_permission;
} }
Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
} }
} }
if (writeGranted(grantResults, permissions)) { if (writeGranted(grantResults, permissions)) {
if (activity != null && activity.xmppConnectionService != null) { if (activity != null && activity.xmppConnectionService != null) {
activity.xmppConnectionService.getBitmapCache().evictAll();
activity.xmppConnectionService.restartFileObserver(); activity.xmppConnectionService.restartFileObserver();
} }
refresh(); refresh();
@ -1607,7 +1618,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
private void createNewConnection(final Message message) { private void createNewConnection(final Message message) {
if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) { if (!activity.xmppConnectionService.hasInternetConnection()) {
Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
return; return;
} }
@ -1616,9 +1627,9 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
@SuppressLint("InflateParams") @SuppressLint("InflateParams")
protected void clearHistoryDialog(final Conversation conversation) { protected void clearHistoryDialog(final Conversation conversation) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setTitle(getString(R.string.clear_conversation_history)); builder.setTitle(getString(R.string.clear_conversation_history));
final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null); final View dialogView = requireActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null);
final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox); final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox);
builder.setView(dialogView); builder.setView(dialogView);
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
@ -1636,7 +1647,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
protected void muteConversationDialog(final Conversation conversation) { protected void muteConversationDialog(final Conversation conversation) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setTitle(R.string.disable_notifications); builder.setTitle(R.string.disable_notifications);
final int[] durations = getResources().getIntArray(R.array.mute_options_durations); final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
final CharSequence[] labels = new CharSequence[durations.length]; final CharSequence[] labels = new CharSequence[durations.length];
@ -1652,13 +1663,13 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (durations[which] == -1) { if (durations[which] == -1) {
till = Long.MAX_VALUE; till = Long.MAX_VALUE;
} else { } else {
till = System.currentTimeMillis() + (durations[which] * 1000); till = System.currentTimeMillis() + (durations[which] * 1000L);
} }
conversation.setMutedTill(till); conversation.setMutedTill(till);
activity.xmppConnectionService.updateConversation(conversation); activity.xmppConnectionService.updateConversation(conversation);
activity.onConversationsListItemUpdated(); activity.onConversationsListItemUpdated();
refresh(); refresh();
getActivity().invalidateOptionsMenu(); requireActivity().invalidateOptionsMenu();
}); });
builder.create().show(); builder.create().show();
} }
@ -1690,7 +1701,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
this.activity.xmppConnectionService.updateConversation(conversation); this.activity.xmppConnectionService.updateConversation(conversation);
this.activity.onConversationsListItemUpdated(); this.activity.onConversationsListItemUpdated();
refresh(); refresh();
getActivity().invalidateOptionsMenu(); requireActivity().invalidateOptionsMenu();
} }
@ -1700,9 +1711,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
switch (attachmentChoice) { switch (attachmentChoice) {
case ATTACHMENT_CHOICE_CHOOSE_IMAGE: case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
intent.setAction(Intent.ACTION_GET_CONTENT); intent.setAction(Intent.ACTION_GET_CONTENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setType("image/*"); intent.setType("image/*");
chooser = true; chooser = true;
break; break;
@ -1720,9 +1729,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
case ATTACHMENT_CHOICE_CHOOSE_FILE: case ATTACHMENT_CHOICE_CHOOSE_FILE:
chooser = true; chooser = true;
intent.setType("*/*"); intent.setType("*/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.addCategory(Intent.CATEGORY_OPENABLE); intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setAction(Intent.ACTION_GET_CONTENT); intent.setAction(Intent.ACTION_GET_CONTENT);
break; break;
@ -1805,7 +1812,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
private void showErrorMessage(final Message message) { private void showErrorMessage(final Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setTitle(R.string.error_message); builder.setTitle(R.string.error_message);
final String errorMessage = message.getErrorMessage(); final String errorMessage = message.getErrorMessage();
final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f"); final String[] errorMessageParts = errorMessage == null ? new String[0] : errorMessage.split("\\u001f");
@ -1826,7 +1833,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
private void deleteFile(final Message message) { private void deleteFile(final Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
builder.setNegativeButton(R.string.cancel, null); builder.setNegativeButton(R.string.cancel, null);
builder.setTitle(R.string.delete_file_dialog); builder.setTitle(R.string.delete_file_dialog);
builder.setMessage(R.string.delete_file_dialog_msg); builder.setMessage(R.string.delete_file_dialog_msg);
@ -1855,7 +1862,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
if (!message.hasFileOnRemoteHost() if (!message.hasFileOnRemoteHost()
&& xmppConnection != null && xmppConnection != null
&& conversation.getMode() == Conversational.MODE_SINGLE && conversation.getMode() == Conversational.MODE_SINGLE
&& !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) { && !xmppConnection.getFeatures().httpUpload(message.getFileParams().getSize())) {
activity.selectPresence(conversation, () -> { activity.selectPresence(conversation, () -> {
message.setCounterpart(conversation.getNextCounterpart()); message.setCounterpart(conversation.getNextCounterpart());
activity.xmppConnectionService.resendFailedMessages(message); activity.xmppConnectionService.resendFailedMessages(message);
@ -1960,7 +1967,7 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
@Override @Override
public void onSaveInstanceState(Bundle outState) { public void onSaveInstanceState(@NotNull Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
if (conversation != null) { if (conversation != null) {
outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid()); outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid());
@ -2184,13 +2191,14 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE); final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE);
final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false); final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false);
final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false); final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false);
final String type = extras.getString(ConversationsActivity.EXTRA_TYPE);
final List<Uri> uris = extractUris(extras); final List<Uri> uris = extractUris(extras);
if (uris != null && uris.size() > 0) { if (uris != null && uris.size() > 0) {
if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) { if (uris.size() == 1 && "geo".equals(uris.get(0).getScheme())) {
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uris.get(0), Attachment.Type.LOCATION));
} else { } else {
final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris)); final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris));
mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris, type));
} }
toggleInputMethod(); toggleInputMethod();
return; return;
@ -2993,6 +3001,11 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
final Menu menu = popupMenu.getMenu(); final Menu menu = popupMenu.getMenu();
menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations()); menu.findItem(R.id.action_manage_accounts).setVisible(QuickConversationsService.isConversations());
popupMenu.setOnMenuItemClickListener(item -> { popupMenu.setOnMenuItemClickListener(item -> {
final XmppActivity activity = this.activity;
if (activity == null) {
Log.e(Config.LOGTAG,"Unable to perform action. no context provided");
return true;
}
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_show_qr_code: case R.id.action_show_qr_code:
activity.showQrCode(conversation.getAccount().getShareableUri()); activity.showQrCode(conversation.getAccount().getShareableUri());
@ -3044,4 +3057,12 @@ public class ConversationFragment extends XmppFragment implements EditMessage.Ke
} }
activity.switchToAccount(message.getConversation().getAccount(), fingerprint); activity.switchToAccount(message.getConversation().getAccount(), fingerprint);
} }
private Activity requireActivity() {
final Activity activity = getActivity();
if (activity == null) {
throw new IllegalStateException("Activity not attached");
}
return activity;
}
} }

View File

@ -30,6 +30,8 @@
package eu.siacs.conversations.ui; package eu.siacs.conversations.ui;
import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.Fragment; import android.app.Fragment;
@ -65,13 +67,16 @@ import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.OmemoSetting; import eu.siacs.conversations.crypto.OmemoSetting;
import eu.siacs.conversations.databinding.ActivityConversationsBinding; import eu.siacs.conversations.databinding.ActivityConversationsBinding;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Conversational;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.interfaces.OnBackendConnected; import eu.siacs.conversations.ui.interfaces.OnBackendConnected;
import eu.siacs.conversations.ui.interfaces.OnConversationArchived; import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
import eu.siacs.conversations.ui.interfaces.OnConversationRead; import eu.siacs.conversations.ui.interfaces.OnConversationRead;
import eu.siacs.conversations.ui.interfaces.OnConversationSelected; import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated; import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
import eu.siacs.conversations.ui.util.ActionBarUtil;
import eu.siacs.conversations.ui.util.ActivityResult; import eu.siacs.conversations.ui.util.ActivityResult;
import eu.siacs.conversations.ui.util.ConversationMenuConfigurator; import eu.siacs.conversations.ui.util.ConversationMenuConfigurator;
import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
@ -83,8 +88,6 @@ import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged { public class ConversationsActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnAffiliationChanged {
public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW"; public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
@ -96,6 +99,7 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
public static final String EXTRA_DO_NOT_APPEND = "do_not_append"; public static final String EXTRA_DO_NOT_APPEND = "do_not_append";
public static final String EXTRA_POST_INIT_ACTION = "post_init_action"; public static final String EXTRA_POST_INIT_ACTION = "post_init_action";
public static final String POST_ACTION_RECORD_VOICE = "record_voice"; public static final String POST_ACTION_RECORD_VOICE = "record_voice";
public static final String EXTRA_TYPE = "type";
private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList( private static final List<String> VIEW_AND_SHARE_ACTIONS = Arrays.asList(
ACTION_VIEW_CONVERSATION, ACTION_VIEW_CONVERSATION,
@ -224,7 +228,7 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) { && getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.battery_optimizations_enabled); builder.setTitle(R.string.battery_optimizations_enabled);
builder.setMessage(R.string.battery_optimizations_enabled_dialog); builder.setMessage(getString(R.string.battery_optimizations_enabled_dialog, getString(R.string.app_name)));
builder.setPositiveButton(R.string.next, (dialog, which) -> { builder.setPositiveButton(R.string.next, (dialog, which) -> {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
Uri uri = Uri.parse("package:" + getPackageName()); Uri uri = Uri.parse("package:" + getPackageName());
@ -278,6 +282,7 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults); UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
if (grantResults.length > 0) { if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
@ -425,16 +430,18 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
} }
private void openConversation(Conversation conversation, Bundle extras) { private void openConversation(Conversation conversation, Bundle extras) {
ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); final FragmentManager fragmentManager = getFragmentManager();
executePendingTransactions(fragmentManager);
ConversationFragment conversationFragment = (ConversationFragment) fragmentManager.findFragmentById(R.id.secondary_fragment);
final boolean mainNeedsRefresh; final boolean mainNeedsRefresh;
if (conversationFragment == null) { if (conversationFragment == null) {
mainNeedsRefresh = false; mainNeedsRefresh = false;
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
if (mainFragment instanceof ConversationFragment) { if (mainFragment instanceof ConversationFragment) {
conversationFragment = (ConversationFragment) mainFragment; conversationFragment = (ConversationFragment) mainFragment;
} else { } else {
conversationFragment = new ConversationFragment(); conversationFragment = new ConversationFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.main_fragment, conversationFragment); fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
fragmentTransaction.addToBackStack(null); fragmentTransaction.addToBackStack(null);
try { try {
@ -456,6 +463,14 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
} }
} }
private static void executePendingTransactions(final FragmentManager fragmentManager) {
try {
fragmentManager.executePendingTransactions();
} catch (final Exception e) {
Log.e(Config.LOGTAG,"unable to execute pending fragment transactions");
}
}
public boolean onXmppUriClicked(Uri uri) { public boolean onXmppUriClicked(Uri uri) {
XmppUri xmppUri = new XmppUri(uri); XmppUri xmppUri = new XmppUri(uri);
if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) { if (xmppUri.isValidJid() && !xmppUri.hasFingerprints()) {
@ -524,6 +539,7 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart();
final int theme = findTheme(); final int theme = findTheme();
if (this.mTheme != theme) { if (this.mTheme != theme) {
this.mSkipBackgroundBinding = true; this.mSkipBackgroundBinding = true;
@ -532,7 +548,6 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
this.mSkipBackgroundBinding = false; this.mSkipBackgroundBinding = false;
} }
mRedirectInProcess.set(false); mRedirectInProcess.set(false);
super.onStart();
} }
@Override @Override
@ -562,17 +577,18 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
} }
private void initializeFragments() { private void initializeFragments() {
FragmentTransaction transaction = getFragmentManager().beginTransaction(); final FragmentManager fragmentManager = getFragmentManager();
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment); final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
if (mainFragment != null) { if (mainFragment != null) {
if (binding.secondaryFragment != null) { if (binding.secondaryFragment != null) {
if (mainFragment instanceof ConversationFragment) { if (mainFragment instanceof ConversationFragment) {
getFragmentManager().popBackStack(); getFragmentManager().popBackStack();
transaction.remove(mainFragment); transaction.remove(mainFragment);
transaction.commit(); transaction.commit();
getFragmentManager().executePendingTransactions(); fragmentManager.executePendingTransactions();
transaction = getFragmentManager().beginTransaction(); transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.secondary_fragment, mainFragment); transaction.replace(R.id.secondary_fragment, mainFragment);
transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment()); transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
transaction.commit(); transaction.commit();
@ -583,7 +599,7 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
transaction.remove(secondaryFragment); transaction.remove(secondaryFragment);
transaction.commit(); transaction.commit();
getFragmentManager().executePendingTransactions(); getFragmentManager().executePendingTransactions();
transaction = getFragmentManager().beginTransaction(); transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_fragment, secondaryFragment); transaction.replace(R.id.main_fragment, secondaryFragment);
transaction.addToBackStack(null); transaction.addToBackStack(null);
transaction.commit(); transaction.commit();
@ -601,18 +617,38 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
private void invalidateActionBarTitle() { private void invalidateActionBarTitle() {
final ActionBar actionBar = getSupportActionBar(); final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) { if (actionBar == null) {
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); return;
}
final FragmentManager fragmentManager = getFragmentManager();
final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
if (mainFragment instanceof ConversationFragment) { if (mainFragment instanceof ConversationFragment) {
final Conversation conversation = ((ConversationFragment) mainFragment).getConversation(); final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
if (conversation != null) { if (conversation != null) {
actionBar.setTitle(EmojiWrapper.transform(conversation.getName())); actionBar.setTitle(EmojiWrapper.transform(conversation.getName()));
actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true);
ActionBarUtil.setActionBarOnClickListener(
binding.toolbar,
(v) -> openConversationDetails(conversation)
);
return; return;
} }
} }
actionBar.setTitle(R.string.app_name); actionBar.setTitle(R.string.app_name);
actionBar.setDisplayHomeAsUpEnabled(false); actionBar.setDisplayHomeAsUpEnabled(false);
ActionBarUtil.resetActionBarOnClickListeners(binding.toolbar);
}
private void openConversationDetails(final Conversation conversation) {
if (conversation.getMode() == Conversational.MODE_MULTI) {
ConferenceDetailsActivity.open(this, conversation);
} else {
final Contact contact = conversation.getContact();
if (contact.isSelf()) {
switchToAccount(conversation.getAccount());
} else {
switchToContactDetails(contact);
}
} }
} }
@ -621,17 +657,18 @@ public class ConversationsActivity extends XmppActivity implements OnConversatio
if (performRedirectIfNecessary(conversation, false)) { if (performRedirectIfNecessary(conversation, false)) {
return; return;
} }
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); final FragmentManager fragmentManager = getFragmentManager();
final Fragment mainFragment = fragmentManager.findFragmentById(R.id.main_fragment);
if (mainFragment instanceof ConversationFragment) { if (mainFragment instanceof ConversationFragment) {
try { try {
getFragmentManager().popBackStack(); fragmentManager.popBackStack();
} catch (IllegalStateException e) { } catch (final IllegalStateException e) {
Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e); Log.w(Config.LOGTAG, "state loss while popping back state after archiving conversation", e);
//this usually means activity is no longer active; meaning on the next open we will run through this again //this usually means activity is no longer active; meaning on the next open we will run through this again
} }
return; return;
} }
Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment); final Fragment secondaryFragment = fragmentManager.findFragmentById(R.id.secondary_fragment);
if (secondaryFragment instanceof ConversationFragment) { if (secondaryFragment instanceof ConversationFragment) {
if (((ConversationFragment) secondaryFragment).getConversation() == conversation) { if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation); Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);

View File

@ -38,7 +38,6 @@ import com.google.common.base.CharMatcher;
import org.openintents.openpgp.util.OpenPgpUtils; import org.openintents.openpgp.util.OpenPgpUtils;
import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -78,6 +77,7 @@ import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.XmppConnection.Features; import eu.siacs.conversations.xmpp.XmppConnection.Features;
import eu.siacs.conversations.xmpp.forms.Data; import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.pep.Avatar; import eu.siacs.conversations.xmpp.pep.Avatar;
import okhttp3.HttpUrl;
public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist, public class EditAccountActivity extends OmemoActivity implements OnAccountUpdate, OnUpdateBlocklist,
OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched { OnKeyStatusUpdated, OnCaptchaRequested, KeyChainAliasCallback, XmppConnectionService.OnShowErrorToast, XmppConnectionService.OnMamPreferencesFetched {
@ -188,7 +188,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
final boolean openRegistrationUrl = registerNewAccount && !accountInfoEdited && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB; final boolean openRegistrationUrl = registerNewAccount && !accountInfoEdited && mAccount != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB;
final boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED; final boolean openPaymentUrl = mAccount != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED;
final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl; final boolean redirectionWorthyStatus = openPaymentUrl || openRegistrationUrl;
URL url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null; final HttpUrl url = connection != null && redirectionWorthyStatus ? connection.getRedirectionUrl() : null;
if (url != null && !wasDisabled) { if (url != null && !wasDisabled) {
try { try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString()))); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.toString())));
@ -531,7 +531,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} }
} else { } else {
XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection(); XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
URL url = connection != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED ? connection.getRedirectionUrl() : null; HttpUrl url = connection != null && mAccount.getStatus() == Account.State.PAYMENT_REQUIRED ? connection.getRedirectionUrl() : null;
if (url != null) { if (url != null) {
this.binding.saveButton.setText(R.string.open_website); this.binding.saveButton.setText(R.string.open_website);
} else if (inNeedOfSaslAccept()) { } else if (inNeedOfSaslAccept()) {
@ -542,7 +542,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} }
} else { } else {
XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection(); XmppConnection connection = mAccount == null ? null : mAccount.getXmppConnection();
URL url = connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB ? connection.getRedirectionUrl() : null; HttpUrl url = connection != null && mAccount.getStatus() == Account.State.REGISTRATION_WEB ? connection.getRedirectionUrl() : null;
if (url != null && this.binding.accountRegisterNew.isChecked() && !accountInfoEdited) { if (url != null && this.binding.accountRegisterNew.isChecked() && !accountInfoEdited) {
this.binding.saveButton.setText(R.string.open_website); this.binding.saveButton.setText(R.string.open_website);
} else { } else {
@ -736,7 +736,8 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} }
@Override @Override
public void onNewIntent(Intent intent) { public void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
if (intent != null && intent.getData() != null) { if (intent != null && intent.getData() != null) {
final XmppUri uri = new XmppUri(intent.getData()); final XmppUri uri = new XmppUri(intent.getData());
if (xmppConnectionServiceBound) { if (xmppConnectionServiceBound) {
@ -1071,9 +1072,6 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
} else { } else {
this.binding.serverInfoHttpUpload.setText(R.string.server_info_available); this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
} }
} else if (features.p1S3FileTransfer()) {
this.binding.serverInfoHttpUploadDescription.setText(R.string.p1_s3_filetransfer);
this.binding.serverInfoHttpUpload.setText(R.string.server_info_available);
} else { } else {
this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable); this.binding.serverInfoHttpUpload.setText(R.string.server_info_unavailable);
} }
@ -1209,7 +1207,7 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE); this.binding.osOptimization.setVisibility(showBatteryWarning || showDataSaverWarning ? View.VISIBLE : View.GONE);
if (showDataSaverWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { if (showDataSaverWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled); this.binding.osOptimizationHeadline.setText(R.string.data_saver_enabled);
this.binding.osOptimizationBody.setText(R.string.data_saver_enabled_explained); this.binding.osOptimizationBody.setText(getString(R.string.data_saver_enabled_explained, getString(R.string.app_name)));
this.binding.osOptimizationDisable.setText(R.string.allow); this.binding.osOptimizationDisable.setText(R.string.allow);
this.binding.osOptimizationDisable.setOnClickListener(v -> { this.binding.osOptimizationDisable.setOnClickListener(v -> {
Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS); Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS);
@ -1218,13 +1216,13 @@ public class EditAccountActivity extends OmemoActivity implements OnAccountUpdat
try { try {
startActivityForResult(intent, REQUEST_DATA_SAVER); startActivityForResult(intent, REQUEST_DATA_SAVER);
} catch (ActivityNotFoundException e) { } catch (ActivityNotFoundException e) {
Toast.makeText(EditAccountActivity.this, R.string.device_does_not_support_data_saver, Toast.LENGTH_SHORT).show(); Toast.makeText(EditAccountActivity.this, getString(R.string.device_does_not_support_data_saver, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
} }
}); });
} else if (showBatteryWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { } else if (showBatteryWarning && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
this.binding.osOptimizationDisable.setText(R.string.disable); this.binding.osOptimizationDisable.setText(R.string.disable);
this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled); this.binding.osOptimizationHeadline.setText(R.string.battery_optimizations_enabled);
this.binding.osOptimizationBody.setText(R.string.battery_optimizations_enabled_explained); this.binding.osOptimizationBody.setText(getString(R.string.battery_optimizations_enabled_explained, getString(R.string.app_name)));
this.binding.osOptimizationDisable.setOnClickListener(v -> { this.binding.osOptimizationDisable.setOnClickListener(v -> {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
Uri uri = Uri.parse("package:" + getPackageName()); Uri uri = Uri.parse("package:" + getPackageName());

View File

@ -31,8 +31,6 @@ import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.CopyrightOverlay; import org.osmdroid.views.overlay.CopyrightOverlay;
import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.Overlay;
import java.io.IOException;
import eu.siacs.conversations.BuildConfig; import eu.siacs.conversations.BuildConfig;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
@ -41,6 +39,7 @@ import eu.siacs.conversations.services.QuickConversationsService;
import eu.siacs.conversations.ui.util.LocationHelper; import eu.siacs.conversations.ui.util.LocationHelper;
import eu.siacs.conversations.ui.widget.Marker; import eu.siacs.conversations.ui.widget.Marker;
import eu.siacs.conversations.ui.widget.MyLocation; import eu.siacs.conversations.ui.widget.MyLocation;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
public abstract class LocationActivity extends ActionBarActivity implements LocationListener { public abstract class LocationActivity extends ActionBarActivity implements LocationListener {
@ -70,6 +69,7 @@ public abstract class LocationActivity extends ActionBarActivity implements Loca
} }
} }
protected void updateLocationMarkers() { protected void updateLocationMarkers() {
clearMarkers(); clearMarkers();
} }
@ -98,11 +98,7 @@ public abstract class LocationActivity extends ActionBarActivity implements Loca
config.load(ctx, getPreferences()); config.load(ctx, getPreferences());
config.setUserAgentValue(BuildConfig.APPLICATION_ID + "/" + BuildConfig.VERSION_CODE); config.setUserAgentValue(BuildConfig.APPLICATION_ID + "/" + BuildConfig.VERSION_CODE);
if (QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor)) { if (QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor)) {
try {
config.setHttpProxy(HttpConnectionManager.getProxy()); config.setHttpProxy(HttpConnectionManager.getProxy());
} catch (IOException e) {
throw new RuntimeException("Unable to configure proxy");
}
} }
} }
@ -228,6 +224,7 @@ public abstract class LocationActivity extends ActionBarActivity implements Loca
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
Configuration.getInstance().load(this, getPreferences()); Configuration.getInstance().load(this, getPreferences());
map.onResume(); map.onResume();
this.setMyLoc(null); this.setMyLoc(null);

View File

@ -39,6 +39,7 @@ import java.util.logging.Logger;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.MTMDecision; import eu.siacs.conversations.entities.MTMDecision;
import eu.siacs.conversations.services.MemorizingTrustManager; import eu.siacs.conversations.services.MemorizingTrustManager;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
public class MemorizingActivity extends AppCompatActivity implements OnClickListener, OnCancelListener { public class MemorizingActivity extends AppCompatActivity implements OnClickListener, OnCancelListener {
@ -61,6 +62,8 @@ public class MemorizingActivity extends AppCompatActivity implements OnClickList
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
Intent i = getIntent(); Intent i = getIntent();
decisionId = i.getIntExtra(MemorizingTrustManager.DECISION_INTENT_ID, MTMDecision.DECISION_INVALID); decisionId = i.getIntExtra(MemorizingTrustManager.DECISION_INTENT_ID, MTMDecision.DECISION_INVALID);
int titleId = i.getIntExtra(MemorizingTrustManager.DECISION_TITLE_ID, R.string.mtm_accept_cert); int titleId = i.getIntExtra(MemorizingTrustManager.DECISION_TITLE_ID, R.string.mtm_accept_cert);

View File

@ -131,6 +131,7 @@ public class PublishProfilePictureActivity extends XmppActivity implements XmppC
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data); CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {

View File

@ -28,6 +28,7 @@ import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.databinding.ActivityRecordingBinding; import eu.siacs.conversations.databinding.ActivityRecordingBinding;
import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
import eu.siacs.conversations.utils.TimeFrameUtils; import eu.siacs.conversations.utils.TimeFrameUtils;
@ -66,6 +67,12 @@ public class RecordingActivity extends Activity implements View.OnClickListener
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} }
@Override
protected void onResume(){
super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
}
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();

View File

@ -1,5 +1,8 @@
package eu.siacs.conversations.ui; package eu.siacs.conversations.ui;
import static java.util.Arrays.asList;
import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied;
import android.Manifest; import android.Manifest;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.PictureInPictureParams; import android.app.PictureInPictureParams;
@ -14,6 +17,7 @@ import android.os.PowerManager;
import android.os.SystemClock; import android.os.SystemClock;
import android.util.Log; import android.util.Log;
import android.util.Rational; import android.util.Rational;
import android.view.KeyEvent;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
@ -34,6 +38,7 @@ import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Futures;
import org.checkerframework.checker.nullness.compatqual.NullableDecl; import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.webrtc.RendererCommon;
import org.webrtc.SurfaceViewRenderer; import org.webrtc.SurfaceViewRenderer;
import org.webrtc.VideoTrack; import org.webrtc.VideoTrack;
@ -53,6 +58,7 @@ import eu.siacs.conversations.services.AppRTCAudioManager;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.ui.util.AvatarWorkerTask; import eu.siacs.conversations.ui.util.AvatarWorkerTask;
import eu.siacs.conversations.ui.util.MainThreadExecutor; import eu.siacs.conversations.ui.util.MainThreadExecutor;
import eu.siacs.conversations.ui.util.Rationals;
import eu.siacs.conversations.utils.PermissionUtils; import eu.siacs.conversations.utils.PermissionUtils;
import eu.siacs.conversations.utils.TimeFrameUtils; import eu.siacs.conversations.utils.TimeFrameUtils;
import eu.siacs.conversations.xml.Namespace; import eu.siacs.conversations.xml.Namespace;
@ -63,10 +69,7 @@ import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
import eu.siacs.conversations.xmpp.jingle.Media; import eu.siacs.conversations.xmpp.jingle.Media;
import eu.siacs.conversations.xmpp.jingle.RtpEndUserState; import eu.siacs.conversations.xmpp.jingle.RtpEndUserState;
import static eu.siacs.conversations.utils.PermissionUtils.getFirstDenied; public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate, eu.siacs.conversations.ui.widget.SurfaceViewRenderer.OnAspectRatioChanged {
import static java.util.Arrays.asList;
public class RtpSessionActivity extends XmppActivity implements XmppConnectionService.OnJingleRtpConnectionUpdate {
public static final String EXTRA_WITH = "with"; public static final String EXTRA_WITH = "with";
public static final String EXTRA_SESSION_ID = "session_id"; public static final String EXTRA_SESSION_ID = "session_id";
@ -80,6 +83,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
private static final List<RtpEndUserState> END_CARD = Arrays.asList( private static final List<RtpEndUserState> END_CARD = Arrays.asList(
RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.APPLICATION_ERROR,
RtpEndUserState.SECURITY_ERROR,
RtpEndUserState.DECLINED_OR_BUSY, RtpEndUserState.DECLINED_OR_BUSY,
RtpEndUserState.CONNECTIVITY_ERROR, RtpEndUserState.CONNECTIVITY_ERROR,
RtpEndUserState.CONNECTIVITY_LOST_ERROR, RtpEndUserState.CONNECTIVITY_LOST_ERROR,
@ -87,11 +91,22 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
); );
private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON = Arrays.asList( private static final List<RtpEndUserState> STATES_SHOWING_HELP_BUTTON = Arrays.asList(
RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.APPLICATION_ERROR,
RtpEndUserState.CONNECTIVITY_ERROR RtpEndUserState.CONNECTIVITY_ERROR,
RtpEndUserState.SECURITY_ERROR
); );
private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT = Arrays.asList( private static final List<RtpEndUserState> STATES_SHOWING_SWITCH_TO_CHAT = Arrays.asList(
RtpEndUserState.CONNECTING, RtpEndUserState.CONNECTING,
RtpEndUserState.CONNECTED RtpEndUserState.CONNECTED,
RtpEndUserState.RECONNECTING
);
private static final List<RtpEndUserState> STATES_CONSIDERED_CONNECTED = Arrays.asList(
RtpEndUserState.CONNECTED,
RtpEndUserState.RECONNECTING
);
private static final List<RtpEndUserState> STATES_SHOWING_PIP_PLACEHOLDER = Arrays.asList(
RtpEndUserState.ACCEPTING_CALL,
RtpEndUserState.CONNECTING,
RtpEndUserState.RECONNECTING
); );
private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session"; private static final String PROXIMITY_WAKE_LOCK_TAG = "conversations:in-rtp-session";
private static final int REQUEST_ACCEPT_CALL = 0x1111; private static final int REQUEST_ACCEPT_CALL = 0x1111;
@ -146,6 +161,18 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
if (xmppConnectionService != null) {
if (xmppConnectionService.getNotificationService().stopSoundAndVibration()) {
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
private boolean isHelpButtonVisible() { private boolean isHelpButtonVisible() {
try { try {
return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState()); return STATES_SHOWING_HELP_BUTTON.contains(requireRtpConnection().getEndUserState());
@ -376,6 +403,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
if (state != null) { if (state != null) {
Log.d(Config.LOGTAG, "restored last state from intent extra"); Log.d(Config.LOGTAG, "restored last state from intent extra");
updateButtonConfiguration(state); updateButtonConfiguration(state);
updateVerifiedShield(false);
updateStateDisplay(state); updateStateDisplay(state);
updateProfilePicture(state); updateProfilePicture(state);
invalidateOptionsMenu(); invalidateOptionsMenu();
@ -421,7 +449,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} else { } else {
throw new IllegalStateException("Invalid permission result request"); throw new IllegalStateException("Invalid permission result request");
} }
Toast.makeText(this, res, Toast.LENGTH_SHORT).show(); Toast.makeText(this, getString(res, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
} }
} }
@ -429,12 +457,14 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL); mHandler.postDelayed(mTickExecutor, CALL_DURATION_UPDATE_INTERVAL);
this.binding.remoteVideo.setOnAspectRatioChanged(this);
} }
@Override @Override
public void onStop() { public void onStop() {
mHandler.removeCallbacks(mTickExecutor); mHandler.removeCallbacks(mTickExecutor);
binding.remoteVideo.release(); binding.remoteVideo.release();
binding.remoteVideo.setOnAspectRatioChanged(null);
binding.localVideo.release(); binding.localVideo.release();
final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference; final WeakReference<JingleRtpConnection> weakReference = this.rtpConnectionReference;
final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get(); final JingleRtpConnection jingleRtpConnection = weakReference == null ? null : weakReference.get();
@ -475,15 +505,14 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
return; return;
} }
//TODO apparently this method is not getting called on Android 10 when using the task switcher //TODO apparently this method is not getting called on Android 10 when using the task switcher
final boolean emptyReference = rtpConnectionReference == null || rtpConnectionReference.get() == null; if (emptyReference(rtpConnectionReference) && xmppConnectionService != null) {
if (emptyReference && xmppConnectionService != null) {
retractSessionProposal(); retractSessionProposal();
} }
} }
private boolean isConnected() { private boolean isConnected() {
final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null; final JingleRtpConnection connection = this.rtpConnectionReference != null ? this.rtpConnectionReference.get() : null;
return connection != null && connection.getEndUserState() == RtpEndUserState.CONNECTED; return connection != null && STATES_CONSIDERED_CONNECTED.contains(connection.getEndUserState());
} }
private boolean switchToPictureInPicture() { private boolean switchToPictureInPicture() {
@ -499,9 +528,12 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
private void startPictureInPicture() { private void startPictureInPicture() {
try { try {
final Rational rational = this.binding.remoteVideo.getAspectRatio();
final Rational clippedRational = Rationals.clip(rational);
Log.d(Config.LOGTAG, "suggested rational " + rational + ". clipped to " + clippedRational);
enterPictureInPictureMode( enterPictureInPictureMode(
new PictureInPictureParams.Builder() new PictureInPictureParams.Builder()
.setAspectRatio(new Rational(10, 16)) .setAspectRatio(clippedRational)
.build() .build()
); );
} catch (final IllegalStateException e) { } catch (final IllegalStateException e) {
@ -510,6 +542,17 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
} }
@Override
public void onAspectRatioChanged(final Rational rational) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isPictureInPicture()) {
final Rational clippedRational = Rationals.clip(rational);
Log.d(Config.LOGTAG, "suggested rational after aspect ratio change " + rational + ". clipped to " + clippedRational);
setPictureInPictureParams(new PictureInPictureParams.Builder()
.setAspectRatio(clippedRational)
.build());
}
}
private boolean deviceSupportsPictureInPicture() { private boolean deviceSupportsPictureInPicture() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE); return getPackageManager().hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE);
@ -545,6 +588,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
this.rtpConnectionReference = reference; this.rtpConnectionReference = reference;
final RtpEndUserState currentState = requireRtpConnection().getEndUserState(); final RtpEndUserState currentState = requireRtpConnection().getEndUserState();
final boolean verified = requireRtpConnection().isVerified();
if (currentState == RtpEndUserState.ENDED) { if (currentState == RtpEndUserState.ENDED) {
reference.get().throwStateTransitionException(); reference.get().throwStateTransitionException();
finish(); finish();
@ -560,6 +604,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
binding.with.setText(getWith().getDisplayName()); binding.with.setText(getWith().getDisplayName());
updateVideoViews(currentState); updateVideoViews(currentState);
updateStateDisplay(currentState, media); updateStateDisplay(currentState, media);
updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(currentState));
updateButtonConfiguration(currentState, media); updateButtonConfiguration(currentState, media);
updateProfilePicture(currentState); updateProfilePicture(currentState);
invalidateOptionsMenu(); invalidateOptionsMenu();
@ -578,6 +623,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
updateStateDisplay(state); updateStateDisplay(state);
updateProfilePicture(state); updateProfilePicture(state);
updateCallDuration(); updateCallDuration();
updateVerifiedShield(false);
invalidateOptionsMenu(); invalidateOptionsMenu();
binding.with.setText(account.getRoster().getContact(with).getDisplayName()); binding.with.setText(account.getRoster().getContact(with).getDisplayName());
} }
@ -599,8 +645,8 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
surfaceViewRenderer.setVisibility(View.VISIBLE); surfaceViewRenderer.setVisibility(View.VISIBLE);
try { try {
surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null); surfaceViewRenderer.init(requireRtpConnection().getEglBaseContext(), null);
} catch (IllegalStateException e) { } catch (final IllegalStateException e) {
Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized"); //Log.d(Config.LOGTAG, "SurfaceViewRenderer was already initialized");
} }
surfaceViewRenderer.setEnableHardwareScaler(true); surfaceViewRenderer.setEnableHardwareScaler(true);
} }
@ -625,6 +671,9 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
case CONNECTED: case CONNECTED:
setTitle(R.string.rtp_state_connected); setTitle(R.string.rtp_state_connected);
break; break;
case RECONNECTING:
setTitle(R.string.rtp_state_reconnecting);
break;
case ACCEPTING_CALL: case ACCEPTING_CALL:
setTitle(R.string.rtp_state_accepting_call); setTitle(R.string.rtp_state_accepting_call);
break; break;
@ -652,6 +701,9 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
case APPLICATION_ERROR: case APPLICATION_ERROR:
setTitle(R.string.rtp_state_application_failure); setTitle(R.string.rtp_state_application_failure);
break; break;
case SECURITY_ERROR:
setTitle(R.string.rtp_state_security_error);
break;
case ENDED: case ENDED:
throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();"); throw new IllegalStateException("Activity should have called finishAndReleaseWakeLock();");
default: default:
@ -659,6 +711,14 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
} }
private void updateVerifiedShield(final boolean verified) {
if (isPictureInPicture()) {
this.binding.verified.setVisibility(View.GONE);
return;
}
this.binding.verified.setVisibility(verified ? View.VISIBLE : View.GONE);
}
private void updateProfilePicture(final RtpEndUserState state) { private void updateProfilePicture(final RtpEndUserState state) {
updateProfilePicture(state, null); updateProfilePicture(state, null);
} }
@ -719,7 +779,8 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
RtpEndUserState.CONNECTIVITY_ERROR, RtpEndUserState.CONNECTIVITY_ERROR,
RtpEndUserState.CONNECTIVITY_LOST_ERROR, RtpEndUserState.CONNECTIVITY_LOST_ERROR,
RtpEndUserState.APPLICATION_ERROR, RtpEndUserState.APPLICATION_ERROR,
RtpEndUserState.RETRACTED RtpEndUserState.RETRACTED,
RtpEndUserState.SECURITY_ERROR
).contains(state)) { ).contains(state)) {
this.binding.rejectCall.setContentDescription(getString(R.string.exit)); this.binding.rejectCall.setContentDescription(getString(R.string.exit));
this.binding.rejectCall.setOnClickListener(this::exit); this.binding.rejectCall.setOnClickListener(this::exit);
@ -755,7 +816,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) { private void updateInCallButtonConfiguration(final RtpEndUserState state, final Set<Media> media) {
if (state == RtpEndUserState.CONNECTED && !isPictureInPicture()) { if (STATES_CONSIDERED_CONNECTED.contains(state) && !isPictureInPicture()) {
Preconditions.checkArgument(media.size() > 0, "Media must not be empty"); Preconditions.checkArgument(media.size() > 0, "Media must not be empty");
if (media.contains(Media.VIDEO)) { if (media.contains(Media.VIDEO)) {
final JingleRtpConnection rtpConnection = requireRtpConnection(); final JingleRtpConnection rtpConnection = requireRtpConnection();
@ -850,7 +911,12 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
private void enableVideo(View view) { private void enableVideo(View view) {
try {
requireRtpConnection().setVideoEnabled(true); requireRtpConnection().setVideoEnabled(true);
} catch (final IllegalStateException e) {
Toast.makeText(this, R.string.unable_to_enable_video, Toast.LENGTH_SHORT).show();
return;
}
updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable()); updateInCallButtonConfigurationVideo(true, requireRtpConnection().isCameraSwitchable());
} }
@ -878,14 +944,11 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
this.binding.duration.setVisibility(View.GONE); this.binding.duration.setVisibility(View.GONE);
return; return;
} }
final long rtpConnectionStarted = connection.getRtpConnectionStarted(); if (connection.zeroDuration()) {
final long rtpConnectionEnded = connection.getRtpConnectionEnded();
if (rtpConnectionStarted != 0) {
final long ended = rtpConnectionEnded == 0 ? SystemClock.elapsedRealtime() : rtpConnectionEnded;
this.binding.duration.setText(TimeFrameUtils.formatTimePassed(rtpConnectionStarted, ended, false));
this.binding.duration.setVisibility(View.VISIBLE);
} else {
this.binding.duration.setVisibility(View.GONE); this.binding.duration.setVisibility(View.GONE);
} else {
this.binding.duration.setText(TimeFrameUtils.formatElapsedTime(connection.getCallDuration(), false));
this.binding.duration.setVisibility(View.VISIBLE);
} }
} }
@ -893,13 +956,17 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) { if (END_CARD.contains(state) || state == RtpEndUserState.ENDING_CALL) {
binding.localVideo.setVisibility(View.GONE); binding.localVideo.setVisibility(View.GONE);
binding.localVideo.release(); binding.localVideo.release();
binding.remoteVideo.setVisibility(View.GONE); binding.remoteVideoWrapper.setVisibility(View.GONE);
binding.remoteVideo.release(); binding.remoteVideo.release();
binding.pipLocalMicOffIndicator.setVisibility(View.GONE); binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
if (isPictureInPicture()) { if (isPictureInPicture()) {
binding.appBarLayout.setVisibility(View.GONE); binding.appBarLayout.setVisibility(View.GONE);
binding.pipPlaceholder.setVisibility(View.VISIBLE); binding.pipPlaceholder.setVisibility(View.VISIBLE);
if (state == RtpEndUserState.APPLICATION_ERROR || state == RtpEndUserState.CONNECTIVITY_ERROR) { if (Arrays.asList(
RtpEndUserState.APPLICATION_ERROR,
RtpEndUserState.CONNECTIVITY_ERROR,
RtpEndUserState.SECURITY_ERROR)
.contains(state)) {
binding.pipWarning.setVisibility(View.VISIBLE); binding.pipWarning.setVisibility(View.VISIBLE);
binding.pipWaiting.setVisibility(View.GONE); binding.pipWaiting.setVisibility(View.GONE);
} else { } else {
@ -913,9 +980,9 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
return; return;
} }
if (isPictureInPicture() && (state == RtpEndUserState.CONNECTING || state == RtpEndUserState.ACCEPTING_CALL)) { if (isPictureInPicture() && STATES_SHOWING_PIP_PLACEHOLDER.contains(state)) {
binding.localVideo.setVisibility(View.GONE); binding.localVideo.setVisibility(View.GONE);
binding.remoteVideo.setVisibility(View.GONE); binding.remoteVideoWrapper.setVisibility(View.GONE);
binding.appBarLayout.setVisibility(View.GONE); binding.appBarLayout.setVisibility(View.GONE);
binding.pipPlaceholder.setVisibility(View.VISIBLE); binding.pipPlaceholder.setVisibility(View.VISIBLE);
binding.pipWarning.setVisibility(View.GONE); binding.pipWarning.setVisibility(View.GONE);
@ -937,12 +1004,18 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
if (remoteVideoTrack.isPresent()) { if (remoteVideoTrack.isPresent()) {
ensureSurfaceViewRendererIsSetup(binding.remoteVideo); ensureSurfaceViewRendererIsSetup(binding.remoteVideo);
addSink(remoteVideoTrack.get(), binding.remoteVideo); addSink(remoteVideoTrack.get(), binding.remoteVideo);
binding.remoteVideo.setScalingType(
RendererCommon.ScalingType.SCALE_ASPECT_FILL,
RendererCommon.ScalingType.SCALE_ASPECT_FIT
);
if (state == RtpEndUserState.CONNECTED) { if (state == RtpEndUserState.CONNECTED) {
binding.appBarLayout.setVisibility(View.GONE); binding.appBarLayout.setVisibility(View.GONE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
binding.remoteVideoWrapper.setVisibility(View.VISIBLE);
} else { } else {
binding.appBarLayout.setVisibility(View.VISIBLE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
binding.remoteVideo.setVisibility(View.GONE); binding.remoteVideoWrapper.setVisibility(View.GONE);
} }
if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) { if (isPictureInPicture() && !requireRtpConnection().isMicrophoneEnabled()) {
binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE); binding.pipLocalMicOffIndicator.setVisibility(View.VISIBLE);
@ -951,7 +1024,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
} else { } else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
binding.remoteVideo.setVisibility(View.GONE); binding.remoteVideoWrapper.setVisibility(View.GONE);
binding.pipLocalMicOffIndicator.setVisibility(View.GONE); binding.pipLocalMicOffIndicator.setVisibility(View.GONE);
} }
} }
@ -1052,7 +1125,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
updateRtpSessionProposalState(account, with, state); updateRtpSessionProposalState(account, with, state);
return; return;
} }
if (this.rtpConnectionReference == null) { if (emptyReference(this.rtpConnectionReference)) {
if (END_CARD.contains(state)) { if (END_CARD.contains(state)) {
Log.d(Config.LOGTAG, "not reinitializing session"); Log.d(Config.LOGTAG, "not reinitializing session");
return; return;
@ -1062,6 +1135,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
return; return;
} }
final AbstractJingleConnection.Id id = requireRtpConnection().getId(); final AbstractJingleConnection.Id id = requireRtpConnection().getId();
final boolean verified = requireRtpConnection().isVerified();
final Set<Media> media = getMedia(); final Set<Media> media = getMedia();
final Contact contact = getWith(); final Contact contact = getWith();
if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) { if (account == id.account && id.with.equals(with) && id.sessionId.equals(sessionId)) {
@ -1071,6 +1145,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
runOnUiThread(() -> { runOnUiThread(() -> {
updateStateDisplay(state, media); updateStateDisplay(state, media);
updateVerifiedShield(verified && STATES_SHOWING_SWITCH_TO_CHAT.contains(state));
updateButtonConfiguration(state, media); updateButtonConfiguration(state, media);
updateVideoViews(state); updateVideoViews(state);
updateProfilePicture(state, contact); updateProfilePicture(state, contact);
@ -1120,6 +1195,7 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
} }
if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) { if (Jid.ofEscaped(withExtra).asBareJid().equals(with)) {
runOnUiThread(() -> { runOnUiThread(() -> {
updateVerifiedShield(false);
updateStateDisplay(state); updateStateDisplay(state);
updateButtonConfiguration(state); updateButtonConfiguration(state);
updateProfilePicture(state); updateProfilePicture(state);
@ -1147,4 +1223,8 @@ public class RtpSessionActivity extends XmppActivity implements XmppConnectionSe
intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL); intent.putExtra(EXTRA_LAST_ACTION, media.contains(Media.VIDEO) ? ACTION_MAKE_VIDEO_CALL : ACTION_MAKE_VOICE_CALL);
setIntent(intent); setIntent(intent);
} }
private static boolean emptyReference(final WeakReference<?> weakReference) {
return weakReference == null || weakReference.get() == null;
}
} }

View File

@ -60,6 +60,7 @@ import java.util.Map;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.ui.service.CameraManager; import eu.siacs.conversations.ui.service.CameraManager;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.ui.widget.ScannerView; import eu.siacs.conversations.ui.widget.ScannerView;
/** /**
@ -181,6 +182,7 @@ public final class ScanActivity extends Activity implements SurfaceTextureListen
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
maybeOpenCamera(); maybeOpenCamera();
} }

View File

@ -40,6 +40,7 @@ import eu.siacs.conversations.services.MemorizingTrustManager;
import eu.siacs.conversations.services.QuickConversationsService; import eu.siacs.conversations.services.QuickConversationsService;
import eu.siacs.conversations.ui.util.StyledAttributes; import eu.siacs.conversations.ui.util.StyledAttributes;
import eu.siacs.conversations.utils.GeoHelper; import eu.siacs.conversations.utils.GeoHelper;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.TimeFrameUtils; import eu.siacs.conversations.utils.TimeFrameUtils;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
@ -57,8 +58,10 @@ public class SettingsActivity extends XmppActivity implements
public static final String THEME = "theme"; public static final String THEME = "theme";
public static final String SHOW_DYNAMIC_TAGS = "show_dynamic_tags"; public static final String SHOW_DYNAMIC_TAGS = "show_dynamic_tags";
public static final String OMEMO_SETTING = "omemo"; public static final String OMEMO_SETTING = "omemo";
public static final String PREVENT_SCREENSHOTS = "prevent_screenshots";
public static final int REQUEST_CREATE_BACKUP = 0xbf8701; public static final int REQUEST_CREATE_BACKUP = 0xbf8701;
private SettingsFragment mSettingsFragment; private SettingsFragment mSettingsFragment;
@Override @Override
@ -393,8 +396,15 @@ public class SettingsActivity extends XmppActivity implements
if (this.mTheme != theme) { if (this.mTheme != theme) {
recreate(); recreate();
} }
} else if(name.equals(PREVENT_SCREENSHOTS)){
SettingsUtils.applyScreenshotPreventionSetting(this);
}
} }
@Override
public void onResume(){
super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
} }
@Override @Override
@ -405,12 +415,16 @@ public class SettingsActivity extends XmppActivity implements
createBackup(); createBackup();
} }
} else { } else {
Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); Toast.makeText(this, getString(R.string.no_storage_permission, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
} }
} }
private void createBackup() { private void createBackup() {
ContextCompat.startForegroundService(this, new Intent(this, ExportBackupService.class)); ContextCompat.startForegroundService(this, new Intent(this, ExportBackupService.class));
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.backup_started_message);
builder.setPositiveButton(R.string.ok, null);
builder.create().show();
} }
private void displayToast(final String msg) { private void displayToast(final String msg) {

View File

@ -13,10 +13,13 @@ import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil; import androidx.databinding.DataBindingUtil;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import com.google.common.math.DoubleMath;
import org.osmdroid.api.IGeoPoint; import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.GeoPoint; import org.osmdroid.util.GeoPoint;
import java.math.RoundingMode;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.databinding.ActivityShareLocationBinding; import eu.siacs.conversations.databinding.ActivityShareLocationBinding;
@ -76,23 +79,7 @@ public class ShareLocationActivity extends LocationActivity implements LocationL
}); });
ThemeHelper.fix(this.snackBar); ThemeHelper.fix(this.snackBar);
this.binding.shareButton.setOnClickListener(view -> { this.binding.shareButton.setOnClickListener(this::shareLocation);
final Intent result = new Intent();
if (marker_fixed_to_loc && myLoc != null) {
result.putExtra("latitude", myLoc.getLatitude());
result.putExtra("longitude", myLoc.getLongitude());
result.putExtra("altitude", myLoc.getAltitude());
result.putExtra("accuracy", (int) myLoc.getAccuracy());
} else {
final IGeoPoint markerPoint = this.binding.map.getMapCenter();
result.putExtra("latitude", markerPoint.getLatitude());
result.putExtra("longitude", markerPoint.getLongitude());
}
setResult(RESULT_OK, result);
finish();
});
this.marker_fixed_to_loc = isLocationEnabledAndAllowed(); this.marker_fixed_to_loc = isLocationEnabledAndAllowed();
@ -108,6 +95,22 @@ public class ShareLocationActivity extends LocationActivity implements LocationL
}); });
} }
private void shareLocation(final View view) {
final Intent result = new Intent();
if (marker_fixed_to_loc && myLoc != null) {
result.putExtra("latitude", myLoc.getLatitude());
result.putExtra("longitude", myLoc.getLongitude());
result.putExtra("altitude", myLoc.getAltitude());
result.putExtra("accuracy", DoubleMath.roundToInt(myLoc.getAccuracy(), RoundingMode.HALF_UP));
} else {
final IGeoPoint markerPoint = this.binding.map.getMapCenter();
result.putExtra("latitude", markerPoint.getLatitude());
result.putExtra("longitude", markerPoint.getLongitude());
}
setResult(RESULT_OK, result);
finish();
}
@Override @Override
public void onRequestPermissionsResult(final int requestCode, public void onRequestPermissionsResult(final int requestCode,
@NonNull final String[] permissions, @NonNull final String[] permissions,

View File

@ -33,7 +33,8 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
refreshUi(); refreshUi();
} }
private class Share { private static class Share {
public String type;
ArrayList<Uri> uris = new ArrayList<>(); ArrayList<Uri> uris = new ArrayList<>();
public String account; public String account;
public String contact; public String contact;
@ -65,6 +66,7 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
@Override @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) if (grantResults.length > 0)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == REQUEST_STORAGE_PERMISSION) { if (requestCode == REQUEST_STORAGE_PERMISSION) {
@ -75,7 +77,7 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
} }
} }
} else { } else {
Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show(); Toast.makeText(this, getString(R.string.no_storage_permission, getString(R.string.app_name)), Toast.LENGTH_SHORT).show();
} }
} }
@ -139,6 +141,7 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
} else if (type != null && uri != null) { } else if (type != null && uri != null) {
this.share.uris.clear(); this.share.uris.clear();
this.share.uris.add(uri); this.share.uris.add(uri);
this.share.type = type;
} else { } else {
this.share.text = text; this.share.text = text;
this.share.asQuote = asQuote; this.share.asQuote = asQuote;
@ -193,6 +196,9 @@ public class ShareWithActivity extends XmppActivity implements XmppConnectionSer
intent.setAction(Intent.ACTION_SEND_MULTIPLE); intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, share.uris); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, share.uris);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (share.type != null) {
intent.putExtra(ConversationsActivity.EXTRA_TYPE, share.type);
}
} else if (share.text != null) { } else if (share.text != null) {
intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION); intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
intent.putExtra(Intent.EXTRA_TEXT, share.text); intent.putExtra(Intent.EXTRA_TEXT, share.text);

View File

@ -37,10 +37,14 @@ import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.MenuRes;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil; import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentManager;
@ -50,6 +54,8 @@ import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager; import androidx.viewpager.widget.ViewPager;
import com.google.android.material.textfield.TextInputLayout; import com.google.android.material.textfield.TextInputLayout;
import com.leinardi.android.speeddial.SpeedDialActionItem;
import com.leinardi.android.speeddial.SpeedDialView;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -265,8 +271,7 @@ public class StartConversationActivity extends XmppActivity implements XmppConne
setSupportActionBar(binding.toolbar); setSupportActionBar(binding.toolbar);
configureActionBar(getSupportActionBar()); configureActionBar(getSupportActionBar());
binding.speedDial.inflate(R.menu.start_conversation_fab_submenu); inflateFab(binding.speedDial, R.menu.start_conversation_fab_submenu);
binding.tabLayout.setupWithViewPager(binding.startConversationViewPager); binding.tabLayout.setupWithViewPager(binding.startConversationViewPager);
binding.startConversationViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { binding.startConversationViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override @Override
@ -337,6 +342,21 @@ public class StartConversationActivity extends XmppActivity implements XmppConne
}); });
} }
private void inflateFab(final SpeedDialView speedDialView, final @MenuRes int menuRes) {
speedDialView.clearActionItems();
final PopupMenu popupMenu = new PopupMenu(this, new View(this));
popupMenu.inflate(menuRes);
final Menu menu = popupMenu.getMenu();
for (int i = 0; i < menu.size(); i++) {
final MenuItem menuItem = menu.getItem(i);
final SpeedDialActionItem actionItem = new SpeedDialActionItem.Builder(menuItem.getItemId(), menuItem.getIcon())
.setLabel(menuItem.getTitle() != null ? menuItem.getTitle().toString() : null)
.setFabImageTintColor(ContextCompat.getColor(this, R.color.white))
.create();
speedDialView.addActionItem(actionItem);
}
}
public static boolean isValidJid(String input) { public static boolean isValidJid(String input) {
try { try {
Jid jid = Jid.ofEscaped(input); Jid jid = Jid.ofEscaped(input);
@ -525,7 +545,8 @@ public class StartConversationActivity extends XmppActivity implements XmppConne
} else if (contact.showInRoster()) { } else if (contact.showInRoster()) {
throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists)); throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists));
} else { } else {
xmppConnectionService.createContact(contact, true); final String preAuth = invite == null ? null : invite.getParameter(XmppUri.PARAMETER_PRE_AUTH);
xmppConnectionService.createContact(contact, true, preAuth);
if (invite != null && invite.hasFingerprints()) { if (invite != null && invite.hasFingerprints()) {
xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
} }
@ -731,19 +752,35 @@ public class StartConversationActivity extends XmppActivity implements XmppConne
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
if (mRequestedContactsPermission.compareAndSet(false, true)) { if (mRequestedContactsPermission.compareAndSet(false, true)) {
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) { if (QuickConversationsService.isQuicksy() || shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AtomicBoolean requestPermission = new AtomicBoolean(false);
builder.setTitle(R.string.sync_with_contacts); builder.setTitle(R.string.sync_with_contacts);
if (QuickConversationsService.isQuicksy()) { if (QuickConversationsService.isQuicksy()) {
builder.setMessage(Html.fromHtml(getString(R.string.sync_with_contacts_quicksy))); builder.setMessage(Html.fromHtml(getString(R.string.sync_with_contacts_quicksy)));
} else { } else {
builder.setMessage(R.string.sync_with_contacts_long); builder.setMessage(getString(R.string.sync_with_contacts_long, getString(R.string.app_name)));
} }
builder.setPositiveButton(R.string.next, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS)); @StringRes int confirmButtonText;
builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS)); if (QuickConversationsService.isConversations()) {
builder.setCancelable(false); confirmButtonText = R.string.next;
AlertDialog dialog = builder.create(); } else {
dialog.setCanceledOnTouchOutside(false); confirmButtonText = R.string.confirm;
}
builder.setPositiveButton(confirmButtonText, (dialog, which) -> {
if (requestPermission.compareAndSet(false, true)) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
}
});
builder.setOnDismissListener(dialog -> {
if (QuickConversationsService.isConversations() && requestPermission.compareAndSet(false, true)) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS);
}
});
builder.setCancelable(QuickConversationsService.isQuicksy());
final AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(QuickConversationsService.isQuicksy());
dialog.setOnShowListener(dialogInterface -> { dialog.setOnShowListener(dialogInterface -> {
final TextView tv = dialog.findViewById(android.R.id.message); final TextView tv = dialog.findViewById(android.R.id.message);
if (tv != null) { if (tv != null) {

View File

@ -237,7 +237,7 @@ public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdat
} }
this.binding.keyErrorHintMutual.setVisibility(anyWithoutMutualPresenceSubscription ? View.VISIBLE : View.GONE); this.binding.keyErrorHintMutual.setVisibility(anyWithoutMutualPresenceSubscription ? View.VISIBLE : View.GONE);
Contact contact = mAccount.getRoster().getContact(contactJids.get(0)); Contact contact = mAccount.getRoster().getContact(contactJids.get(0));
binding.keyErrorGeneral.setText(getString(R.string.error_trustkey_general, contact.getDisplayName())); binding.keyErrorGeneral.setText(getString(R.string.error_trustkey_general, getString(R.string.app_name), contact.getDisplayName()));
binding.ownKeysDetails.removeAllViews(); binding.ownKeysDetails.removeAllViews();
if (OmemoSetting.isAlways()) { if (OmemoSetting.isAlways()) {
binding.disableButton.setVisibility(View.GONE); binding.disableButton.setVisibility(View.GONE);

View File

@ -7,24 +7,39 @@ import android.content.pm.PackageManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.databinding.ActivityUriHandlerBinding;
import eu.siacs.conversations.http.HttpConnectionManager;
import eu.siacs.conversations.persistance.DatabaseBackend; import eu.siacs.conversations.persistance.DatabaseBackend;
import eu.siacs.conversations.services.QuickConversationsService; import eu.siacs.conversations.services.QuickConversationsService;
import eu.siacs.conversations.utils.ProvisioningUtils; import eu.siacs.conversations.utils.ProvisioningUtils;
import eu.siacs.conversations.utils.SignupUtils; import eu.siacs.conversations.utils.SignupUtils;
import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.utils.XmppUri;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
public class UriHandlerActivity extends AppCompatActivity { public class UriHandlerActivity extends AppCompatActivity {
@ -34,7 +49,9 @@ public class UriHandlerActivity extends AppCompatActivity {
private static final int REQUEST_CAMERA_PERMISSIONS_TO_SCAN = 0x6789; private static final int REQUEST_CAMERA_PERMISSIONS_TO_SCAN = 0x6789;
private static final int REQUEST_CAMERA_PERMISSIONS_TO_SCAN_AND_PROVISION = 0x6790; private static final int REQUEST_CAMERA_PERMISSIONS_TO_SCAN_AND_PROVISION = 0x6790;
private static final Pattern V_CARD_XMPP_PATTERN = Pattern.compile("\nIMPP([^:]*):(xmpp:.+)\n"); private static final Pattern V_CARD_XMPP_PATTERN = Pattern.compile("\nIMPP([^:]*):(xmpp:.+)\n");
private boolean handled = false; private static final Pattern LINK_HEADER_PATTERN = Pattern.compile("<(.*?)>");
private ActivityUriHandlerBinding binding;
private Call call;
public static void scan(final Activity activity) { public static void scan(final Activity activity) {
scan(activity, false); scan(activity, false);
@ -77,9 +94,7 @@ public class UriHandlerActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.handled = savedInstanceState != null && savedInstanceState.getBoolean("handled", false); this.binding = DataBindingUtil.setContentView(this, R.layout.activity_uri_handler);
getLayoutInflater().inflate(R.layout.toolbar, findViewById(android.R.id.content));
setSupportActionBar(findViewById(R.id.toolbar));
} }
@Override @Override
@ -89,21 +104,16 @@ public class UriHandlerActivity extends AppCompatActivity {
} }
@Override @Override
public void onSaveInstanceState(Bundle savedInstanceState) { public void onNewIntent(final Intent intent) {
savedInstanceState.putBoolean("handled", this.handled); super.onNewIntent(intent);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onNewIntent(Intent intent) {
handleIntent(intent); handleIntent(intent);
} }
private void handleUri(Uri uri) { private boolean handleUri(final Uri uri) {
handleUri(uri, false); return handleUri(uri, false);
} }
private void handleUri(Uri uri, final boolean scanned) { private boolean handleUri(final Uri uri, final boolean scanned) {
final Intent intent; final Intent intent;
final XmppUri xmppUri = new XmppUri(uri); final XmppUri xmppUri = new XmppUri(uri);
final List<Jid> accounts = DatabaseBackend.getInstance(this).getAccountJids(true); final List<Jid> accounts = DatabaseBackend.getInstance(this).getAccountJids(true);
@ -113,19 +123,22 @@ public class UriHandlerActivity extends AppCompatActivity {
final Jid jid = xmppUri.getJid(); final Jid jid = xmppUri.getJid();
if (xmppUri.isAction(XmppUri.ACTION_REGISTER)) { if (xmppUri.isAction(XmppUri.ACTION_REGISTER)) {
if (jid.getEscapedLocal() != null && accounts.contains(jid.asBareJid())) { if (jid.getEscapedLocal() != null && accounts.contains(jid.asBareJid())) {
Toast.makeText(this, R.string.account_already_exists, Toast.LENGTH_LONG).show(); showError(R.string.account_already_exists);
return; return false;
} }
intent = SignupUtils.getTokenRegistrationIntent(this, jid, preAuth); intent = SignupUtils.getTokenRegistrationIntent(this, jid, preAuth);
startActivity(intent); startActivity(intent);
return; return true;
} }
if (xmppUri.isAction(XmppUri.ACTION_ROSTER) && "y".equals(xmppUri.getParameter(XmppUri.PARAMETER_IBR))) { if (accounts.size() == 0 && xmppUri.isAction(XmppUri.ACTION_ROSTER) && "y".equals(xmppUri.getParameter(XmppUri.PARAMETER_IBR))) {
intent = SignupUtils.getTokenRegistrationIntent(this, jid.getDomain(), preAuth); intent = SignupUtils.getTokenRegistrationIntent(this, jid.getDomain(), preAuth);
intent.putExtra(StartConversationActivity.EXTRA_INVITE_URI, xmppUri.toString()); intent.putExtra(StartConversationActivity.EXTRA_INVITE_URI, xmppUri.toString());
startActivity(intent); startActivity(intent);
return; return true;
} }
} else if (xmppUri.isAction(XmppUri.ACTION_REGISTER)) {
showError(R.string.account_registrations_are_not_supported);
return false;
} }
if (accounts.size() == 0) { if (accounts.size() == 0) {
@ -133,26 +146,19 @@ public class UriHandlerActivity extends AppCompatActivity {
intent = SignupUtils.getSignUpIntent(this); intent = SignupUtils.getSignUpIntent(this);
intent.putExtra(StartConversationActivity.EXTRA_INVITE_URI, xmppUri.toString()); intent.putExtra(StartConversationActivity.EXTRA_INVITE_URI, xmppUri.toString());
startActivity(intent); startActivity(intent);
return true;
} else { } else {
Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show(); showError(R.string.invalid_jid);
return false;
} }
return;
} }
if (xmppUri.isAction(XmppUri.ACTION_MESSAGE)) { if (xmppUri.isAction(XmppUri.ACTION_MESSAGE)) {
final Jid jid = xmppUri.getJid(); final Jid jid = xmppUri.getJid();
final String body = xmppUri.getBody(); final String body = xmppUri.getBody();
if (jid != null) { if (jid != null) {
Class clazz; final Class<?> clazz = findShareViaAccountClass();
try {
clazz = Class.forName("eu.siacs.conversations.ui.ShareViaAccountActivity");
} catch (ClassNotFoundException e) {
clazz = null;
}
if (clazz != null) { if (clazz != null) {
intent = new Intent(this, clazz); intent = new Intent(this, clazz);
intent.putExtra("contact", jid.toEscapedString()); intent.putExtra("contact", jid.toEscapedString());
@ -163,7 +169,6 @@ public class UriHandlerActivity extends AppCompatActivity {
intent.setData(uri); intent.setData(uri);
intent.putExtra("account", accounts.get(0).toEscapedString()); intent.putExtra("account", accounts.get(0).toEscapedString());
} }
} else { } else {
intent = new Intent(this, ShareWithActivity.class); intent = new Intent(this, ShareWithActivity.class);
intent.setAction(Intent.ACTION_SEND); intent.setAction(Intent.ACTION_SEND);
@ -183,36 +188,94 @@ public class UriHandlerActivity extends AppCompatActivity {
intent.putExtra("scanned", scanned); intent.putExtra("scanned", scanned);
intent.setData(uri); intent.setData(uri);
} else { } else {
Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show(); showError(R.string.invalid_jid);
return; return false;
} }
startActivity(intent); startActivity(intent);
return true;
} }
private void handleIntent(Intent data) { private void checkForLinkHeader(final HttpUrl url) {
if (handled) { Log.d(Config.LOGTAG, "checking for link header on " + url);
this.call = HttpConnectionManager.OK_HTTP_CLIENT.newCall(new Request.Builder()
.url(url)
.head()
.build());
this.call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(Config.LOGTAG, "unable to check HTTP url", e);
showError(R.string.no_xmpp_adddress_found);
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
if (response.isSuccessful()) {
final String linkHeader = response.header("Link");
if (linkHeader != null && processLinkHeader(linkHeader)) {
return; return;
} }
if (data == null || data.getAction() == null) { }
showError(R.string.no_xmpp_adddress_found);
}
});
}
private boolean processLinkHeader(final String header) {
final Matcher matcher = LINK_HEADER_PATTERN.matcher(header);
if (matcher.find()) {
final String group = matcher.group();
final String link = group.substring(1, group.length() - 1);
if (handleUri(Uri.parse(link))) {
finish(); finish();
return; return true;
}
}
return false;
} }
handled = true; private void showError(@StringRes int error) {
this.binding.progress.setVisibility(View.INVISIBLE);
this.binding.error.setText(error);
this.binding.error.setVisibility(View.VISIBLE);
}
switch (data.getAction()) { private static Class<?> findShareViaAccountClass() {
try {
return Class.forName("eu.siacs.conversations.ui.ShareViaAccountActivity");
} catch (final ClassNotFoundException e) {
return null;
}
}
private void handleIntent(final Intent data) {
final String action = data == null ? null : data.getAction();
if (action == null) {
return;
}
switch (action) {
case Intent.ACTION_MAIN:
binding.progress.setVisibility(call != null && !call.isCanceled() ? View.VISIBLE : View.INVISIBLE);
break;
case Intent.ACTION_VIEW: case Intent.ACTION_VIEW:
case Intent.ACTION_SENDTO: case Intent.ACTION_SENDTO:
handleUri(data.getData()); if (handleUri(data.getData())) {
finish();
}
break; break;
case ACTION_SCAN_QR_CODE: case ACTION_SCAN_QR_CODE:
Intent intent = new Intent(this, ScanActivity.class); Log.d(Config.LOGTAG, "scan. allow=" + allowProvisioning());
startActivityForResult(intent, REQUEST_SCAN_QR_CODE); setIntent(createMainIntent());
return; startActivityForResult(new Intent(this, ScanActivity.class), REQUEST_SCAN_QR_CODE);
break;
}
} }
finish(); private Intent createMainIntent() {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra(EXTRA_ALLOW_PROVISIONING, allowProvisioning());
return intent;
} }
private boolean allowProvisioning() { private boolean allowProvisioning() {
@ -224,6 +287,7 @@ public class UriHandlerActivity extends AppCompatActivity {
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
super.onActivityResult(requestCode, requestCode, intent); super.onActivityResult(requestCode, requestCode, intent);
if (requestCode == REQUEST_SCAN_QR_CODE && resultCode == RESULT_OK) { if (requestCode == REQUEST_SCAN_QR_CODE && resultCode == RESULT_OK) {
final boolean allowProvisioning = allowProvisioning();
final String result = intent.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT); final String result = intent.getStringExtra(ScanActivity.INTENT_EXTRA_RESULT);
if (Strings.isNullOrEmpty(result)) { if (Strings.isNullOrEmpty(result)) {
finish(); finish();
@ -232,22 +296,38 @@ public class UriHandlerActivity extends AppCompatActivity {
if (result.startsWith("BEGIN:VCARD\n")) { if (result.startsWith("BEGIN:VCARD\n")) {
final Matcher matcher = V_CARD_XMPP_PATTERN.matcher(result); final Matcher matcher = V_CARD_XMPP_PATTERN.matcher(result);
if (matcher.find()) { if (matcher.find()) {
handleUri(Uri.parse(matcher.group(2)), true); if (handleUri(Uri.parse(matcher.group(2)), true)) {
}
finish(); finish();
}
} else {
showError(R.string.no_xmpp_adddress_found);
}
return; return;
} else if (QuickConversationsService.isConversations() && looksLikeJsonObject(result) && allowProvisioning()) { } else if (QuickConversationsService.isConversations() && looksLikeJsonObject(result) && allowProvisioning) {
ProvisioningUtils.provision(this, result); ProvisioningUtils.provision(this, result);
finish(); finish();
return; return;
} }
handleUri(Uri.parse(result), true); final Uri uri = Uri.parse(result.trim());
} if (allowProvisioning && "https".equalsIgnoreCase(uri.getScheme()) && !XmppUri.INVITE_DOMAIN.equalsIgnoreCase(uri.getHost())) {
final HttpUrl httpUrl = HttpUrl.parse(uri.toString());
if (httpUrl != null) {
checkForLinkHeader(httpUrl);
} else {
finish(); finish();
} }
} else if (handleUri(uri, true)) {
finish();
} else {
setIntent(new Intent(Intent.ACTION_VIEW, uri));
}
} else {
finish();
}
}
private static boolean looksLikeJsonObject(final String input) { private static boolean looksLikeJsonObject(final String input) {
final String trimmed = Strings.emptyToNull(input).trim(); final String trimmed = Strings.nullToEmpty(input).trim();
return trimmed.charAt(0) == '{' && trimmed.charAt(trimmed.length() - 1) == '}'; return trimmed.charAt(0) == '{' && trimmed.charAt(trimmed.length() - 1) == '}';
} }
} }

View File

@ -34,6 +34,7 @@ import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import android.os.SystemClock; import android.os.SystemClock;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.Html;
import android.text.InputType; import android.text.InputType;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
import android.util.Log; import android.util.Log;
@ -51,6 +52,8 @@ import androidx.appcompat.app.AlertDialog.Builder;
import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.app.AppCompatDelegate;
import androidx.databinding.DataBindingUtil; import androidx.databinding.DataBindingUtil;
import com.google.common.base.Strings;
import java.io.IOException; import java.io.IOException;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
@ -77,6 +80,7 @@ import eu.siacs.conversations.ui.util.PresenceSelector;
import eu.siacs.conversations.ui.util.SoftKeyboardUtils; import eu.siacs.conversations.ui.util.SoftKeyboardUtils;
import eu.siacs.conversations.utils.AccountUtils; import eu.siacs.conversations.utils.AccountUtils;
import eu.siacs.conversations.utils.ExceptionHelper; import eu.siacs.conversations.utils.ExceptionHelper;
import eu.siacs.conversations.ui.util.SettingsUtils;
import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.utils.ThemeHelper;
import eu.siacs.conversations.xmpp.Jid; import eu.siacs.conversations.xmpp.Jid;
import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
@ -248,7 +252,7 @@ public abstract class XmppActivity extends ActionBarActivity {
Builder builder = new AlertDialog.Builder(this); Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.openkeychain_required)); builder.setTitle(getString(R.string.openkeychain_required));
builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setIconAttribute(android.R.attr.alertDialogIcon);
builder.setMessage(getText(R.string.openkeychain_required_long)); builder.setMessage(Html.fromHtml(getString(R.string.openkeychain_required_long, getString(R.string.app_name))));
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
builder.setNeutralButton(getString(R.string.restart), builder.setNeutralButton(getString(R.string.restart),
(dialog, which) -> { (dialog, which) -> {
@ -405,11 +409,7 @@ public abstract class XmppActivity extends ActionBarActivity {
metrics = getResources().getDisplayMetrics(); metrics = getResources().getDisplayMetrics();
ExceptionHelper.init(getApplicationContext()); ExceptionHelper.init(getApplicationContext());
new EmojiService(this).init(); new EmojiService(this).init();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY); this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
} else {
this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
this.mTheme = findTheme(); this.mTheme = findTheme();
setTheme(this.mTheme); setTheme(this.mTheme);
} }
@ -572,13 +572,7 @@ public abstract class XmppActivity extends ActionBarActivity {
if (account.getPgpId() == 0) { if (account.getPgpId() == 0) {
choosePgpSignId(account); choosePgpSignId(account);
} else { } else {
String status = null; final String status = Strings.nullToEmpty(account.getPresenceStatusMessage());
if (manuallyChangePresence()) {
status = account.getPresenceStatusMessage();
}
if (status == null) {
status = "";
}
xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() { xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() {
@Override @Override
@ -826,8 +820,9 @@ public abstract class XmppActivity extends ActionBarActivity {
} }
@Override @Override
public void onResume() { protected void onResume(){
super.onResume(); super.onResume();
SettingsUtils.applyScreenshotPreventionSetting(this);
} }
protected int findTheme() { protected int findTheme() {

Some files were not shown because too many files have changed in this diff Show More