Removed all references to google play and firebase.

Removed phone number utils.
 Slowly remove signal code.
This commit is contained in:
Mikunj 2020-02-28 09:07:01 +11:00
parent 19356bf969
commit 3cdaf80c5d
25 changed files with 69 additions and 729 deletions

View File

@ -79,22 +79,13 @@
android:theme="@style/Session.DarkTheme" android:theme="@style/Session.DarkTheme"
tools:replace="android:allowBackup"> tools:replace="android:allowBackup">
<meta-data <!-- Disable analytics -->
android:name="io.fabric.ApiKey"
android:value="d0c4d13f424a96b9064aa0a9ecafabdb0db4287f" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCSx9xea86GwDKGznCAULE9Y5a8b-TfN9U" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<!--
<meta-data android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
-->
<meta-data <meta-data
android:name="firebase_analytics_collection_deactivated" android:name="firebase_analytics_collection_deactivated"
android:value="true" /> android:value="true" />
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
<meta-data <meta-data
android:name="google_analytics_adid_collection_enabled" android:name="google_analytics_adid_collection_enabled"
android:value="false" /> android:value="false" />
@ -440,10 +431,6 @@
android:noHistory="true" android:noHistory="true"
android:stateNotNeeded="true" android:stateNotNeeded="true"
android:theme="@android:style/Theme.NoDisplay" /> android:theme="@android:style/Theme.NoDisplay" />
<activity
android:name="org.thoughtcrime.securesms.PlayServicesProblemActivity"
android:configChanges="touchscreen|keyboard|keyboardHidden|orientation|screenLayout|screenSize"
android:theme="@style/TextSecure.DialogActivity" />
<activity android:name="org.thoughtcrime.securesms.SmsSendtoActivity"> <activity android:name="org.thoughtcrime.securesms.SmsSendtoActivity">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.SENDTO" /> <action android:name="android.intent.action.SENDTO" />

View File

@ -11,13 +11,11 @@ buildscript {
mavenLocal() mavenLocal()
google() google()
mavenCentral() mavenCentral()
maven { url 'https://maven.fabric.io/public' }
} }
dependencies { dependencies {
classpath "com.android.tools.build:gradle:$gradle_version" classpath "com.android.tools.build:gradle:$gradle_version"
classpath files('libs/gradle-witness.jar') classpath files('libs/gradle-witness.jar')
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "io.fabric.tools:gradle:1.+"
} }
} }
@ -25,7 +23,6 @@ apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android' apply plugin: 'kotlin-android'
apply plugin: 'witness' apply plugin: 'witness'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
repositories { repositories {
@ -62,7 +59,6 @@ repositories {
} }
google() google()
jcenter() jcenter()
maven { url 'https://maven.fabric.io/public' }
maven { url "https://jitpack.io" } maven { url "https://jitpack.io" }
} }
@ -91,16 +87,6 @@ dependencies {
implementation 'android.arch.lifecycle:extensions:1.1.1' implementation 'android.arch.lifecycle:extensions:1.1.1'
implementation 'android.arch.lifecycle:common-java8:1.1.1' implementation 'android.arch.lifecycle:common-java8:1.1.1'
implementation('com.google.firebase:firebase-messaging:17.3.4') {
exclude group: 'com.google.firebase', module: 'firebase-core'
exclude group: 'com.google.firebase', module: 'firebase-analytics'
exclude group: 'com.google.firebase', module: 'firebase-measurement-connector'
}
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-places:16.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.exoplayer:exoplayer-core:2.9.1' implementation 'com.google.android.exoplayer:exoplayer-core:2.9.1'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.9.1' implementation 'com.google.android.exoplayer:exoplayer-ui:2.9.1'
@ -186,7 +172,6 @@ dependencies {
// Remote: // Remote:
// implementation "com.github.loki-project:loki-messenger-android-service:dev-SNAPSHOT" // implementation "com.github.loki-project:loki-messenger-android-service:dev-SNAPSHOT"
implementation "com.google.protobuf:protobuf-java:2.5.0" implementation "com.google.protobuf:protobuf-java:2.5.0"
implementation "com.googlecode.libphonenumber:libphonenumber:8.10.7"
implementation "com.fasterxml.jackson.core:jackson-databind:2.9.8" implementation "com.fasterxml.jackson.core:jackson-databind:2.9.8"
implementation "com.squareup.okhttp3:okhttp:3.12.1" implementation "com.squareup.okhttp3:okhttp:3.12.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
@ -279,8 +264,6 @@ android {
debug { debug {
minifyEnabled true minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-firebase-messaging.pro',
'proguard-google-play-services.pro',
'proguard-dagger.pro', 'proguard-dagger.pro',
'proguard-jackson.pro', 'proguard-jackson.pro',
'proguard-sqlite.pro', 'proguard-sqlite.pro',
@ -371,12 +354,12 @@ android {
def assembleWebsiteDescriptor = { variant, file -> def assembleWebsiteDescriptor = { variant, file ->
if (file.exists()) { if (file.exists()) {
MessageDigest md = MessageDigest.getInstance("SHA-256"); MessageDigest md = MessageDigest.getInstance("SHA-256")
file.eachByte 4096, {bytes, size -> file.eachByte 4096, {bytes, size ->
md.update(bytes, 0, size); md.update(bytes, 0, size)
} }
String digest = md.digest().collect {String.format "%02x", it}.join(); String digest = md.digest().collect {String.format "%02x", it}.join()
String url = variant.productFlavors.get(0).ext.websiteUpdateUrl String url = variant.productFlavors.get(0).ext.websiteUpdateUrl
String apkName = file.getName() String apkName = file.getName()

View File

@ -1 +0,0 @@
-dontwarn com.google.firebase.analytics.connector.AnalyticsConnector

View File

@ -1,19 +0,0 @@
## Google Play Services 4.3.23 specific rules ##
## https://developer.android.com/google/play-services/setup.html#Proguard ##
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents();
}
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL;
}
-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
@com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}

View File

@ -5,11 +5,13 @@
<FrameLayout android:layout_width="match_parent" <FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:layout_weight="1"> android:layout_weight="1">
<!--
<com.google.android.gms.maps.MapView <com.google.android.gms.maps.MapView
android:id="@+id/map_view" android:id="@+id/map_view"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:visibility="gone"/> android:visibility="gone"/>
-->
<ImageView android:id="@+id/image_view" <ImageView android:id="@+id/image_view"
android:layout_width="match_parent" android:layout_width="match_parent"

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="google_app_id" translatable="false">1:312334754206:android:a9297b152879f266</string>
<string name="gcm_defaultSenderId" translatable="false">312334754206</string>
<string name="default_web_client_id" translatable="false">312334754206-dg1p1mtekis8ivja3ica50vonmrlunh4.apps.googleusercontent.com</string>
<string name="firebase_database_url" translatable="false">https://api-project-312334754206.firebaseio.com</string>
<string name="google_api_key" translatable="false">AIzaSyDrfzNAPBPzX6key51hqo3p5LZXF5Y-yxU</string>
<string name="google_crash_reporting_api_key" translatable="false">AIzaSyDrfzNAPBPzX6key51hqo3p5LZXF5Y-yxU</string>
<string name="project_id" translatable="false">api-project-312334754206</string>
</resources>

View File

@ -16,7 +16,6 @@
*/ */
package org.thoughtcrime.securesms; package org.thoughtcrime.securesms;
import android.annotation.SuppressLint;
import android.arch.lifecycle.DefaultLifecycleObserver; import android.arch.lifecycle.DefaultLifecycleObserver;
import android.arch.lifecycle.LifecycleOwner; import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.ProcessLifecycleOwner; import android.arch.lifecycle.ProcessLifecycleOwner;
@ -31,8 +30,6 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.multidex.MultiDexApplication; import android.support.multidex.MultiDexApplication;
import com.google.android.gms.security.ProviderInstaller;
import org.conscrypt.Conscrypt; import org.conscrypt.Conscrypt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.signal.aesgcmprovider.AesGcmProvider; import org.signal.aesgcmprovider.AesGcmProvider;
@ -176,7 +173,6 @@ public class ApplicationContext extends MultiDexApplication implements Dependenc
initializeTypingStatusSender(); initializeTypingStatusSender();
initializeSignedPreKeyCheck(); initializeSignedPreKeyCheck();
initializePeriodicTasks(); initializePeriodicTasks();
initializeCircumvention();
initializeWebRtc(); initializeWebRtc();
initializePendingMessages(); initializePendingMessages();
initializeUnidentifiedDeliveryAbilityRefresh(); initializeUnidentifiedDeliveryAbilityRefresh();
@ -403,25 +399,6 @@ public class ApplicationContext extends MultiDexApplication implements Dependenc
} }
} }
@SuppressLint("StaticFieldLeak")
private void initializeCircumvention() {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
if (new SignalServiceNetworkAccess(ApplicationContext.this).isCensored(ApplicationContext.this)) {
try {
ProviderInstaller.installIfNeeded(ApplicationContext.this);
} catch (Throwable t) {
Log.w(TAG, t);
}
}
return null;
}
};
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void executePendingContactSync() { private void executePendingContactSync() {
if (TextSecurePreferences.needsFullContactSync(this)) { if (TextSecurePreferences.needsFullContactSync(this)) {
ApplicationContext.getInstance(this).getJobManager().add(new MultiDeviceContactUpdateJob(this, true)); ApplicationContext.getInstance(this).getJobManager().add(new MultiDeviceContactUpdateJob(this, true));

View File

@ -1,30 +0,0 @@
/**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class PlayServicesProblemActivity extends FragmentActivity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
PlayServicesProblemFragment fragment = new PlayServicesProblemFragment();
fragment.show(getSupportFragmentManager(), "dialog");
}
}

View File

@ -1,67 +0,0 @@
/**
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import com.google.android.gms.common.GoogleApiAvailability;
import network.loki.messenger.R;
public class PlayServicesProblemFragment extends DialogFragment {
@Override
public @NonNull Dialog onCreateDialog(@Nullable Bundle bundle) {
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getActivity());
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), code, 9111);
if (dialog == null) {
return new AlertDialog.Builder(requireActivity())
.setNegativeButton(android.R.string.ok, null)
.setMessage(R.string.PlayServicesProblemFragment_the_version_of_google_play_services_you_have_installed_is_not_functioning)
.create();
} else {
return dialog;
}
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
finish();
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
finish();
}
private void finish() {
Activity activity = getActivity();
if (activity != null) activity.finish();
}
}

View File

@ -3,10 +3,8 @@ package org.thoughtcrime.securesms;
import android.Manifest; import android.Manifest;
import android.animation.Animator; import android.animation.Animator;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
@ -29,17 +27,6 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.dd.CircularProgressButton; import com.dd.CircularProgressButton;
import com.google.android.gms.auth.api.phone.SmsRetriever;
import com.google.android.gms.auth.api.phone.SmsRetrieverClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.Task;
import com.google.i18n.phonenumbers.AsYouTypeFormatter;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabase;
@ -72,12 +59,9 @@ import org.thoughtcrime.securesms.push.AccountManagerFactory;
import org.thoughtcrime.securesms.registration.CaptchaActivity; import org.thoughtcrime.securesms.registration.CaptchaActivity;
import org.thoughtcrime.securesms.service.DirectoryRefreshListener; import org.thoughtcrime.securesms.service.DirectoryRefreshListener;
import org.thoughtcrime.securesms.service.RotateSignedPreKeyListener; import org.thoughtcrime.securesms.service.RotateSignedPreKeyListener;
import org.thoughtcrime.securesms.service.VerificationCodeParser;
import org.thoughtcrime.securesms.util.BackupUtil; import org.thoughtcrime.securesms.util.BackupUtil;
import org.thoughtcrime.securesms.util.DateUtils; import org.thoughtcrime.securesms.util.DateUtils;
import org.thoughtcrime.securesms.util.Dialogs; import org.thoughtcrime.securesms.util.Dialogs;
import org.thoughtcrime.securesms.util.PlayServicesUtil;
import org.thoughtcrime.securesms.util.PlayServicesUtil.PlayServicesStatus;
import org.thoughtcrime.securesms.util.ServiceUtil; import org.thoughtcrime.securesms.util.ServiceUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util; import org.thoughtcrime.securesms.util.Util;
@ -120,7 +104,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
private static final String TAG = RegistrationActivity.class.getSimpleName(); private static final String TAG = RegistrationActivity.class.getSimpleName();
private AsYouTypeFormatter countryFormatter;
private ArrayAdapter<String> countrySpinnerAdapter; private ArrayAdapter<String> countrySpinnerAdapter;
private Spinner countrySpinner; private Spinner countrySpinner;
private LabeledEditText countryCode; private LabeledEditText countryCode;
@ -148,7 +131,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
private VerificationPinKeyboard keyboard; private VerificationPinKeyboard keyboard;
private VerificationCodeView verificationCodeView; private VerificationCodeView verificationCodeView;
private RegistrationState registrationState; private RegistrationState registrationState;
private SmsRetrieverReceiver smsRetrieverReceiver;
private SignalServiceAccountManager accountManager; private SignalServiceAccountManager accountManager;
private int debugTapCounter; private int debugTapCounter;
@ -162,13 +144,11 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
initializeSpinner(); initializeSpinner();
initializeNumber(); initializeNumber();
initializeBackupDetection(); initializeBackupDetection();
initializeChallengeListener();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy(); super.onDestroy();
shutdownChallengeListener();
markAsVerifying(false); markAsVerifying(false);
EventBus.getDefault().unregister(this); EventBus.getDefault().unregister(this);
} }
@ -178,7 +158,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
if (requestCode == PICK_COUNTRY && resultCode == RESULT_OK && data != null) { if (requestCode == PICK_COUNTRY && resultCode == RESULT_OK && data != null) {
this.countryCode.setText(String.valueOf(data.getIntExtra("country_code", 1))); this.countryCode.setText(String.valueOf(data.getIntExtra("country_code", 1)));
setCountryDisplay(data.getStringExtra("country_name")); setCountryDisplay(data.getStringExtra("country_name"));
setCountryFormatter(data.getIntExtra("country_code", 1));
} else if (requestCode == CAPTCHA && resultCode == RESULT_OK && data != null) { } else if (requestCode == CAPTCHA && resultCode == RESULT_OK && data != null) {
registrationState = new RegistrationState(Optional.fromNullable(data.getStringExtra(CaptchaActivity.KEY_TOKEN)), registrationState); registrationState = new RegistrationState(Optional.fromNullable(data.getStringExtra(CaptchaActivity.KEY_TOKEN)), registrationState);
@ -285,24 +264,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
}); });
} }
@SuppressLint("MissingPermission")
private void initializeNumber() { private void initializeNumber() {
Optional<Phonenumber.PhoneNumber> localNumber = Optional.absent();
if (Permissions.hasAll(this, Manifest.permission.READ_PHONE_STATE)) {
localNumber = Util.getDeviceNumber(this);
}
if (localNumber.isPresent()) {
this.countryCode.setText(String.valueOf(localNumber.get().getCountryCode()));
this.number.setText(String.valueOf(localNumber.get().getNationalNumber()));
} else {
Optional<String> simCountryIso = Util.getSimCountryIso(this);
if (simCountryIso.isPresent() && !TextUtils.isEmpty(simCountryIso.get())) {
this.countryCode.setText(String.valueOf(PhoneNumberUtil.getInstance().getCountryCodeForRegion(simCountryIso.get())));
}
}
} }
@SuppressLint("StaticFieldLeak") @SuppressLint("StaticFieldLeak")
@ -337,14 +299,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
this.countrySpinnerAdapter.add(value); this.countrySpinnerAdapter.add(value);
} }
private void setCountryFormatter(int countryCode) {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
String regionCode = util.getRegionCodeForCountryCode(countryCode);
if (regionCode == null) this.countryFormatter = null;
else this.countryFormatter = util.getAsYouTypeFormatter(regionCode);
}
private String getConfiguredE164Number() { private String getConfiguredE164Number() {
return PhoneNumberFormatter.formatE164(countryCode.getText().toString(), return PhoneNumberFormatter.formatE164(countryCode.getText().toString(),
number.getText().toString()); number.getText().toString());
@ -435,20 +389,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
Dialogs.showAlertDialog(this, Dialogs.showAlertDialog(this,
getString(R.string.RegistrationActivity_invalid_number), getString(R.string.RegistrationActivity_invalid_number),
String.format(getString(R.string.RegistrationActivity_the_number_you_specified_s_is_invalid), e164number)); String.format(getString(R.string.RegistrationActivity_the_number_you_specified_s_is_invalid), e164number));
return;
}
PlayServicesStatus gcmStatus = PlayServicesUtil.getPlayServicesStatus(this);
if (gcmStatus == PlayServicesStatus.SUCCESS) {
handleRequestVerification(e164number, true);
} else if (gcmStatus == PlayServicesStatus.MISSING) {
handlePromptForNoPlayServices(e164number);
} else if (gcmStatus == PlayServicesStatus.NEEDS_UPDATE) {
GoogleApiAvailability.getInstance().getErrorDialog(this, ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED, 0).show();
} else {
Dialogs.showAlertDialog(this, getString(R.string.RegistrationActivity_play_services_error),
getString(R.string.RegistrationActivity_google_play_services_is_updating_or_unavailable));
} }
} }
@ -456,23 +396,8 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
createButton.setIndeterminateProgressMode(true); createButton.setIndeterminateProgressMode(true);
createButton.setProgress(50); createButton.setProgress(50);
if (gcmSupported) {
SmsRetrieverClient client = SmsRetriever.getClient(this);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(none -> {
Log.i(TAG, "Successfully registered SMS listener.");
requestVerificationCode(e164number, true, true);
});
task.addOnFailureListener(e -> {
Log.w(TAG, "Failed to register SMS listener.", e);
requestVerificationCode(e164number, true, false);
});
} else {
requestVerificationCode(e164number, false, false); requestVerificationCode(e164number, false, false);
} }
}
@SuppressLint("StaticFieldLeak") @SuppressLint("StaticFieldLeak")
private void requestVerificationCode(@NonNull String e164number, boolean gcmSupported, boolean smsRetrieverSupported) { private void requestVerificationCode(@NonNull String e164number, boolean gcmSupported, boolean smsRetrieverSupported) {
@ -932,19 +857,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
dialog.show(); dialog.show();
} }
private void initializeChallengeListener() {
smsRetrieverReceiver = new SmsRetrieverReceiver();
IntentFilter filter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
registerReceiver(smsRetrieverReceiver, filter);
}
private void shutdownChallengeListener() {
if (smsRetrieverReceiver != null) {
unregisterReceiver(smsRetrieverReceiver);
smsRetrieverReceiver = null;
}
}
private void markAsVerifying(boolean verifying) { private void markAsVerifying(boolean verifying) {
TextSecurePreferences.setVerifying(this, verifying); TextSecurePreferences.setVerifying(this, verifying);
@ -954,13 +866,8 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
} }
private String formatNumber(@NonNull String e164Number) { private String formatNumber(@NonNull String e164Number) {
try {
Phonenumber.PhoneNumber number = PhoneNumberUtil.getInstance().parse(e164Number, null);
return PhoneNumberUtil.getInstance().format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
} catch (NumberParseException e) {
return e164Number; return e164Number;
} }
}
private void onWrongNumberClicked() { private void onWrongNumberClicked() {
displayInitialView(false); displayInitialView(false);
@ -973,53 +880,16 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
else restoreBackupProgress.setText(getString(R.string.RegistrationActivity_d_messages_so_far, event.getCount())); else restoreBackupProgress.setText(getString(R.string.RegistrationActivity_d_messages_so_far, event.getCount()));
} }
private class SmsRetrieverReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "SmsRetrieverReceiver received a broadcast...");
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
Optional<String> code = VerificationCodeParser.parse(context, (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE));
if (code.isPresent()) {
Log.i(TAG, "Received verification code.");
handleVerificationCodeReceived(code.get());
} else {
Log.w(TAG, "Could not parse verification code.");
}
break;
case CommonStatusCodes.TIMEOUT:
Log.w(TAG, "Hit a timeout waiting for the SMS to arrive.");
break;
}
} else {
Log.w(TAG, "SmsRetrieverReceiver received the wrong action?");
}
}
}
private class CountryCodeChangedListener implements TextWatcher { private class CountryCodeChangedListener implements TextWatcher {
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s) || !TextUtils.isDigitsOnly(s)) { if (TextUtils.isEmpty(s) || !TextUtils.isDigitsOnly(s)) {
setCountryDisplay(getString(R.string.RegistrationActivity_select_your_country)); setCountryDisplay(getString(R.string.RegistrationActivity_select_your_country));
countryFormatter = null;
return; return;
} }
int countryCode = Integer.parseInt(s.toString()); int countryCode = Integer.parseInt(s.toString());
String regionCode = PhoneNumberUtil.getInstance().getRegionCodeForCountryCode(countryCode); setCountryDisplay("N/A");
setCountryFormatter(countryCode);
setCountryDisplay(PhoneNumberFormatter.getRegionDisplayName(regionCode));
if (!TextUtils.isEmpty(regionCode) && !regionCode.equals("ZZ")) {
number.requestFocus();
}
} }
@Override @Override
@ -1035,24 +905,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements Verif
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
if (countryFormatter == null)
return;
if (TextUtils.isEmpty(s))
return;
countryFormatter.clear();
String number = s.toString().replaceAll("[^\\d.]", "");
String formattedNumber = null;
for (int i=0;i<number.length();i++) {
formattedNumber = countryFormatter.inputDigit(number.charAt(i));
}
if (formattedNumber != null && !s.toString().equals(formattedNumber)) {
s.replace(0, s.length(), formattedNumber);
}
} }
@Override @Override

View File

@ -7,26 +7,18 @@ import android.os.Build;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.MarkerOptions;
import network.loki.messenger.R;
import org.thoughtcrime.securesms.util.ViewUtil; import org.thoughtcrime.securesms.util.ViewUtil;
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture; import org.thoughtcrime.securesms.util.concurrent.ListenableFuture;
import org.thoughtcrime.securesms.util.concurrent.SettableFuture; import org.thoughtcrime.securesms.util.concurrent.SettableFuture;
import network.loki.messenger.R;
public class SignalMapView extends LinearLayout { public class SignalMapView extends LinearLayout {
private MapView mapView;
private ImageView imageView; private ImageView imageView;
private TextView textView; private TextView textView;
@ -49,7 +41,6 @@ public class SignalMapView extends LinearLayout {
setOrientation(LinearLayout.VERTICAL); setOrientation(LinearLayout.VERTICAL);
LayoutInflater.from(context).inflate(R.layout.signal_map_view, this, true); LayoutInflater.from(context).inflate(R.layout.signal_map_view, this, true);
this.mapView = ViewUtil.findById(this, R.id.map_view);
this.imageView = ViewUtil.findById(this, R.id.image_view); this.imageView = ViewUtil.findById(this, R.id.image_view);
this.textView = ViewUtil.findById(this, R.id.address_view); this.textView = ViewUtil.findById(this, R.id.address_view);
} }
@ -57,39 +48,8 @@ public class SignalMapView extends LinearLayout {
public ListenableFuture<Bitmap> display(final SignalPlace place) { public ListenableFuture<Bitmap> display(final SignalPlace place) {
final SettableFuture<Bitmap> future = new SettableFuture<>(); final SettableFuture<Bitmap> future = new SettableFuture<>();
this.mapView.onCreate(null);
this.mapView.onResume();
this.mapView.setVisibility(View.VISIBLE);
this.imageView.setVisibility(View.GONE); this.imageView.setVisibility(View.GONE);
this.mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final GoogleMap googleMap) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLong(), 13));
googleMap.addMarker(new MarkerOptions().position(place.getLatLong()));
googleMap.setBuildingsEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setAllGesturesEnabled(false);
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
googleMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
@Override
public void onSnapshotReady(Bitmap bitmap) {
future.set(bitmap);
imageView.setImageBitmap(bitmap);
imageView.setVisibility(View.VISIBLE);
mapView.setVisibility(View.GONE);
mapView.onPause();
mapView.onDestroy();
}
});
}
});
}
});
this.textView.setText(place.getDescription()); this.textView.setText(place.getDescription());
return future; return future;

View File

@ -7,8 +7,6 @@ import android.text.TextUtils;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.maps.model.LatLng;
import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.util.JsonUtils; import org.thoughtcrime.securesms.util.JsonUtils;
@ -17,6 +15,22 @@ import java.io.IOException;
public class SignalPlace { public class SignalPlace {
/* Loki - Temporary Placeholders */
class LatLng {
double latitude;
double longitude;
LatLng(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
}
class Place {
public CharSequence getName() { return ""; }
public CharSequence getAddress() { return ""; }
LatLng getLatLng() { return new LatLng(0, 0); }
}
private static final String URL = "https://maps.google.com/maps"; private static final String URL = "https://maps.google.com/maps";
private static final String TAG = SignalPlace.class.getSimpleName(); private static final String TAG = SignalPlace.class.getSimpleName();

View File

@ -13,11 +13,7 @@ import android.support.v7.app.AlertDialog;
import android.text.TextUtils; import android.text.TextUtils;
import com.annimon.stream.Stream; import com.annimon.stream.Stream;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import network.loki.messenger.R;
import org.thoughtcrime.securesms.components.emoji.EmojiStrings; import org.thoughtcrime.securesms.components.emoji.EmojiStrings;
import org.thoughtcrime.securesms.contactshare.Contact.Email; import org.thoughtcrime.securesms.contactshare.Contact.Email;
import org.thoughtcrime.securesms.contactshare.Contact.Phone; import org.thoughtcrime.securesms.contactshare.Contact.Phone;
@ -34,6 +30,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import network.loki.messenger.R;
public final class ContactUtil { public final class ContactUtil {
private static final String TAG = ContactUtil.class.getSimpleName(); private static final String TAG = ContactUtil.class.getSimpleName();
@ -102,14 +100,8 @@ public final class ContactUtil {
} }
private static @NonNull String getPrettyPhoneNumber(@NonNull String phoneNumber, @NonNull Locale fallbackLocale) { private static @NonNull String getPrettyPhoneNumber(@NonNull String phoneNumber, @NonNull Locale fallbackLocale) {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
try {
PhoneNumber parsed = util.parse(phoneNumber, fallbackLocale.getISO3Country());
return util.format(parsed, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
} catch (NumberParseException e) {
return phoneNumber; return phoneNumber;
} }
}
public static @NonNull String getNormalizedPhoneNumber(@NonNull Context context, @NonNull String number) { public static @NonNull String getNormalizedPhoneNumber(@NonNull Context context, @NonNull String number) {
Address address = Address.fromExternal(context, number); Address address = Address.fromExternal(context, number);

View File

@ -77,7 +77,6 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.annimon.stream.Stream; import com.annimon.stream.Stream;
import com.google.android.gms.location.places.ui.PlacePicker;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
@ -133,7 +132,6 @@ import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.DraftDatabase; import org.thoughtcrime.securesms.database.DraftDatabase;
import org.thoughtcrime.securesms.database.DraftDatabase.Draft; import org.thoughtcrime.securesms.database.DraftDatabase.Draft;
import org.thoughtcrime.securesms.database.DraftDatabase.Drafts; import org.thoughtcrime.securesms.database.DraftDatabase.Drafts;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.database.IdentityDatabase;
import org.thoughtcrime.securesms.database.IdentityDatabase.IdentityRecord; import org.thoughtcrime.securesms.database.IdentityDatabase.IdentityRecord;
import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus; import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus;
@ -179,7 +177,6 @@ import org.thoughtcrime.securesms.mms.ImageSlide;
import org.thoughtcrime.securesms.mms.LocationSlide; import org.thoughtcrime.securesms.mms.LocationSlide;
import org.thoughtcrime.securesms.mms.MediaConstraints; import org.thoughtcrime.securesms.mms.MediaConstraints;
import org.thoughtcrime.securesms.mms.OutgoingExpirationUpdateMessage; import org.thoughtcrime.securesms.mms.OutgoingExpirationUpdateMessage;
import org.thoughtcrime.securesms.mms.OutgoingGroupMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage; import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage; import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage;
import org.thoughtcrime.securesms.mms.QuoteId; import org.thoughtcrime.securesms.mms.QuoteId;
@ -662,10 +659,12 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity
recipient.addListener(this); recipient.addListener(this);
fragment.reloadList(); fragment.reloadList();
break; break;
/*
case PICK_LOCATION: case PICK_LOCATION:
SignalPlace place = new SignalPlace(PlacePicker.getPlace(data, this)); SignalPlace place = new SignalPlace(PlacePicker.getPlace(data, this));
attachmentManager.setLocation(place, getCurrentMediaConstraints()); attachmentManager.setLocation(place, getCurrentMediaConstraints());
break; break;
*/
case PICK_GIF: case PICK_GIF:
setMedia(data.getData(), setMedia(data.getData(),
MediaType.GIF, MediaType.GIF,
@ -1240,15 +1239,13 @@ public class ConversationActivity extends PassphraseRequiredActionBarActivity
} }
private boolean handleDisplayQuickContact() { private boolean handleDisplayQuickContact() {
if (recipient.getAddress().isGroup()) return false; return !recipient.getAddress().isGroup();
// if (recipient.getContactUri() != null) { // if (recipient.getContactUri() != null) {
// ContactsContract.QuickContact.showQuickContact(ConversationActivity.this, titleView, recipient.getContactUri(), ContactsContract.QuickContact.MODE_LARGE, null); // ContactsContract.QuickContact.showQuickContact(ConversationActivity.this, titleView, recipient.getContactUri(), ContactsContract.QuickContact.MODE_LARGE, null);
// } else { // } else {
// handleAddToContacts(); // handleAddToContacts();
// } // }
return true;
} }
private void handleAddAttachment() { private void handleAddAttachment() {

View File

@ -10,12 +10,6 @@ import android.support.annotation.VisibleForTesting;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Pair; import android.util.Pair;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.ShortNumberInfo;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.util.DelimiterUtil; import org.thoughtcrime.securesms.util.DelimiterUtil;
import org.thoughtcrime.securesms.util.GroupUtil; import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.NumberUtil; import org.thoughtcrime.securesms.util.NumberUtil;
@ -200,19 +194,10 @@ public class Address implements Parcelable, Comparable<Address> {
private final Optional<PhoneNumber> localNumber; private final Optional<PhoneNumber> localNumber;
private final String localCountryCode; private final String localCountryCode;
private final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
private final Pattern ALPHA_PATTERN = Pattern.compile("[a-zA-Z]"); private final Pattern ALPHA_PATTERN = Pattern.compile("[a-zA-Z]");
ExternalAddressFormatter(@NonNull String localNumberString) { ExternalAddressFormatter(@NonNull String localNumberString) {
try { throw new AssertionError("Not Implemented");
Phonenumber.PhoneNumber libNumber = phoneNumberUtil.parse(localNumberString, null);
int countryCode = libNumber.getCountryCode();
this.localNumber = Optional.of(new PhoneNumber(localNumberString, countryCode, parseAreaCode(localNumberString, countryCode)));
this.localCountryCode = phoneNumberUtil.getRegionCodeForNumber(libNumber);
} catch (NumberParseException e) {
throw new AssertionError(e);
}
} }
ExternalAddressFormatter(@NonNull String localCountryCode, boolean countryCode) { ExternalAddressFormatter(@NonNull String localCountryCode, boolean countryCode) {
@ -222,61 +207,7 @@ public class Address implements Parcelable, Comparable<Address> {
public String format(@Nullable String number) { public String format(@Nullable String number) {
if (number == null) return "Unknown"; if (number == null) return "Unknown";
if (GroupUtil.isEncodedGroup(number)) return number; return number;
if (ALPHA_PATTERN.matcher(number).find()) return number.trim();
String bareNumber = number.replaceAll("[^0-9+]", "");
if (bareNumber.length() == 0) {
if (number.trim().length() == 0) return "Unknown";
else return number.trim();
}
// libphonenumber doesn't seem to be correct for Germany and Finland
if (bareNumber.length() <= 6 && ("DE".equals(localCountryCode) || "FI".equals(localCountryCode) || "SK".equals(localCountryCode))) {
return bareNumber;
}
// libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
return bareNumber;
}
if (isShortCode(bareNumber, localCountryCode)) {
return bareNumber;
}
String processedNumber = applyAreaCodeRules(localNumber, bareNumber);
try {
Phonenumber.PhoneNumber parsedNumber = phoneNumberUtil.parse(processedNumber, localCountryCode);
return phoneNumberUtil.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
} catch (NumberParseException e) {
Log.w(TAG, e);
if (bareNumber.charAt(0) == '+')
return bareNumber;
String localNumberImprecise = localNumber.isPresent() ? localNumber.get().getE164Number() : "";
if (localNumberImprecise.charAt(0) == '+')
localNumberImprecise = localNumberImprecise.substring(1);
if (localNumberImprecise.length() == bareNumber.length() || bareNumber.length() > localNumberImprecise.length())
return "+" + number;
int difference = localNumberImprecise.length() - bareNumber.length();
return "+" + localNumberImprecise.substring(0, difference) + bareNumber;
}
}
private boolean isShortCode(@NonNull String bareNumber, String localCountryCode) {
try {
Phonenumber.PhoneNumber parsedNumber = phoneNumberUtil.parse(bareNumber, localCountryCode);
return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(parsedNumber, localCountryCode);
} catch (NumberParseException e) {
return false;
}
} }
private @Nullable String parseAreaCode(@NonNull String e164Number, int countryCode) { private @Nullable String parseAreaCode(@NonNull String e164Number, int countryCode) {

View File

@ -1,24 +1,16 @@
package org.thoughtcrime.securesms.database.helpers; package org.thoughtcrime.securesms.database.helpers;
import android.Manifest;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.text.TextUtils; import android.text.TextUtils;
import org.thoughtcrime.securesms.logging.Log;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.ShortNumberInfo;
import org.thoughtcrime.securesms.DatabaseUpgradeActivity; import org.thoughtcrime.securesms.DatabaseUpgradeActivity;
import org.thoughtcrime.securesms.crypto.AttachmentSecret; import org.thoughtcrime.securesms.crypto.AttachmentSecret;
@ -26,7 +18,6 @@ import org.thoughtcrime.securesms.crypto.ClassicDecryptingPartInputStream;
import org.thoughtcrime.securesms.crypto.MasterCipher; import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.database.Address;
import org.thoughtcrime.securesms.database.AttachmentDatabase; import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.database.DraftDatabase; import org.thoughtcrime.securesms.database.DraftDatabase;
import org.thoughtcrime.securesms.database.GroupDatabase; import org.thoughtcrime.securesms.database.GroupDatabase;
@ -37,8 +28,8 @@ import org.thoughtcrime.securesms.database.PushDatabase;
import org.thoughtcrime.securesms.database.RecipientDatabase; import org.thoughtcrime.securesms.database.RecipientDatabase;
import org.thoughtcrime.securesms.database.SmsDatabase; import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.permissions.Permissions;
import org.thoughtcrime.securesms.util.Base64; import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.DelimiterUtil; import org.thoughtcrime.securesms.util.DelimiterUtil;
import org.thoughtcrime.securesms.util.Hex; import org.thoughtcrime.securesms.util.Hex;
@ -1385,71 +1376,18 @@ public class ClassicOpenHelper extends SQLiteOpenHelper {
add("AC"); add("AC");
}}; }};
private final Phonenumber.PhoneNumber localNumber;
private final String localNumberString; private final String localNumberString;
private final String localCountryCode;
private final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
private final Pattern ALPHA_PATTERN = Pattern.compile("[a-zA-Z]"); private final Pattern ALPHA_PATTERN = Pattern.compile("[a-zA-Z]");
public NumberMigrator(String localNumber) { public NumberMigrator(String localNumber) {
try {
this.localNumberString = localNumber; this.localNumberString = localNumber;
this.localNumber = phoneNumberUtil.parse(localNumber, null);
this.localCountryCode = phoneNumberUtil.getRegionCodeForNumber(this.localNumber);
} catch (NumberParseException e) {
throw new AssertionError(e);
}
} }
public String migrate(@Nullable String number) { public String migrate(@Nullable String number) {
if (number == null) return "Unknown"; if (number == null) return "Unknown";
if (number.startsWith("__textsecure_group__!")) return number; return number;
if (ALPHA_PATTERN.matcher(number).find()) return number.trim();
String bareNumber = number.replaceAll("[^0-9+]", "");
if (bareNumber.length() == 0) {
if (TextUtils.isEmpty(number.trim())) return "Unknown";
else return number.trim();
}
// libphonenumber doesn't seem to be correct for Germany and Finland
if (bareNumber.length() <= 6 && ("DE".equals(localCountryCode) || "FI".equals(localCountryCode) || "SK".equals(localCountryCode))) {
return bareNumber;
}
// libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
return bareNumber;
}
try {
Phonenumber.PhoneNumber parsedNumber = phoneNumberUtil.parse(bareNumber, localCountryCode);
if (ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(parsedNumber, localCountryCode)) {
return bareNumber;
}
return phoneNumberUtil.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
} catch (NumberParseException e) {
Log.w(TAG, e);
if (bareNumber.charAt(0) == '+')
return bareNumber;
String localNumberImprecise = localNumberString;
if (localNumberImprecise.charAt(0) == '+')
localNumberImprecise = localNumberImprecise.substring(1);
if (localNumberImprecise.length() == bareNumber.length() || bareNumber.length() > localNumberImprecise.length())
return "+" + number;
int difference = localNumberImprecise.length() - bareNumber.length();
return "+" + localNumberImprecise.substring(0, difference) + bareNumber;
}
} }
} }

View File

@ -1,19 +1,12 @@
package org.thoughtcrime.securesms.database.loaders; package org.thoughtcrime.securesms.database.loaders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import android.content.Context; import android.content.Context;
import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.AsyncTaskLoader;
import java.util.ArrayList;
import com.google.i18n.phonenumbers.PhoneNumberUtil; import java.util.Comparator;
import org.whispersystems.signalservice.api.util.PhoneNumberFormatter; import java.util.Map;
public class CountryListLoader extends AsyncTaskLoader<ArrayList<Map<String, String>>> { public class CountryListLoader extends AsyncTaskLoader<ArrayList<Map<String, String>>> {
@ -23,19 +16,7 @@ public class CountryListLoader extends AsyncTaskLoader<ArrayList<Map<String, Str
@Override @Override
public ArrayList<Map<String, String>> loadInBackground() { public ArrayList<Map<String, String>> loadInBackground() {
Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions(); return new ArrayList<>();
ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
for (String region : regions) {
Map<String, String> data = new HashMap<String, String>(2);
data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
data.put("country_code", "+" +PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
results.add(data);
}
Collections.sort(results, new RegionComparator());
return results;
} }
private static class RegionComparator implements Comparator<Map<String, String>> { private static class RegionComparator implements Comparator<Map<String, String>> {

View File

@ -33,20 +33,12 @@ import android.provider.OpenableColumns;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.text.TextUtils; import android.text.TextUtils;
import org.thoughtcrime.securesms.TransportOption;
import org.thoughtcrime.securesms.mediasend.MediaSendActivity;
import org.thoughtcrime.securesms.logging.Log;
import android.util.Pair; import android.util.Pair;
import android.view.View; import android.view.View;
import android.widget.Toast; import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.ui.PlacePicker;
import org.thoughtcrime.securesms.MediaPreviewActivity; import org.thoughtcrime.securesms.MediaPreviewActivity;
import network.loki.messenger.R; import org.thoughtcrime.securesms.TransportOption;
import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.components.AudioView; import org.thoughtcrime.securesms.components.AudioView;
import org.thoughtcrime.securesms.components.DocumentView; import org.thoughtcrime.securesms.components.DocumentView;
@ -55,6 +47,8 @@ import org.thoughtcrime.securesms.components.ThumbnailView;
import org.thoughtcrime.securesms.components.location.SignalMapView; import org.thoughtcrime.securesms.components.location.SignalMapView;
import org.thoughtcrime.securesms.components.location.SignalPlace; import org.thoughtcrime.securesms.components.location.SignalPlace;
import org.thoughtcrime.securesms.giph.ui.GiphyActivity; import org.thoughtcrime.securesms.giph.ui.GiphyActivity;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.mediasend.MediaSendActivity;
import org.thoughtcrime.securesms.permissions.Permissions; import org.thoughtcrime.securesms.permissions.Permissions;
import org.thoughtcrime.securesms.providers.BlobProvider; import org.thoughtcrime.securesms.providers.BlobProvider;
import org.thoughtcrime.securesms.providers.DeprecatedPersistentBlobProvider; import org.thoughtcrime.securesms.providers.DeprecatedPersistentBlobProvider;
@ -77,6 +71,8 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import network.loki.messenger.R;
public class AttachmentManager { public class AttachmentManager {

View File

@ -14,17 +14,14 @@ import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.Preference; import android.support.v7.preference.Preference;
import org.thoughtcrime.securesms.logging.Log;
import android.widget.Toast; import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.ApplicationPreferencesActivity;
import org.thoughtcrime.securesms.LogSubmitActivity; import org.thoughtcrime.securesms.LogSubmitActivity;
import network.loki.messenger.R;
import org.thoughtcrime.securesms.RegistrationActivity; import org.thoughtcrime.securesms.RegistrationActivity;
import org.thoughtcrime.securesms.contacts.ContactAccessor; import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.contacts.ContactIdentityManager; import org.thoughtcrime.securesms.contacts.ContactIdentityManager;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.push.AccountManagerFactory; import org.thoughtcrime.securesms.push.AccountManagerFactory;
import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.task.ProgressDialogAsyncTask; import org.thoughtcrime.securesms.util.task.ProgressDialogAsyncTask;
@ -34,6 +31,8 @@ import org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedE
import java.io.IOException; import java.io.IOException;
import network.loki.messenger.R;
public class AdvancedPreferenceFragment extends CorrectedPreferenceFragment { public class AdvancedPreferenceFragment extends CorrectedPreferenceFragment {
private static final String TAG = AdvancedPreferenceFragment.class.getSimpleName(); private static final String TAG = AdvancedPreferenceFragment.class.getSimpleName();
@ -187,15 +186,11 @@ public class AdvancedPreferenceFragment extends CorrectedPreferenceFragment {
SignalServiceAccountManager accountManager = AccountManagerFactory.createManager(context); SignalServiceAccountManager accountManager = AccountManagerFactory.createManager(context);
try { try {
accountManager.setGcmId(Optional.<String>absent()); accountManager.setGcmId(Optional.absent());
} catch (AuthorizationFailedException e) { } catch (AuthorizationFailedException e) {
Log.w(TAG, e); Log.w(TAG, e);
} }
if (!TextSecurePreferences.isFcmDisabled(context)) {
FirebaseInstanceId.getInstance().deleteInstanceId();
}
return SUCCESS; return SUCCESS;
} catch (IOException ioe) { } catch (IOException ioe) {
Log.w(TAG, ioe); Log.w(TAG, ioe);

View File

@ -1,15 +1,12 @@
package org.thoughtcrime.securesms.push; package org.thoughtcrime.securesms.push;
import android.content.Context; import android.content.Context;
import android.os.AsyncTask;
import org.thoughtcrime.securesms.logging.Log;
import com.google.android.gms.security.ProviderInstaller;
import network.loki.messenger.BuildConfig;
import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.signalservice.api.SignalServiceAccountManager; import org.whispersystems.signalservice.api.SignalServiceAccountManager;
import network.loki.messenger.BuildConfig;
public class AccountManagerFactory { public class AccountManagerFactory {
private static final String TAG = AccountManagerFactory.class.getSimpleName(); private static final String TAG = AccountManagerFactory.class.getSimpleName();
@ -22,20 +19,6 @@ public class AccountManagerFactory {
} }
public static SignalServiceAccountManager createManager(final Context context, String number, String password) { public static SignalServiceAccountManager createManager(final Context context, String number, String password) {
if (new SignalServiceNetworkAccess(context).isCensored(number)) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
ProviderInstaller.installIfNeeded(context);
} catch (Throwable t) {
Log.w(TAG, t);
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
return new SignalServiceAccountManager(new SignalServiceNetworkAccess(context).getConfiguration(number), return new SignalServiceAccountManager(new SignalServiceNetworkAccess(context).getConfiguration(number),
number, password, BuildConfig.USER_AGENT); number, password, BuildConfig.USER_AGENT);
} }

View File

@ -6,7 +6,6 @@ import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread; import android.support.annotation.WorkerThread;
import com.annimon.stream.Stream; import com.annimon.stream.Stream;
import com.google.android.gms.common.util.Hex;
import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.DatabaseFactory;
@ -15,6 +14,7 @@ import org.thoughtcrime.securesms.database.model.StickerPackRecord;
import org.thoughtcrime.securesms.database.model.StickerRecord; import org.thoughtcrime.securesms.database.model.StickerRecord;
import org.thoughtcrime.securesms.dependencies.InjectableType; import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.util.Hex;
import org.thoughtcrime.securesms.util.concurrent.SignalExecutors; import org.thoughtcrime.securesms.util.concurrent.SignalExecutors;
import org.whispersystems.libsignal.InvalidMessageException; import org.whispersystems.libsignal.InvalidMessageException;
import org.whispersystems.libsignal.util.guava.Optional; import org.whispersystems.libsignal.util.guava.Optional;
@ -81,8 +81,8 @@ public final class StickerPackPreviewRepository implements InjectableType {
@WorkerThread @WorkerThread
private Optional<StickerManifestResult> getManifestRemote(@NonNull String packId, @NonNull String packKey) { private Optional<StickerManifestResult> getManifestRemote(@NonNull String packId, @NonNull String packKey) {
try { try {
byte[] packIdBytes = Hex.stringToBytes(packId); byte[] packIdBytes = Hex.fromStringCondensed(packId);
byte[] packKeyBytes = Hex.stringToBytes(packKey); byte[] packKeyBytes = Hex.fromStringCondensed(packKey);
SignalServiceStickerManifest remoteManifest = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes); SignalServiceStickerManifest remoteManifest = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes);
StickerManifest localManifest = new StickerManifest(packId, StickerManifest localManifest = new StickerManifest(packId,
packKey, packKey,

View File

@ -5,9 +5,9 @@ import android.support.annotation.NonNull;
import com.bumptech.glide.Priority; import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.data.DataFetcher;
import com.google.android.gms.common.util.Hex;
import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.util.Hex;
import org.whispersystems.libsignal.InvalidMessageException; import org.whispersystems.libsignal.InvalidMessageException;
import org.whispersystems.signalservice.api.SignalServiceMessageReceiver; import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
@ -32,8 +32,8 @@ public final class StickerRemoteUriFetcher implements DataFetcher<InputStream> {
@Override @Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) { public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
try { try {
byte[] packIdBytes = Hex.stringToBytes(stickerUri.getPackId()); byte[] packIdBytes = Hex.fromStringCondensed(stickerUri.getPackId());
byte[] packKeyBytes = Hex.stringToBytes(stickerUri.getPackKey()); byte[] packKeyBytes = Hex.fromStringCondensed(stickerUri.getPackKey());
InputStream stream = receiver.retrieveSticker(packIdBytes, packKeyBytes, stickerUri.getStickerId()); InputStream stream = receiver.retrieveSticker(packIdBytes, packKeyBytes, stickerUri.getStickerId());
callback.onDataReady(stream); callback.onDataReady(stream);

View File

@ -1,61 +0,0 @@
package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import org.thoughtcrime.securesms.logging.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class PlayServicesUtil {
private static final String TAG = PlayServicesUtil.class.getSimpleName();
public enum PlayServicesStatus {
SUCCESS,
MISSING,
NEEDS_UPDATE,
TRANSIENT_ERROR
}
public static PlayServicesStatus getPlayServicesStatus(Context context) {
int gcmStatus = 0;
try {
gcmStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
} catch (Throwable t) {
Log.w(TAG, t);
return PlayServicesStatus.MISSING;
}
Log.i(TAG, "Play Services: " + gcmStatus);
switch (gcmStatus) {
case ConnectionResult.SUCCESS:
return PlayServicesStatus.SUCCESS;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
try {
ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo("com.google.android.gms", 0);
if (applicationInfo != null && !applicationInfo.enabled) {
return PlayServicesStatus.MISSING;
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
}
return PlayServicesStatus.NEEDS_UPDATE;
case ConnectionResult.SERVICE_DISABLED:
case ConnectionResult.SERVICE_MISSING:
case ConnectionResult.SERVICE_INVALID:
case ConnectionResult.API_UNAVAILABLE:
case ConnectionResult.SERVICE_MISSING_PERMISSION:
return PlayServicesStatus.MISSING;
default:
return PlayServicesStatus.TRANSIENT_ERROR;
}
}
}

View File

@ -2,13 +2,6 @@ package org.thoughtcrime.securesms.util;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.ShortNumberInfo;
import org.thoughtcrime.securesms.logging.Log;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@ -24,23 +17,7 @@ public class ShortCodeUtil {
}}; }};
public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) { public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) {
try {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null);
String localCountryCode = util.getRegionCodeForNumber(localNumberObject);
String bareNumber = number.replaceAll("[^0-9+]", "");
// libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
return true;
}
Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode);
return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode);
} catch (NumberParseException e) {
Log.w(TAG, e);
return false; return false;
} }
}
} }

View File

@ -32,20 +32,14 @@ import android.os.Looper;
import android.provider.Telephony; import android.provider.Telephony;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.StyleSpan; import android.text.style.StyleSpan;
import com.google.android.mms.pdu_alt.CharacterSets;
import com.google.android.mms.pdu_alt.EncodedStringValue; import com.google.android.mms.pdu_alt.EncodedStringValue;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import network.loki.messenger.BuildConfig;
import org.thoughtcrime.securesms.components.ComposeText; import org.thoughtcrime.securesms.components.ComposeText;
import org.thoughtcrime.securesms.database.Address; import org.thoughtcrime.securesms.database.Address;
import org.thoughtcrime.securesms.logging.Log; import org.thoughtcrime.securesms.logging.Log;
@ -58,7 +52,7 @@ import java.io.EOFException;
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.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.ArrayList; import java.util.ArrayList;
@ -73,6 +67,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import network.loki.messenger.BuildConfig;
public class Util { public class Util {
private static final String TAG = Util.class.getSimpleName(); private static final String TAG = Util.class.getSimpleName();
@ -170,27 +166,15 @@ public class Util {
} }
public static @NonNull String toIsoString(byte[] bytes) { public static @NonNull String toIsoString(byte[] bytes) {
try { return new String(bytes, StandardCharsets.ISO_8859_1);
return new String(bytes, CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("ISO_8859_1 must be supported!");
}
} }
public static byte[] toIsoBytes(String isoString) { public static byte[] toIsoBytes(String isoString) {
try { return isoString.getBytes(StandardCharsets.ISO_8859_1);
return isoString.getBytes(CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("ISO_8859_1 must be supported!");
}
} }
public static byte[] toUtf8Bytes(String utf8String) { public static byte[] toUtf8Bytes(String utf8String) {
try { return utf8String.getBytes(StandardCharsets.UTF_8);
return utf8String.getBytes(CharacterSets.MIMENAME_UTF_8);
} catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF_8 must be supported!");
}
} }
public static void wait(Object lock, long timeout) { public static void wait(Object lock, long timeout) {
@ -279,27 +263,6 @@ public class Util {
return total; return total;
} }
@RequiresPermission(anyOf = {
android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.READ_SMS,
android.Manifest.permission.READ_PHONE_NUMBERS
})
@SuppressLint("MissingPermission")
public static Optional<Phonenumber.PhoneNumber> getDeviceNumber(Context context) {
try {
final String localNumber = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
final Optional<String> countryIso = getSimCountryIso(context);
if (TextUtils.isEmpty(localNumber)) return Optional.absent();
if (!countryIso.isPresent()) return Optional.absent();
return Optional.fromNullable(PhoneNumberUtil.getInstance().parse(localNumber, countryIso.get()));
} catch (NumberParseException e) {
Log.w(TAG, e);
return Optional.absent();
}
}
public static Optional<String> getSimCountryIso(Context context) { public static Optional<String> getSimCountryIso(Context context) {
String simCountryIso = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getSimCountryIso(); String simCountryIso = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getSimCountryIso();
return Optional.fromNullable(simCountryIso != null ? simCountryIso.toUpperCase() : null); return Optional.fromNullable(simCountryIso != null ? simCountryIso.toUpperCase() : null);