repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/RefreshAttributesJob.java
package org.thoughtcrime.securesms.jobs; import android.content.Context; import android.util.Log; import org.thoughtcrime.redphone.signaling.RedPhoneAccountAttributes; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.securesms.dependencies.InjectableType; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.jobqueue.JobParameters; import org.whispersystems.jobqueue.requirements.NetworkRequirement; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.NetworkFailureException; import java.io.IOException; import javax.inject.Inject; public class RefreshAttributesJob extends ContextJob implements InjectableType { public static final long serialVersionUID = 1L; private static final String TAG = RefreshAttributesJob.class.getSimpleName(); @Inject transient TextSecureAccountManager textSecureAccountManager; @Inject transient RedPhoneAccountManager redPhoneAccountManager; public RefreshAttributesJob(Context context) { super(context, JobParameters.newBuilder() .withPersistence() .withRequirement(new NetworkRequirement(context)) .withWakeLock(true) .create()); } @Override public void onAdded() {} @Override public void onRun() throws IOException { String signalingKey = TextSecurePreferences.getSignalingKey(context); String gcmRegistrationId = TextSecurePreferences.getGcmRegistrationId(context); int registrationId = TextSecurePreferences.getLocalRegistrationId(context); String token = textSecureAccountManager.getAccountVerificationToken(); redPhoneAccountManager.createAccount(token, new RedPhoneAccountAttributes(signalingKey, gcmRegistrationId)); textSecureAccountManager.setAccountAttributes(signalingKey, registrationId, true); } @Override public boolean onShouldRetry(Exception e) { return e instanceof NetworkFailureException; } @Override public void onCanceled() { Log.w(TAG, "Failed to update account attributes!"); } }
2,213
35.295082
112
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/RefreshPreKeysJob.java
package org.thoughtcrime.securesms.jobs; import android.content.Context; import android.util.Log; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.dependencies.InjectableType; import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.jobqueue.JobParameters; import org.whispersystems.jobqueue.requirements.NetworkRequirement; import org.whispersystems.libaxolotl.IdentityKeyPair; import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException; import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException; import java.io.IOException; import java.util.List; import javax.inject.Inject; public class RefreshPreKeysJob extends MasterSecretJob implements InjectableType { private static final String TAG = RefreshPreKeysJob.class.getSimpleName(); private static final int PREKEY_MINIMUM = 10; @Inject transient TextSecureAccountManager accountManager; public RefreshPreKeysJob(Context context) { super(context, JobParameters.newBuilder() .withGroupId(RefreshPreKeysJob.class.getSimpleName()) .withRequirement(new NetworkRequirement(context)) .withRequirement(new MasterSecretRequirement(context)) .withRetryCount(5) .create()); } @Override public void onAdded() { } @Override public void onRun(MasterSecret masterSecret) throws IOException { if (!TextSecurePreferences.isPushRegistered(context)) return; int availableKeys = accountManager.getPreKeysCount(); if (availableKeys >= PREKEY_MINIMUM && TextSecurePreferences.isSignedPreKeyRegistered(context)) { Log.w(TAG, "Available keys sufficient: " + availableKeys); return; } List<PreKeyRecord> preKeyRecords = PreKeyUtil.generatePreKeys(context); PreKeyRecord lastResortKeyRecord = PreKeyUtil.generateLastResortKey(context); IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(context); SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, identityKey); Log.w(TAG, "Registering new prekeys..."); accountManager.setPreKeys(identityKey.getPublicKey(), lastResortKeyRecord, signedPreKeyRecord, preKeyRecords); TextSecurePreferences.setSignedPreKeyRegistered(context, true); ApplicationContext.getInstance(context) .getJobManager() .add(new CleanPreKeysJob(context)); } @Override public boolean onShouldRetryThrowable(Exception exception) { if (exception instanceof NonSuccessfulResponseCodeException) return false; if (exception instanceof PushNetworkException) return true; return false; } @Override public void onCanceled() { } }
3,337
36.088889
114
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/SendJob.java
package org.thoughtcrime.securesms.jobs; import android.content.Context; import android.support.annotation.NonNull; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.TextSecureExpiredException; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.AttachmentDatabase; import org.thoughtcrime.securesms.mms.MediaConstraints; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.jobqueue.JobParameters; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import ws.com.google.android.mms.MmsException; public abstract class SendJob extends MasterSecretJob { private final static String TAG = SendJob.class.getSimpleName(); public SendJob(Context context, JobParameters parameters) { super(context, parameters); } @Override public final void onRun(MasterSecret masterSecret) throws Exception { if (!Util.isBuildFresh()) { throw new TextSecureExpiredException(String.format("TextSecure expired (build %d, now %d)", BuildConfig.BUILD_TIMESTAMP, System.currentTimeMillis())); } onSend(masterSecret); } protected abstract void onSend(MasterSecret masterSecret) throws Exception; protected void markAttachmentsUploaded(long messageId, @NonNull List<Attachment> attachments) { AttachmentDatabase database = DatabaseFactory.getAttachmentDatabase(context); for (Attachment attachment : attachments) { database.markAttachmentUploaded(messageId, attachment); } } protected List<Attachment> scaleAttachments(@NonNull MasterSecret masterSecret, @NonNull MediaConstraints constraints, @NonNull List<Attachment> attachments) throws UndeliverableMessageException { AttachmentDatabase attachmentDatabase = DatabaseFactory.getAttachmentDatabase(context); List<Attachment> results = new LinkedList<>(); for (Attachment attachment : attachments) { try { if (constraints.isSatisfied(context, masterSecret, attachment)) { results.add(attachment); } else if (constraints.canResize(attachment)) { InputStream resized = constraints.getResizedMedia(context, masterSecret, attachment); results.add(attachmentDatabase.updateAttachmentData(masterSecret, attachment, resized)); } else { throw new UndeliverableMessageException("Size constraints could not be met!"); } } catch (IOException | MmsException e) { throw new UndeliverableMessageException(e); } } return results; } }
3,009
37.101266
98
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/SmsReceiveJob.java
package org.thoughtcrime.securesms.jobs; import android.content.Context; import android.telephony.SmsMessage; import android.util.Log; import android.util.Pair; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUnion; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.sms.IncomingTextMessage; import org.whispersystems.jobqueue.JobParameters; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.LinkedList; import java.util.List; public class SmsReceiveJob extends ContextJob { private static final String TAG = SmsReceiveJob.class.getSimpleName(); private final Object[] pdus; public SmsReceiveJob(Context context, Object[] pdus) { super(context, JobParameters.newBuilder() .withPersistence() .withWakeLock(true) .create()); this.pdus = pdus; } @Override public void onAdded() {} @Override public void onRun() { Optional<IncomingTextMessage> message = assembleMessageFragments(pdus); MasterSecret masterSecret = KeyCachingService.getMasterSecret(context); MasterSecretUnion masterSecretUnion; if (masterSecret == null) { masterSecretUnion = new MasterSecretUnion(MasterSecretUtil.getAsymmetricMasterSecret(context, null)); } else { masterSecretUnion = new MasterSecretUnion(masterSecret); } if (message.isPresent() && !isBlocked(message.get())) { Pair<Long, Long> messageAndThreadId = storeMessage(masterSecretUnion, message.get()); MessageNotifier.updateNotification(context, masterSecret, messageAndThreadId.second); } else if (message.isPresent()) { Log.w(TAG, "*** Received blocked SMS, ignoring..."); } } @Override public void onCanceled() { } @Override public boolean onShouldRetry(Exception exception) { return false; } private boolean isBlocked(IncomingTextMessage message) { if (message.getSender() != null) { Recipients recipients = RecipientFactory.getRecipientsFromString(context, message.getSender(), false); return recipients.isBlocked(); } return false; } private Pair<Long, Long> storeMessage(MasterSecretUnion masterSecret, IncomingTextMessage message) { EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context); Pair<Long, Long> messageAndThreadId; if (message.isSecureMessage()) { IncomingTextMessage placeholder = new IncomingTextMessage(message, ""); messageAndThreadId = database.insertMessageInbox(placeholder); database.markAsLegacyVersion(messageAndThreadId.first); } else { messageAndThreadId = database.insertMessageInbox(masterSecret, message); } return messageAndThreadId; } private Optional<IncomingTextMessage> assembleMessageFragments(Object[] pdus) { List<IncomingTextMessage> messages = new LinkedList<>(); for (Object pdu : pdus) { messages.add(new IncomingTextMessage(SmsMessage.createFromPdu((byte[])pdu))); } if (messages.isEmpty()) { return Optional.absent(); } return Optional.of(new IncomingTextMessage(messages)); } }
3,655
31.642857
108
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/SmsSendJob.java
package org.thoughtcrime.securesms.jobs; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.telephony.SmsManager; import android.util.Log; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; import org.thoughtcrime.securesms.database.NoSuchMessageException; import org.thoughtcrime.securesms.database.SmsDatabase; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement; import org.thoughtcrime.securesms.jobs.requirements.NetworkOrServiceRequirement; import org.thoughtcrime.securesms.jobs.requirements.ServiceRequirement; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.service.SmsDeliveryListener; import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import org.thoughtcrime.securesms.util.NumberUtil; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.jobqueue.JobParameters; import java.util.ArrayList; public class SmsSendJob extends SendJob { private static final String TAG = SmsSendJob.class.getSimpleName(); private final long messageId; public SmsSendJob(Context context, long messageId, String name) { super(context, constructParameters(context, name)); this.messageId = messageId; } @Override public void onAdded() { SmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context); database.markAsSending(messageId); } @Override public void onSend(MasterSecret masterSecret) throws NoSuchMessageException { EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context); SmsMessageRecord record = database.getMessage(masterSecret, messageId); try { Log.w(TAG, "Sending message: " + messageId); deliver(record); } catch (UndeliverableMessageException ude) { Log.w(TAG, ude); DatabaseFactory.getSmsDatabase(context).markAsSentFailed(record.getId()); MessageNotifier.notifyMessageDeliveryFailed(context, record.getRecipients(), record.getThreadId()); } } @Override public boolean onShouldRetryThrowable(Exception throwable) { return false; } @Override public void onCanceled() { Log.w(TAG, "onCanceled()"); long threadId = DatabaseFactory.getSmsDatabase(context).getThreadIdForMessage(messageId); Recipients recipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId); DatabaseFactory.getSmsDatabase(context).markAsSentFailed(messageId); MessageNotifier.notifyMessageDeliveryFailed(context, recipients, threadId); } private void deliver(SmsMessageRecord message) throws UndeliverableMessageException { if (!NumberUtil.isValidSmsOrEmail(message.getIndividualRecipient().getNumber())) { throw new UndeliverableMessageException("Not a valid SMS destination! " + message.getIndividualRecipient().getNumber()); } if (message.isSecure() || message.isKeyExchange() || message.isEndSession()) { throw new UndeliverableMessageException("Trying to send a secure SMS?"); } ArrayList<String> messages = SmsManager.getDefault().divideMessage(message.getBody().getBody()); ArrayList<PendingIntent> sentIntents = constructSentIntents(message.getId(), message.getType(), messages, false); ArrayList<PendingIntent> deliveredIntents = constructDeliveredIntents(message.getId(), message.getType(), messages); String recipient = message.getIndividualRecipient().getNumber(); // remove characters for visible number formatting - they break sending sms on some phones (issue #1516) // stripSeparator() to rigid? what will people try to send here? - see discussion on #3099 //recipient = PhoneNumberUtils.stripSeparators(recipient); // minimum required to fix the issue - brackets are no dialable chars... recipient = recipient.replaceAll("[\\(\\)]", ""); // NOTE 11/04/14 -- There's apparently a bug where for some unknown recipients // and messages, this will throw an NPE. We have no idea why, so we're just // catching it and marking the message as a failure. That way at least it doesn't // repeatedly crash every time you start the app. try { SmsManager.getDefault().sendMultipartTextMessage(recipient, null, messages, sentIntents, deliveredIntents); } catch (NullPointerException npe) { Log.w(TAG, npe); Log.w(TAG, "Recipient: " + recipient); Log.w(TAG, "Message Parts: " + messages.size()); try { for (int i=0;i<messages.size();i++) { SmsManager.getDefault().sendTextMessage(recipient, null, messages.get(i), sentIntents.get(i), deliveredIntents == null ? null : deliveredIntents.get(i)); } } catch (NullPointerException npe2) { Log.w(TAG, npe); throw new UndeliverableMessageException(npe2); } } } private ArrayList<PendingIntent> constructSentIntents(long messageId, long type, ArrayList<String> messages, boolean secure) { ArrayList<PendingIntent> sentIntents = new ArrayList<>(messages.size()); for (String ignored : messages) { sentIntents.add(PendingIntent.getBroadcast(context, 0, constructSentIntent(context, messageId, type, secure, false), 0)); } return sentIntents; } private ArrayList<PendingIntent> constructDeliveredIntents(long messageId, long type, ArrayList<String> messages) { if (!TextSecurePreferences.isSmsDeliveryReportsEnabled(context)) { return null; } ArrayList<PendingIntent> deliveredIntents = new ArrayList<>(messages.size()); for (String ignored : messages) { deliveredIntents.add(PendingIntent.getBroadcast(context, 0, constructDeliveredIntent(context, messageId, type), 0)); } return deliveredIntents; } private Intent constructSentIntent(Context context, long messageId, long type, boolean upgraded, boolean push) { Intent pending = new Intent(SmsDeliveryListener.SENT_SMS_ACTION, Uri.parse("custom://" + messageId + System.currentTimeMillis()), context, SmsDeliveryListener.class); pending.putExtra("type", type); pending.putExtra("message_id", messageId); pending.putExtra("upgraded", upgraded); pending.putExtra("push", push); return pending; } private Intent constructDeliveredIntent(Context context, long messageId, long type) { Intent pending = new Intent(SmsDeliveryListener.DELIVERED_SMS_ACTION, Uri.parse("custom://" + messageId + System.currentTimeMillis()), context, SmsDeliveryListener.class); pending.putExtra("type", type); pending.putExtra("message_id", messageId); return pending; } private static JobParameters constructParameters(Context context, String name) { JobParameters.Builder builder = JobParameters.newBuilder() .withPersistence() .withRequirement(new MasterSecretRequirement(context)) .withRetryCount(15) .withGroupId(name); if (TextSecurePreferences.isWifiSmsEnabled(context)) { builder.withRequirement(new NetworkOrServiceRequirement(context)); } else { builder.withRequirement(new ServiceRequirement(context)); } return builder.create(); } }
8,295
41.111675
126
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/SmsSentJob.java
package org.thoughtcrime.securesms.jobs; import android.app.Activity; import android.content.Context; import android.telephony.SmsManager; import android.util.Log; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.SecurityEvent; import org.thoughtcrime.securesms.crypto.storage.TextSecureSessionStore; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.EncryptingSmsDatabase; import org.thoughtcrime.securesms.database.NoSuchMessageException; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.service.SmsDeliveryListener; import org.whispersystems.jobqueue.JobParameters; import org.whispersystems.libaxolotl.state.SessionStore; public class SmsSentJob extends MasterSecretJob { private static final String TAG = SmsSentJob.class.getSimpleName(); private final long messageId; private final String action; private final int result; public SmsSentJob(Context context, long messageId, String action, int result) { super(context, JobParameters.newBuilder() .withPersistence() .withRequirement(new MasterSecretRequirement(context)) .create()); this.messageId = messageId; this.action = action; this.result = result; } @Override public void onAdded() { } @Override public void onRun(MasterSecret masterSecret) { Log.w(TAG, "Got SMS callback: " + action + " , " + result); switch (action) { case SmsDeliveryListener.SENT_SMS_ACTION: handleSentResult(masterSecret, messageId, result); break; case SmsDeliveryListener.DELIVERED_SMS_ACTION: handleDeliveredResult(messageId, result); break; } } @Override public boolean onShouldRetryThrowable(Exception throwable) { return false; } @Override public void onCanceled() { } private void handleDeliveredResult(long messageId, int result) { DatabaseFactory.getEncryptingSmsDatabase(context).markStatus(messageId, result); } private void handleSentResult(MasterSecret masterSecret, long messageId, int result) { try { EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context); SmsMessageRecord record = database.getMessage(masterSecret, messageId); switch (result) { case Activity.RESULT_OK: database.markAsSent(messageId); break; case SmsManager.RESULT_ERROR_NO_SERVICE: case SmsManager.RESULT_ERROR_RADIO_OFF: Log.w(TAG, "Service connectivity problem, requeuing..."); ApplicationContext.getInstance(context) .getJobManager() .add(new SmsSendJob(context, messageId, record.getIndividualRecipient().getNumber())); break; default: database.markAsSentFailed(messageId); MessageNotifier.notifyMessageDeliveryFailed(context, record.getRecipients(), record.getThreadId()); } } catch (NoSuchMessageException e) { Log.w(TAG, e); } } }
3,359
32.939394
109
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/TrimThreadJob.java
/** * 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.jobs; import android.content.Context; import android.util.Log; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.jobqueue.Job; import org.whispersystems.jobqueue.JobParameters; public class TrimThreadJob extends Job { private static final String TAG = TrimThreadJob.class.getSimpleName(); private final Context context; private final long threadId; public TrimThreadJob(Context context, long threadId) { super(JobParameters.newBuilder().withGroupId(TrimThreadJob.class.getSimpleName()).create()); this.context = context; this.threadId = threadId; } @Override public void onAdded() { } @Override public void onRun() { boolean trimmingEnabled = TextSecurePreferences.isThreadLengthTrimmingEnabled(context); int threadLengthLimit = TextSecurePreferences.getThreadTrimLength(context); if (!trimmingEnabled) return; DatabaseFactory.getThreadDatabase(context).trimThread(threadId, threadLengthLimit); } @Override public boolean onShouldRetry(Exception exception) { return false; } @Override public void onCanceled() { Log.w(TAG, "Canceling trim attempt: " + threadId); } }
1,999
29.30303
96
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/persistence/EncryptingJobSerializer.java
package org.thoughtcrime.securesms.jobs.persistence; import org.thoughtcrime.securesms.crypto.MasterCipher; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.util.ParcelUtil; import org.whispersystems.jobqueue.EncryptionKeys; import org.whispersystems.jobqueue.Job; import org.whispersystems.jobqueue.persistence.JavaJobSerializer; import org.whispersystems.jobqueue.persistence.JobSerializer; import org.whispersystems.libaxolotl.InvalidMessageException; import java.io.IOException; public class EncryptingJobSerializer implements JobSerializer { private final JavaJobSerializer delegate; public EncryptingJobSerializer() { this.delegate = new JavaJobSerializer(); } @Override public String serialize(Job job) throws IOException { String plaintext = delegate.serialize(job); if (job.getEncryptionKeys() != null) { MasterSecret masterSecret = ParcelUtil.deserialize(job.getEncryptionKeys().getEncoded(), MasterSecret.CREATOR); MasterCipher masterCipher = new MasterCipher(masterSecret); return masterCipher.encryptBody(plaintext); } else { return plaintext; } } @Override public Job deserialize(EncryptionKeys keys, boolean encrypted, String serialized) throws IOException { try { String plaintext; if (encrypted) { MasterSecret masterSecret = ParcelUtil.deserialize(keys.getEncoded(), MasterSecret.CREATOR); MasterCipher masterCipher = new MasterCipher(masterSecret); plaintext = masterCipher.decryptBody(serialized); } else { plaintext = serialized; } return delegate.deserialize(keys, encrypted, plaintext); } catch (InvalidMessageException e) { throw new IOException(e); } } }
1,830
31.696429
104
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/MasterSecretRequirement.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.Context; import org.thoughtcrime.securesms.service.KeyCachingService; import org.whispersystems.jobqueue.dependencies.ContextDependent; import org.whispersystems.jobqueue.requirements.Requirement; public class MasterSecretRequirement implements Requirement, ContextDependent { private transient Context context; public MasterSecretRequirement(Context context) { this.context = context; } @Override public boolean isPresent() { return KeyCachingService.getMasterSecret(context) != null; } @Override public void setContext(Context context) { this.context = context; } }
682
24.296296
79
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/MasterSecretRequirementProvider.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import org.thoughtcrime.securesms.service.KeyCachingService; import org.whispersystems.jobqueue.requirements.RequirementListener; import org.whispersystems.jobqueue.requirements.RequirementProvider; public class MasterSecretRequirementProvider implements RequirementProvider { private final BroadcastReceiver newKeyReceiver; private RequirementListener listener; public MasterSecretRequirementProvider(Context context) { this.newKeyReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (listener != null) { listener.onRequirementStatusChanged(); } } }; IntentFilter filter = new IntentFilter(KeyCachingService.NEW_KEY_EVENT); context.registerReceiver(newKeyReceiver, filter, KeyCachingService.KEY_PERMISSION, null); } @Override public void setListener(RequirementListener listener) { this.listener = listener; } }
1,148
30.054054
93
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/MediaNetworkRequirement.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.annotation.NonNull; import android.util.Log; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.attachments.AttachmentId; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.AttachmentDatabase; import org.thoughtcrime.securesms.util.MediaUtil; import org.thoughtcrime.securesms.util.ServiceUtil; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.jobqueue.dependencies.ContextDependent; import org.whispersystems.jobqueue.requirements.Requirement; import java.util.Collections; import java.util.Set; public class MediaNetworkRequirement implements Requirement, ContextDependent { private static final long serialVersionUID = 0L; private static final String TAG = MediaNetworkRequirement.class.getSimpleName(); private transient Context context; private final long messageId; private final long partRowId; private final long partUniqueId; public MediaNetworkRequirement(Context context, long messageId, AttachmentId attachmentId) { this.context = context; this.messageId = messageId; this.partRowId = attachmentId.getRowId(); this.partUniqueId = attachmentId.getUniqueId(); } @Override public void setContext(Context context) { this.context = context; } private NetworkInfo getNetworkInfo() { return ServiceUtil.getConnectivityManager(context).getActiveNetworkInfo(); } public boolean isConnectedWifi() { final NetworkInfo info = getNetworkInfo(); return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI; } public boolean isConnectedMobile() { final NetworkInfo info = getNetworkInfo(); return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE; } public boolean isConnectedRoaming() { final NetworkInfo info = getNetworkInfo(); return info != null && info.isConnected() && info.isRoaming() && info.getType() == ConnectivityManager.TYPE_MOBILE; } private @NonNull Set<String> getAllowedAutoDownloadTypes() { if (isConnectedWifi()) { return TextSecurePreferences.getWifiMediaDownloadAllowed(context); } else if (isConnectedRoaming()) { return TextSecurePreferences.getRoamingMediaDownloadAllowed(context); } else if (isConnectedMobile()) { return TextSecurePreferences.getMobileMediaDownloadAllowed(context); } else { return Collections.emptySet(); } } @Override public boolean isPresent() { final AttachmentId attachmentId = new AttachmentId(partRowId, partUniqueId); final AttachmentDatabase db = DatabaseFactory.getAttachmentDatabase(context); final Attachment attachment = db.getAttachment(attachmentId); if (attachment == null) { Log.w(TAG, "attachment was null, returning vacuous true"); return true; } Log.w(TAG, "part transfer progress is " + attachment.getTransferState()); switch (attachment.getTransferState()) { case AttachmentDatabase.TRANSFER_PROGRESS_STARTED: return true; case AttachmentDatabase.TRANSFER_PROGRESS_AUTO_PENDING: final Set<String> allowedTypes = getAllowedAutoDownloadTypes(); final boolean isAllowed = allowedTypes.contains(MediaUtil.getDiscreteMimeType(attachment.getContentType())); /// XXX WTF -- This is *hella* gross. A requirement shouldn't have the side effect of // *modifying the database* just by calling isPresent(). if (isAllowed) db.setTransferState(messageId, attachmentId, AttachmentDatabase.TRANSFER_PROGRESS_STARTED); return isAllowed; default: return false; } } }
3,916
37.029126
121
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/MediaNetworkRequirementProvider.java
package org.thoughtcrime.securesms.jobs.requirements; import org.whispersystems.jobqueue.requirements.RequirementListener; import org.whispersystems.jobqueue.requirements.RequirementProvider; public class MediaNetworkRequirementProvider implements RequirementProvider { private RequirementListener listener; public void notifyMediaControlEvent() { if (listener != null) listener.onRequirementStatusChanged(); } @Override public void setListener(RequirementListener listener) { this.listener = listener; } }
532
27.052632
77
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/NetworkOrServiceRequirement.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.Context; import org.whispersystems.jobqueue.dependencies.ContextDependent; import org.whispersystems.jobqueue.requirements.NetworkRequirement; import org.whispersystems.jobqueue.requirements.Requirement; public class NetworkOrServiceRequirement implements Requirement, ContextDependent { private transient Context context; public NetworkOrServiceRequirement(Context context) { this.context = context; } @Override public void setContext(Context context) { this.context = context; } @Override public boolean isPresent() { NetworkRequirement networkRequirement = new NetworkRequirement(context); ServiceRequirement serviceRequirement = new ServiceRequirement(context); return networkRequirement.isPresent() || serviceRequirement.isPresent(); } }
866
27.9
83
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/ServiceRequirement.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.Context; import android.os.Looper; import android.os.MessageQueue; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.util.Log; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.sms.TelephonyServiceState; import org.whispersystems.jobqueue.dependencies.ContextDependent; import org.whispersystems.jobqueue.requirements.Requirement; public class ServiceRequirement implements Requirement, ContextDependent { private static final String TAG = ServiceRequirement.class.getSimpleName(); private transient Context context; public ServiceRequirement(Context context) { this.context = context; } @Override public void setContext(Context context) { this.context = context; } @Override public boolean isPresent() { TelephonyServiceState telephonyServiceState = new TelephonyServiceState(); return telephonyServiceState.isConnected(context); } }
1,087
28.405405
78
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/requirements/ServiceRequirementProvider.java
package org.thoughtcrime.securesms.jobs.requirements; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import org.whispersystems.jobqueue.requirements.RequirementListener; import org.whispersystems.jobqueue.requirements.RequirementProvider; import java.util.concurrent.atomic.AtomicBoolean; public class ServiceRequirementProvider implements RequirementProvider { private final TelephonyManager telephonyManager; private final ServiceStateListener serviceStateListener; private final AtomicBoolean listeningForServiceState; private RequirementListener requirementListener; public ServiceRequirementProvider(Context context) { this.telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); this.serviceStateListener = new ServiceStateListener(); this.listeningForServiceState = new AtomicBoolean(false); } @Override public void setListener(RequirementListener requirementListener) { this.requirementListener = requirementListener; } public void start() { if (listeningForServiceState.compareAndSet(false, true)) { this.telephonyManager.listen(serviceStateListener, PhoneStateListener.LISTEN_SERVICE_STATE); } } private void handleInService() { if (listeningForServiceState.compareAndSet(true, false)) { this.telephonyManager.listen(serviceStateListener, PhoneStateListener.LISTEN_NONE); } if (requirementListener != null) { requirementListener.onRequirementStatusChanged(); } } private class ServiceStateListener extends PhoneStateListener { @Override public void onServiceStateChanged(ServiceState serviceState) { if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) { handleInService(); } } } }
1,903
32.403509
107
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/ApnUnavailableException.java
package org.thoughtcrime.securesms.mms; public class ApnUnavailableException extends Exception { public ApnUnavailableException() { } public ApnUnavailableException(String detailMessage) { super(detailMessage); } public ApnUnavailableException(Throwable throwable) { super(throwable); } public ApnUnavailableException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } }
433
20.7
77
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/AttachmentManager.java
/** * Copyright (C) 2011 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.mms; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.provider.ContactsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Toast; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.components.AudioView; import org.thoughtcrime.securesms.components.RemovableMediaView; import org.thoughtcrime.securesms.components.ThumbnailView; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.MediaUtil; import org.thoughtcrime.securesms.util.ViewUtil; import org.whispersystems.libaxolotl.util.guava.Optional; import java.io.IOException; public class AttachmentManager { private final static String TAG = AttachmentManager.class.getSimpleName(); private final @NonNull Context context; private final @NonNull View attachmentView; private final @NonNull RemovableMediaView removableMediaView; private final @NonNull ThumbnailView thumbnail; private final @NonNull AudioView audioView; private final @NonNull AttachmentListener attachmentListener; private @NonNull Optional<Slide> slide = Optional.absent(); private @Nullable Uri captureUri; public AttachmentManager(@NonNull Activity activity, @NonNull AttachmentListener listener) { this.attachmentView = ViewUtil.findById(activity, R.id.attachment_editor); this.thumbnail = ViewUtil.findById(activity, R.id.attachment_thumbnail); this.audioView = ViewUtil.findById(activity, R.id.attachment_audio); this.removableMediaView = ViewUtil.findById(activity, R.id.removable_media_view); this.context = activity; this.attachmentListener = listener; removableMediaView.setRemoveClickListener(new RemoveButtonListener()); } public void clear() { AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f); animation.setDuration(200); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { slide = Optional.absent(); thumbnail.clear(); attachmentView.setVisibility(View.GONE); attachmentListener.onAttachmentChanged(); } }); attachmentView.startAnimation(animation); audioView.cleanup(); } public void cleanup() { cleanup(captureUri); cleanup(getSlideUri()); captureUri = null; slide = Optional.absent(); } private void cleanup(final @Nullable Uri uri) { if (uri != null && PersistentBlobProvider.isAuthority(context, uri)) { Log.w(TAG, "cleaning up " + uri); PersistentBlobProvider.getInstance(context).delete(uri); } } private void setSlide(@NonNull Slide slide) { if (getSlideUri() != null) cleanup(getSlideUri()); if (captureUri != null && slide.getUri() != captureUri) cleanup(captureUri); this.captureUri = null; this.slide = Optional.of(slide); } public void setMedia(@NonNull final MasterSecret masterSecret, @NonNull final Uri uri, @NonNull final MediaType mediaType, @NonNull final MediaConstraints constraints) { new AsyncTask<Void, Void, Slide>() { @Override protected void onPreExecute() { thumbnail.clear(); thumbnail.showProgressSpinner(); attachmentView.setVisibility(View.VISIBLE); } @Override protected @Nullable Slide doInBackground(Void... params) { long start = System.currentTimeMillis(); try { final long mediaSize = MediaUtil.getMediaSize(context, masterSecret, uri); final Slide slide = mediaType.createSlide(context, uri, mediaSize); Log.w(TAG, "slide with size " + mediaSize + " took " + (System.currentTimeMillis() - start) + "ms"); return slide; } catch (IOException ioe) { Log.w(TAG, ioe); return null; } } @Override protected void onPostExecute(@Nullable final Slide slide) { if (slide == null) { attachmentView.setVisibility(View.GONE); Toast.makeText(context, R.string.ConversationActivity_sorry_there_was_an_error_setting_your_attachment, Toast.LENGTH_SHORT).show(); } else if (!areConstraintsSatisfied(context, masterSecret, slide, constraints)) { attachmentView.setVisibility(View.GONE); Toast.makeText(context, R.string.ConversationActivity_attachment_exceeds_size_limits, Toast.LENGTH_SHORT).show(); } else { setSlide(slide); attachmentView.setVisibility(View.VISIBLE); if (slide.hasAudio()) { audioView.setAudio(masterSecret, (AudioSlide)slide, false); removableMediaView.display(audioView); } else { thumbnail.setImageResource(masterSecret, slide, false); removableMediaView.display(thumbnail); } attachmentListener.onAttachmentChanged(); } } }.execute(); } public boolean isAttachmentPresent() { return attachmentView.getVisibility() == View.VISIBLE; } public @NonNull SlideDeck buildSlideDeck() { SlideDeck deck = new SlideDeck(); if (slide.isPresent()) deck.addSlide(slide.get()); return deck; } public static void selectVideo(Activity activity, int requestCode) { selectMediaType(activity, "video/*", requestCode); } public static void selectImage(Activity activity, int requestCode) { selectMediaType(activity, "image/*", requestCode); } public static void selectAudio(Activity activity, int requestCode) { selectMediaType(activity, "audio/*", requestCode); } public static void selectContactInfo(Activity activity, int requestCode) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); activity.startActivityForResult(intent, requestCode); } private @Nullable Uri getSlideUri() { return slide.isPresent() ? slide.get().getUri() : null; } public @Nullable Uri getCaptureUri() { return captureUri; } public void capturePhoto(Activity activity, Recipients recipients, int requestCode) { try { Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (captureIntent.resolveActivity(activity.getPackageManager()) != null) { if (captureUri == null) { captureUri = PersistentBlobProvider.getInstance(context).createForExternal(recipients); } Log.w(TAG, "captureUri path is " + captureUri.getPath()); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri); activity.startActivityForResult(captureIntent, requestCode); } } catch (IOException ioe) { Log.w(TAG, ioe); } } private static void selectMediaType(Activity activity, String type, int requestCode) { final Intent intent = new Intent(); intent.setType(type); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { intent.setAction(Intent.ACTION_OPEN_DOCUMENT); try { activity.startActivityForResult(intent, requestCode); return; } catch (ActivityNotFoundException anfe) { Log.w(TAG, "couldn't complete ACTION_OPEN_DOCUMENT, no activity found. falling back."); } } intent.setAction(Intent.ACTION_GET_CONTENT); try { activity.startActivityForResult(intent, requestCode); } catch (ActivityNotFoundException anfe) { Log.w(TAG, "couldn't complete ACTION_GET_CONTENT intent, no activity found. falling back."); Toast.makeText(activity, R.string.AttachmentManager_cant_open_media_selection, Toast.LENGTH_LONG).show(); } } private boolean areConstraintsSatisfied(final @NonNull Context context, final @NonNull MasterSecret masterSecret, final @Nullable Slide slide, final @NonNull MediaConstraints constraints) { return slide == null || constraints.isSatisfied(context, masterSecret, slide.asAttachment()) || constraints.canResize(slide.asAttachment()); } private class RemoveButtonListener implements View.OnClickListener { @Override public void onClick(View v) { cleanup(); clear(); } } public interface AttachmentListener { void onAttachmentChanged(); } public enum MediaType { IMAGE, GIF, AUDIO, VIDEO; public @NonNull Slide createSlide(@NonNull Context context, @NonNull Uri uri, long dataSize) throws IOException { switch (this) { case IMAGE: return new ImageSlide(context, uri, dataSize); case GIF: return new GifSlide(context, uri, dataSize); case AUDIO: return new AudioSlide(context, uri, dataSize); case VIDEO: return new VideoSlide(context, uri, dataSize); default: throw new AssertionError("unrecognized enum"); } } } }
10,650
35.601375
111
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/AttachmentStreamLocalUriFetcher.java
package org.thoughtcrime.securesms.mms; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.util.Log; import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.data.StreamLocalUriFetcher; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.whispersystems.textsecure.api.crypto.AttachmentCipherInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class AttachmentStreamLocalUriFetcher implements DataFetcher<InputStream> { private static final String TAG = AttachmentStreamLocalUriFetcher.class.getSimpleName(); private File attachment; private byte[] key; private InputStream is; public AttachmentStreamLocalUriFetcher(File attachment, byte[] key) { this.attachment = attachment; this.key = key; } @Override public InputStream loadData(Priority priority) throws Exception { is = new AttachmentCipherInputStream(attachment, key); return is; } @Override public void cleanup() { try { if (is != null) is.close(); is = null; } catch (IOException ioe) { Log.w(TAG, "ioe"); } } @Override public String getId() { return AttachmentStreamLocalUriFetcher.class.getCanonicalName() + "::" + attachment.getAbsolutePath(); } @Override public void cancel() { } }
1,469
26.735849
106
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/AttachmentStreamUriLoader.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.net.Uri; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.bumptech.glide.load.model.stream.StreamModelLoader; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.mms.AttachmentStreamUriLoader.AttachmentModel; import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri; import org.thoughtcrime.securesms.util.SaveAttachmentTask.Attachment; import java.io.File; import java.io.InputStream; /** * A {@link ModelLoader} for translating uri models into {@link InputStream} data. Capable of handling 'http', * 'https', 'android.resource', 'content', and 'file' schemes. Unsupported schemes will throw an exception in * {@link #getResourceFetcher(Uri, int, int)}. */ public class AttachmentStreamUriLoader implements StreamModelLoader<AttachmentModel> { private final Context context; /** * THe default factory for {@link com.bumptech.glide.load.model.stream.StreamUriLoader}s. */ public static class Factory implements ModelLoaderFactory<AttachmentModel, InputStream> { @Override public StreamModelLoader<AttachmentModel> build(Context context, GenericLoaderFactory factories) { return new AttachmentStreamUriLoader(context); } @Override public void teardown() { // Do nothing. } } public AttachmentStreamUriLoader(Context context) { this.context = context; } @Override public DataFetcher<InputStream> getResourceFetcher(AttachmentModel model, int width, int height) { return new AttachmentStreamLocalUriFetcher(model.attachment, model.key); } public static class AttachmentModel { public File attachment; public byte[] key; public AttachmentModel(File attachment, byte[] key) { this.attachment = attachment; this.key = key; } } }
2,073
31.40625
110
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/AttachmentTypeSelectorAdapter.java
/* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thoughtcrime.securesms.mms; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.ResUtil; import java.util.ArrayList; import java.util.List; public class AttachmentTypeSelectorAdapter extends ArrayAdapter<AttachmentTypeSelectorAdapter.IconListItem> { public static final int ADD_IMAGE = 1; public static final int ADD_VIDEO = 2; public static final int ADD_SOUND = 3; public static final int ADD_CONTACT_INFO = 4; public static final int TAKE_PHOTO = 5; private final Context context; public AttachmentTypeSelectorAdapter(Context context) { super(context, R.layout.icon_list_item, getItemList(context)); this.context = context; } public int buttonToCommand(int position) { return getItem(position).getCommand(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.icon_list_item, parent, false); } else { view = convertView; } TextView text = (TextView) view.findViewById(R.id.text1); ImageView image = (ImageView) view.findViewById(R.id.icon); text.setText(getItem(position).getTitle()); image.setImageResource(getItem(position).getResource()); return view; } private static List<IconListItem> getItemList(Context context) { List<IconListItem> data = new ArrayList<>(4); addItem(data, context.getString(R.string.AttachmentTypeSelectorAdapter_camera), ResUtil.getDrawableRes(context, R.attr.conversation_attach_camera), TAKE_PHOTO); addItem(data, context.getString(R.string.AttachmentTypeSelectorAdapter_picture), ResUtil.getDrawableRes(context, R.attr.conversation_attach_image), ADD_IMAGE); addItem(data, context.getString(R.string.AttachmentTypeSelectorAdapter_video), ResUtil.getDrawableRes(context, R.attr.conversation_attach_video), ADD_VIDEO); addItem(data, context.getString(R.string.AttachmentTypeSelectorAdapter_audio), ResUtil.getDrawableRes(context, R.attr.conversation_attach_sound), ADD_SOUND); addItem(data, context.getString(R.string.AttachmentTypeSelectorAdapter_contact), ResUtil.getDrawableRes(context, R.attr.conversation_attach_contact_info), ADD_CONTACT_INFO); return data; } private static void addItem(List<IconListItem> list, String text, int resource, int id) { list.add(new IconListItem(text, resource, id)); } public static class IconListItem { private final String title; private final int resource; private final int id; public IconListItem(String title, int resource, int id) { this.resource = resource; this.title = title; this.id = id; } public int getCommand() { return id; } public String getTitle() { return title; } public int getResource() { return resource; } } }
3,944
34.223214
177
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/AudioSlide.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.content.res.Resources.Theme; import android.net.Uri; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.util.ResUtil; import java.io.IOException; import ws.com.google.android.mms.ContentType; import ws.com.google.android.mms.pdu.PduPart; public class AudioSlide extends Slide { public AudioSlide(Context context, Uri uri, long dataSize) throws IOException { super(context, constructAttachmentFromUri(context, uri, ContentType.AUDIO_UNSPECIFIED, dataSize)); } public AudioSlide(Context context, Attachment attachment) { super(context, attachment); } @Override @Nullable public Uri getThumbnailUri() { return null; } @Override public boolean hasPlaceholder() { return true; } @Override public boolean hasImage() { return true; } @Override public boolean hasAudio() { return true; } @NonNull @Override public String getContentDescription() { return context.getString(R.string.Slide_audio); } @Override public @DrawableRes int getPlaceholderRes(Theme theme) { return ResUtil.getDrawableRes(theme, R.attr.conversation_icon_attach_audio); } }
2,127
26.636364
102
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/CompatMmsConnection.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import java.io.IOException; import ws.com.google.android.mms.MmsException; import ws.com.google.android.mms.pdu.RetrieveConf; import ws.com.google.android.mms.pdu.SendConf; public class CompatMmsConnection implements OutgoingMmsConnection, IncomingMmsConnection { private static final String TAG = CompatMmsConnection.class.getSimpleName(); private Context context; public CompatMmsConnection(Context context) { this.context = context; } @Nullable @Override public SendConf send(@NonNull byte[] pduBytes) throws UndeliverableMessageException { try { Log.w(TAG, "Sending via legacy connection"); return new OutgoingLegacyMmsConnection(context).send(pduBytes); } catch (UndeliverableMessageException | ApnUnavailableException e) { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { Log.w(TAG, "Falling back to try sending via Lollipop API"); return new OutgoingLollipopMmsConnection(context).send(pduBytes); } else { throw new UndeliverableMessageException(e); } } } @Nullable @Override public RetrieveConf retrieve(@NonNull String contentLocation, byte[] transactionId) throws MmsException, MmsRadioException, ApnUnavailableException, IOException { try { Log.w(TAG, "Receiving via legacy connection"); return new IncomingLegacyMmsConnection(context).retrieve(contentLocation, transactionId); } catch (MmsRadioException | IOException | ApnUnavailableException e) { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { Log.w(TAG, "Falling back to try receiving via Lollipop API"); return new IncomingLollipopMmsConnection(context).retrieve(contentLocation, transactionId); } else { throw e; } } } }
2,137
32.40625
99
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/ContactPhotoLocalUriFetcher.java
package org.thoughtcrime.securesms.mms; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.provider.ContactsContract; import com.bumptech.glide.load.data.StreamLocalUriFetcher; import java.io.FileNotFoundException; import java.io.InputStream; public class ContactPhotoLocalUriFetcher extends StreamLocalUriFetcher { private static final String TAG = ContactPhotoLocalUriFetcher.class.getSimpleName(); public ContactPhotoLocalUriFetcher(Context context, Uri uri) { super(context, uri); } @Override protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException { if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) { return ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri, true); } else { return ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri); } } }
1,039
30.515152
95
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/ContactPhotoUriLoader.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.net.Uri; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.bumptech.glide.load.model.stream.StreamModelLoader; import org.thoughtcrime.securesms.mms.ContactPhotoUriLoader.ContactPhotoUri; import java.io.InputStream; public class ContactPhotoUriLoader implements StreamModelLoader<ContactPhotoUri> { private final Context context; /** * THe default factory for {@link com.bumptech.glide.load.model.stream.StreamUriLoader}s. */ public static class Factory implements ModelLoaderFactory<ContactPhotoUri, InputStream> { @Override public StreamModelLoader<ContactPhotoUri> build(Context context, GenericLoaderFactory factories) { return new ContactPhotoUriLoader(context); } @Override public void teardown() { // Do nothing. } } public ContactPhotoUriLoader(Context context) { this.context = context; } @Override public DataFetcher<InputStream> getResourceFetcher(ContactPhotoUri model, int width, int height) { return new ContactPhotoLocalUriFetcher(context, model.uri); } public static class ContactPhotoUri { public Uri uri; public ContactPhotoUri(Uri uri) { this.uri = uri; } } }
1,395
25.846154
102
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/DecryptableStreamLocalUriFetcher.java
package org.thoughtcrime.securesms.mms; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.util.Log; import com.bumptech.glide.load.data.StreamLocalUriFetcher; import org.thoughtcrime.securesms.crypto.MasterSecret; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class DecryptableStreamLocalUriFetcher extends StreamLocalUriFetcher { private static final String TAG = DecryptableStreamLocalUriFetcher.class.getSimpleName(); private Context context; private MasterSecret masterSecret; public DecryptableStreamLocalUriFetcher(Context context, MasterSecret masterSecret, Uri uri) { super(context, uri); this.context = context; this.masterSecret = masterSecret; } @Override protected InputStream loadResource(Uri uri, ContentResolver contentResolver) throws FileNotFoundException { try { return PartAuthority.getAttachmentStream(context, masterSecret, uri); } catch (IOException ioe) { Log.w(TAG, ioe); throw new FileNotFoundException("PartAuthority couldn't load Uri resource."); } } }
1,173
29.102564
109
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/DecryptableStreamUriLoader.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.net.Uri; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.bumptech.glide.load.model.stream.StreamModelLoader; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri; import java.io.InputStream; /** * A {@link ModelLoader} for translating uri models into {@link InputStream} data. Capable of handling 'http', * 'https', 'android.resource', 'content', and 'file' schemes. Unsupported schemes will throw an exception in * {@link #getResourceFetcher(Uri, int, int)}. */ public class DecryptableStreamUriLoader implements StreamModelLoader<DecryptableUri> { private final Context context; /** * THe default factory for {@link com.bumptech.glide.load.model.stream.StreamUriLoader}s. */ public static class Factory implements ModelLoaderFactory<DecryptableUri, InputStream> { @Override public StreamModelLoader<DecryptableUri> build(Context context, GenericLoaderFactory factories) { return new DecryptableStreamUriLoader(context); } @Override public void teardown() { // Do nothing. } } public DecryptableStreamUriLoader(Context context) { this.context = context; } @Override public DataFetcher<InputStream> getResourceFetcher(DecryptableUri model, int width, int height) { return new DecryptableStreamLocalUriFetcher(context, model.masterSecret, model.uri); } public static class DecryptableUri { public MasterSecret masterSecret; public Uri uri; public DecryptableUri(MasterSecret masterSecret, Uri uri) { this.masterSecret = masterSecret; this.uri = uri; } } }
1,937
30.770492
110
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/GifSlide.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.net.Uri; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.crypto.MasterSecret; import java.io.IOException; import java.io.InputStream; import ws.com.google.android.mms.pdu.PduPart; public class GifSlide extends ImageSlide { public GifSlide(Context context, Attachment attachment) { super(context, attachment); } public GifSlide(Context context, Uri uri, long dataSize) throws IOException { super(context, uri, dataSize); } @Override @Nullable public Uri getThumbnailUri() { return getUri(); } }
705
21.774194
79
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/ImageSlide.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.content.res.Resources.Theme; import android.net.Uri; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.attachments.Attachment; import java.io.IOException; import ws.com.google.android.mms.ContentType; public class ImageSlide extends Slide { private static final String TAG = ImageSlide.class.getSimpleName(); public ImageSlide(@NonNull Context context, @NonNull Attachment attachment) { super(context, attachment); } public ImageSlide(Context context, Uri uri, long size) throws IOException { super(context, constructAttachmentFromUri(context, uri, ContentType.IMAGE_JPEG, size)); } @Override public @DrawableRes int getPlaceholderRes(Theme theme) { return 0; } @Override public boolean hasImage() { return true; } @NonNull @Override public String getContentDescription() { return context.getString(R.string.Slide_image); } }
1,779
29.689655
91
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/IncomingLegacyMmsConnection.java
/** * Copyright (C) 2015 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.mms; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGetHC4; import org.apache.http.client.methods.HttpUriRequest; import java.io.IOException; import java.util.Arrays; import ws.com.google.android.mms.InvalidHeaderValueException; import ws.com.google.android.mms.pdu.NotifyRespInd; import ws.com.google.android.mms.pdu.PduComposer; import ws.com.google.android.mms.pdu.PduHeaders; import ws.com.google.android.mms.pdu.PduParser; import ws.com.google.android.mms.pdu.RetrieveConf; @SuppressWarnings("deprecation") public class IncomingLegacyMmsConnection extends LegacyMmsConnection implements IncomingMmsConnection { private static final String TAG = IncomingLegacyMmsConnection.class.getSimpleName(); public IncomingLegacyMmsConnection(Context context) throws ApnUnavailableException { super(context); } private HttpUriRequest constructRequest(Apn contentApn, boolean useProxy) throws IOException { HttpGetHC4 request = new HttpGetHC4(contentApn.getMmsc()); for (Header header : getBaseHeaders()) { request.addHeader(header); } if (useProxy) { HttpHost proxy = new HttpHost(contentApn.getProxy(), contentApn.getPort()); request.setConfig(RequestConfig.custom().setProxy(proxy).build()); } return request; } @Override public @Nullable RetrieveConf retrieve(@NonNull String contentLocation, byte[] transactionId) throws MmsRadioException, ApnUnavailableException, IOException { MmsRadio radio = MmsRadio.getInstance(context); Apn contentApn = new Apn(contentLocation, apn.getProxy(), Integer.toString(apn.getPort()), apn.getUsername(), apn.getPassword()); if (isCdmaDevice()) { Log.w(TAG, "Connecting directly..."); try { return retrieve(contentApn, transactionId, false, false); } catch (IOException | ApnUnavailableException e) { Log.w(TAG, e); } } Log.w(TAG, "Changing radio to MMS mode.."); radio.connect(); try { Log.w(TAG, "Downloading in MMS mode with proxy..."); try { return retrieve(contentApn, transactionId, true, true); } catch (IOException | ApnUnavailableException e) { Log.w(TAG, e); } Log.w(TAG, "Downloading in MMS mode without proxy..."); return retrieve(contentApn, transactionId, true, false); } finally { radio.disconnect(); } } public RetrieveConf retrieve(Apn contentApn, byte[] transactionId, boolean usingMmsRadio, boolean useProxyIfAvailable) throws IOException, ApnUnavailableException { byte[] pdu = null; final boolean useProxy = useProxyIfAvailable && contentApn.hasProxy(); final String targetHost = useProxy ? contentApn.getProxy() : Uri.parse(contentApn.getMmsc()).getHost(); if (checkRouteToHost(context, targetHost, usingMmsRadio)) { Log.w(TAG, "got successful route to host " + targetHost); pdu = execute(constructRequest(contentApn, useProxy)); } if (pdu == null) { throw new IOException("Connection manager could not obtain route to host."); } RetrieveConf retrieved = (RetrieveConf)new PduParser(pdu).parse(); if (retrieved == null) { Log.w(TAG, "Couldn't parse PDU, byte response: " + Arrays.toString(pdu)); Log.w(TAG, "Couldn't parse PDU, ASCII: " + new String(pdu)); throw new IOException("Bad retrieved PDU"); } sendRetrievedAcknowledgement(transactionId, usingMmsRadio, useProxy); return retrieved; } private void sendRetrievedAcknowledgement(byte[] transactionId, boolean usingRadio, boolean useProxy) throws ApnUnavailableException { try { NotifyRespInd notifyResponse = new NotifyRespInd(PduHeaders.CURRENT_MMS_VERSION, transactionId, PduHeaders.STATUS_RETRIEVED); OutgoingLegacyMmsConnection connection = new OutgoingLegacyMmsConnection(context); connection.sendNotificationReceived(new PduComposer(context, notifyResponse).make(), usingRadio, useProxy); } catch (InvalidHeaderValueException | IOException e) { Log.w(TAG, e); } } }
5,371
36.048276
133
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/IncomingLollipopMmsConnection.java
/** * Copyright (C) 2015 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.mms; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.telephony.SmsManager; import android.util.Log; import org.thoughtcrime.securesms.providers.MmsBodyProvider; import org.thoughtcrime.securesms.util.Hex; import org.thoughtcrime.securesms.util.Util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.concurrent.TimeoutException; import ws.com.google.android.mms.MmsException; import ws.com.google.android.mms.pdu.PduParser; import ws.com.google.android.mms.pdu.RetrieveConf; public class IncomingLollipopMmsConnection extends LollipopMmsConnection implements IncomingMmsConnection { public static final String ACTION = IncomingLollipopMmsConnection.class.getCanonicalName() + "MMS_DOWNLOADED_ACTION"; private static final String TAG = IncomingLollipopMmsConnection.class.getSimpleName(); public IncomingLollipopMmsConnection(Context context) { super(context, ACTION); } @TargetApi(VERSION_CODES.LOLLIPOP) @Override public synchronized void onResult(Context context, Intent intent) { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { Log.w(TAG, "HTTP status: " + intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, -1)); } Log.w(TAG, "code: " + getResultCode() + ", result string: " + getResultData()); } @Override @TargetApi(VERSION_CODES.LOLLIPOP) public synchronized @Nullable RetrieveConf retrieve(@NonNull String contentLocation, byte[] transactionId) throws MmsException { beginTransaction(); try { MmsBodyProvider.Pointer pointer = MmsBodyProvider.makeTemporaryPointer(getContext()); Log.w(TAG, "downloading multimedia from " + contentLocation + " to " + pointer.getUri()); SmsManager.getDefault().downloadMultimediaMessage(getContext(), contentLocation, pointer.getUri(), null, getPendingIntent()); waitForResult(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Util.copy(pointer.getInputStream(), baos); pointer.close(); Log.w(TAG, baos.size() + "-byte response: " + Hex.dump(baos.toByteArray())); return (RetrieveConf) new PduParser(baos.toByteArray()).parse(); } catch (IOException | TimeoutException e) { Log.w(TAG, e); throw new MmsException(e); } finally { endTransaction(); } } }
3,540
37.48913
120
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/IncomingMediaMessage.java
package org.thoughtcrime.securesms.mms; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.attachments.PointerAttachment; import org.thoughtcrime.securesms.crypto.MasterSecretUnion; import org.thoughtcrime.securesms.database.MmsAddresses; import org.thoughtcrime.securesms.util.GroupUtil; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.messages.TextSecureAttachment; import org.whispersystems.textsecure.api.messages.TextSecureGroup; import java.util.LinkedList; import java.util.List; public class IncomingMediaMessage { private final String from; private final String body; private final String groupId; private final boolean push; private final long sentTimeMillis; private final List<String> to = new LinkedList<>(); private final List<String> cc = new LinkedList<>(); private final List<Attachment> attachments = new LinkedList<>(); public IncomingMediaMessage(String from, List<String> to, List<String> cc, String body, long sentTimeMillis, List<Attachment> attachments) { this.from = from; this.sentTimeMillis = sentTimeMillis; this.body = body; this.groupId = null; this.push = false; this.to.addAll(to); this.cc.addAll(cc); this.attachments.addAll(attachments); } public IncomingMediaMessage(MasterSecretUnion masterSecret, String from, String to, long sentTimeMillis, Optional<String> relay, Optional<String> body, Optional<TextSecureGroup> group, Optional<List<TextSecureAttachment>> attachments) { this.push = true; this.from = from; this.sentTimeMillis = sentTimeMillis; this.body = body.orNull(); if (group.isPresent()) this.groupId = GroupUtil.getEncodedId(group.get().getGroupId()); else this.groupId = null; this.to.add(to); this.attachments.addAll(PointerAttachment.forPointers(masterSecret, attachments)); } public String getBody() { return body; } public MmsAddresses getAddresses() { return new MmsAddresses(from, to, cc, new LinkedList<String>()); } public List<Attachment> getAttachments() { return attachments; } public String getGroupId() { return groupId; } public boolean isPushMessage() { return push; } public long getSentTimeMillis() { return sentTimeMillis; } public boolean isGroupMessage() { return groupId != null || to.size() > 1 || cc.size() > 0; } }
2,832
30.131868
91
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/IncomingMmsConnection.java
package org.thoughtcrime.securesms.mms; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.IOException; import ws.com.google.android.mms.MmsException; import ws.com.google.android.mms.pdu.RetrieveConf; public interface IncomingMmsConnection { @Nullable RetrieveConf retrieve(@NonNull String contentLocation, byte[] transactionId) throws MmsException, MmsRadioException, ApnUnavailableException, IOException; }
467
32.428571
166
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/LegacyMmsConnection.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.annotation.Nullable; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import org.apache.http.Header; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.NoConnectionReuseStrategyHC4; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.thoughtcrime.securesms.database.ApnDatabase; import org.thoughtcrime.securesms.util.TelephonyUtil; import org.thoughtcrime.securesms.util.Conversions; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URL; import java.util.LinkedList; import java.util.List; @SuppressWarnings("deprecation") public abstract class LegacyMmsConnection { public static final String USER_AGENT = "Android-Mms/2.0"; private static final String TAG = LegacyMmsConnection.class.getSimpleName(); protected final Context context; protected final Apn apn; protected LegacyMmsConnection(Context context) throws ApnUnavailableException { this.context = context; this.apn = getApn(context); } public static Apn getApn(Context context) throws ApnUnavailableException { try { Optional<Apn> params = ApnDatabase.getInstance(context) .getMmsConnectionParameters(TelephonyUtil.getMccMnc(context), TelephonyUtil.getApn(context)); if (!params.isPresent()) { throw new ApnUnavailableException("No parameters available from ApnDefaults."); } return params.get(); } catch (IOException ioe) { throw new ApnUnavailableException("ApnDatabase threw an IOException", ioe); } } protected boolean isCdmaDevice() { return ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA; } @SuppressWarnings("TryWithIdenticalCatches") protected static boolean checkRouteToHost(Context context, String host, boolean usingMmsRadio) throws IOException { InetAddress inetAddress = InetAddress.getByName(host); if (!usingMmsRadio) { if (inetAddress.isSiteLocalAddress()) { throw new IOException("RFC1918 address in non-MMS radio situation!"); } Log.w(TAG, "returning vacuous success since MMS radio is not in use"); return true; } if (inetAddress == null) { throw new IOException("Unable to lookup host: InetAddress.getByName() returned null."); } byte[] ipAddressBytes = inetAddress.getAddress(); if (ipAddressBytes == null) { Log.w(TAG, "resolved IP address bytes are null, returning true to attempt a connection anyway."); return true; } Log.w(TAG, "Checking route to address: " + host + ", " + inetAddress.getHostAddress()); ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); try { final Method requestRouteMethod = manager.getClass().getMethod("requestRouteToHostAddress", Integer.TYPE, InetAddress.class); final boolean routeToHostObtained = (Boolean) requestRouteMethod.invoke(manager, MmsRadio.TYPE_MOBILE_MMS, inetAddress); Log.w(TAG, "requestRouteToHostAddress(" + inetAddress + ") -> " + routeToHostObtained); return routeToHostObtained; } catch (NoSuchMethodException nsme) { Log.w(TAG, nsme); } catch (IllegalAccessException iae) { Log.w(TAG, iae); } catch (InvocationTargetException ite) { Log.w(TAG, ite); } final int ipAddress = Conversions.byteArrayToIntLittleEndian(ipAddressBytes, 0); final boolean routeToHostObtained = manager.requestRouteToHost(MmsRadio.TYPE_MOBILE_MMS, ipAddress); Log.w(TAG, "requestRouteToHost(" + ipAddress + ") -> " + routeToHostObtained); return routeToHostObtained; } protected static byte[] parseResponse(InputStream is) throws IOException { InputStream in = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Util.copy(in, baos); Log.w(TAG, "Received full server response, " + baos.size() + " bytes"); return baos.toByteArray(); } protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom() .setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000) .setSocketTimeout(20 * 1000) .setMaxRedirects(20) .build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom() .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()) .setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider) .build(); } protected byte[] execute(HttpUriRequest request) throws IOException { Log.w(TAG, "connecting to " + apn.getMmsc()); CloseableHttpClient client = null; CloseableHttpResponse response = null; try { client = constructHttpClient(); response = client.execute(request); Log.w(TAG, "* response code: " + response.getStatusLine()); if (response.getStatusLine().getStatusCode() == 200) { return parseResponse(response.getEntity().getContent()); } } catch (NullPointerException npe) { // TODO determine root cause // see: https://github.com/WhisperSystems/Signal-Android/issues/4379 throw new IOException(npe); } finally { if (response != null) response.close(); if (client != null) client.close(); } throw new IOException("unhandled response code"); } protected List<Header> getBaseHeaders() { final String number = TelephonyUtil.getManager(context).getLine1Number(); ; return new LinkedList<Header>() {{ add(new BasicHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic")); add(new BasicHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml")); add(new BasicHeader("Content-Type", "application/vnd.wap.mms-message")); add(new BasicHeader("x-carrier-magic", "http://magic.google.com")); if (!TextUtils.isEmpty(number)) { add(new BasicHeader("x-up-calling-line-id", number)); add(new BasicHeader("X-MDN", number)); } }}; } public static class Apn { public static Apn EMPTY = new Apn("", "", "", "", ""); private final String mmsc; private final String proxy; private final String port; private final String username; private final String password; public Apn(String mmsc, String proxy, String port, String username, String password) { this.mmsc = mmsc; this.proxy = proxy; this.port = port; this.username = username; this.password = password; } public Apn(Apn customApn, Apn defaultApn, boolean useCustomMmsc, boolean useCustomProxy, boolean useCustomProxyPort, boolean useCustomUsername, boolean useCustomPassword) { this.mmsc = useCustomMmsc ? customApn.mmsc : defaultApn.mmsc; this.proxy = useCustomProxy ? customApn.proxy : defaultApn.proxy; this.port = useCustomProxyPort ? customApn.port : defaultApn.port; this.username = useCustomUsername ? customApn.username : defaultApn.username; this.password = useCustomPassword ? customApn.password : defaultApn.password; } public boolean hasProxy() { return !TextUtils.isEmpty(proxy); } public String getMmsc() { return mmsc; } public String getProxy() { return hasProxy() ? proxy : null; } public int getPort() { return TextUtils.isEmpty(port) ? 80 : Integer.parseInt(port); } public boolean hasAuthentication() { return !TextUtils.isEmpty(username); } public String getUsername() { return username; } public String getPassword() { return password; } @Override public String toString() { return Apn.class.getSimpleName() + "{ mmsc: \"" + mmsc + "\"" + ", proxy: " + (proxy == null ? "none" : '"' + proxy + '"') + ", port: " + (port == null ? "(none)" : port) + ", user: " + (username == null ? "none" : '"' + username + '"') + ", pass: " + (password == null ? "none" : '"' + password + '"') + " }"; } } }
11,183
37.565517
134
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/LollipopMmsConnection.java
/** * Copyright (C) 2015 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.mms; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; import org.thoughtcrime.securesms.util.Util; import java.util.concurrent.TimeoutException; public abstract class LollipopMmsConnection extends BroadcastReceiver { private static final String TAG = LollipopMmsConnection.class.getSimpleName(); private final Context context; private final String action; private boolean resultAvailable; public abstract void onResult(Context context, Intent intent); protected LollipopMmsConnection(Context context, String action) { super(); this.context = context; this.action = action; } @Override public synchronized void onReceive(Context context, Intent intent) { Log.w(TAG, "onReceive()"); if (!action.equals(intent.getAction())) { Log.w(TAG, "received broadcast with unexpected action " + intent.getAction()); return; } onResult(context, intent); resultAvailable = true; notifyAll(); } protected void beginTransaction() { getContext().getApplicationContext().registerReceiver(this, new IntentFilter(action)); } protected void endTransaction() { getContext().getApplicationContext().unregisterReceiver(this); resultAvailable = false; } protected void waitForResult() throws TimeoutException { long timeoutExpiration = System.currentTimeMillis() + 60000; while (!resultAvailable) { Util.wait(this, Math.max(1, timeoutExpiration - System.currentTimeMillis())); if (System.currentTimeMillis() >= timeoutExpiration) { throw new TimeoutException("timeout when waiting for MMS"); } } } protected PendingIntent getPendingIntent() { return PendingIntent.getBroadcast(getContext(), 1, new Intent(action), PendingIntent.FLAG_ONE_SHOT); } protected Context getContext() { return context; } }
2,722
30.298851
104
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MediaConstraints.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.util.Pair; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri; import org.thoughtcrime.securesms.util.BitmapUtil; import org.thoughtcrime.securesms.util.MediaUtil; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutionException; public abstract class MediaConstraints { private static final String TAG = MediaConstraints.class.getSimpleName(); public static MediaConstraints MMS_CONSTRAINTS = new MmsMediaConstraints(); public static MediaConstraints PUSH_CONSTRAINTS = new PushMediaConstraints(); public abstract int getImageMaxWidth(Context context); public abstract int getImageMaxHeight(Context context); public abstract int getImageMaxSize(); public abstract int getGifMaxSize(); public abstract int getVideoMaxSize(); public abstract int getAudioMaxSize(); public boolean isSatisfied(@NonNull Context context, @NonNull MasterSecret masterSecret, @NonNull Attachment attachment) { try { return (MediaUtil.isGif(attachment) && attachment.getSize() <= getGifMaxSize() && isWithinBounds(context, masterSecret, attachment.getDataUri())) || (MediaUtil.isImage(attachment) && attachment.getSize() <= getImageMaxSize() && isWithinBounds(context, masterSecret, attachment.getDataUri())) || (MediaUtil.isAudio(attachment) && attachment.getSize() <= getAudioMaxSize()) || (MediaUtil.isVideo(attachment) && attachment.getSize() <= getVideoMaxSize()) || (!MediaUtil.isImage(attachment) && !MediaUtil.isAudio(attachment) && !MediaUtil.isVideo(attachment)); } catch (IOException ioe) { Log.w(TAG, "Failed to determine if media's constraints are satisfied.", ioe); return false; } } public boolean isWithinBounds(Context context, MasterSecret masterSecret, Uri uri) throws IOException { InputStream is = PartAuthority.getAttachmentStream(context, masterSecret, uri); Pair<Integer, Integer> dimensions = BitmapUtil.getDimensions(is); return dimensions.first > 0 && dimensions.first <= getImageMaxWidth(context) && dimensions.second > 0 && dimensions.second <= getImageMaxHeight(context); } public boolean canResize(@Nullable Attachment attachment) { return attachment != null && MediaUtil.isImage(attachment) && !MediaUtil.isGif(attachment); } public InputStream getResizedMedia(@NonNull Context context, @NonNull MasterSecret masterSecret, @NonNull Attachment attachment) throws IOException { if (!canResize(attachment)) { throw new UnsupportedOperationException("Cannot resize this content type"); } try { // XXX - This is loading everything into memory! We want the send path to be stream-like. return new ByteArrayInputStream(BitmapUtil.createScaledBytes(context, new DecryptableUri(masterSecret, attachment.getDataUri()), this)); } catch (ExecutionException ee) { throw new IOException(ee); } } }
3,426
42.935897
159
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MediaNotFoundException.java
/** * 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.mms; public class MediaNotFoundException extends Exception { public MediaNotFoundException() { } public MediaNotFoundException(String detailMessage) { super(detailMessage); } public MediaNotFoundException(Throwable throwable) { super(throwable); } public MediaNotFoundException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } }
1,130
29.567568
76
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MediaTooLargeException.java
/** * Copyright (C) 2011 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.mms; public class MediaTooLargeException extends Exception { public MediaTooLargeException() { // TODO Auto-generated constructor stub } public MediaTooLargeException(String detailMessage) { super(detailMessage); // TODO Auto-generated constructor stub } public MediaTooLargeException(Throwable throwable) { super(throwable); // TODO Auto-generated constructor stub } public MediaTooLargeException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); // TODO Auto-generated constructor stub } }
1,303
30.804878
76
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MmsMediaConstraints.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import org.thoughtcrime.securesms.util.Util; public class MmsMediaConstraints extends MediaConstraints { private static final int MAX_IMAGE_DIMEN_LOWMEM = 768; private static final int MAX_IMAGE_DIMEN = 1024; public static final int MAX_MESSAGE_SIZE = 280 * 1024; @Override public int getImageMaxWidth(Context context) { return Util.isLowMemory(context) ? MAX_IMAGE_DIMEN_LOWMEM : MAX_IMAGE_DIMEN; } @Override public int getImageMaxHeight(Context context) { return getImageMaxWidth(context); } @Override public int getImageMaxSize() { return MAX_MESSAGE_SIZE; } @Override public int getGifMaxSize() { return MAX_MESSAGE_SIZE; } @Override public int getVideoMaxSize() { return MAX_MESSAGE_SIZE; } @Override public int getAudioMaxSize() { return MAX_MESSAGE_SIZE; } }
927
21.095238
80
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MmsRadio.java
package org.thoughtcrime.securesms.mms; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.PowerManager; import android.util.Log; import org.thoughtcrime.securesms.util.Util; public class MmsRadio { private static MmsRadio instance; public static synchronized MmsRadio getInstance(Context context) { if (instance == null) instance = new MmsRadio(context.getApplicationContext()); return instance; } /// private static final String FEATURE_ENABLE_MMS = "enableMMS"; private static final int APN_ALREADY_ACTIVE = 0; public static final int TYPE_MOBILE_MMS = 2; private final Context context; private ConnectivityManager connectivityManager; private ConnectivityListener connectivityListener; private PowerManager.WakeLock wakeLock; private int connectedCounter = 0; private MmsRadio(Context context) { PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); this.context = context; this.connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS Connection"); this.wakeLock.setReferenceCounted(true); } public synchronized void disconnect() { Log.w("MmsRadio", "MMS Radio Disconnect Called..."); wakeLock.release(); connectedCounter--; Log.w("MmsRadio", "Reference count: " + connectedCounter); if (connectedCounter == 0) { Log.w("MmsRadio", "Turning off MMS radio..."); connectivityManager.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, FEATURE_ENABLE_MMS); if (connectivityListener != null) { Log.w("MmsRadio", "Unregistering receiver..."); context.unregisterReceiver(connectivityListener); connectivityListener = null; } } } public synchronized void connect() throws MmsRadioException { int status = connectivityManager.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, FEATURE_ENABLE_MMS); Log.w("MmsRadio", "startUsingNetworkFeature status: " + status); if (status == APN_ALREADY_ACTIVE) { wakeLock.acquire(); connectedCounter++; return; } else { wakeLock.acquire(); connectedCounter++; if (connectivityListener == null) { IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); connectivityListener = new ConnectivityListener(); context.registerReceiver(connectivityListener, filter); } Util.wait(this, 30000); if (!isConnected()) { Log.w("MmsRadio", "Got back from connectivity wait, and not connected..."); disconnect(); throw new MmsRadioException("Unable to successfully enable MMS radio."); } } } private boolean isConnected() { NetworkInfo info = connectivityManager.getNetworkInfo(TYPE_MOBILE_MMS); Log.w("MmsRadio", "Connected: " + info); if ((info == null) || (info.getType() != TYPE_MOBILE_MMS) || !info.isConnected()) return false; return true; } private boolean isConnectivityPossible() { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(TYPE_MOBILE_MMS); return networkInfo != null && networkInfo.isAvailable(); } private boolean isConnectivityFailure() { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(TYPE_MOBILE_MMS); return networkInfo == null || networkInfo.getDetailedState() == NetworkInfo.DetailedState.FAILED; } private synchronized void issueConnectivityChange() { if (isConnected()) { Log.w("MmsRadio", "Notifying connected..."); notifyAll(); return; } if (!isConnected() && (isConnectivityFailure() || !isConnectivityPossible())) { Log.w("MmsRadio", "Notifying not connected..."); notifyAll(); return; } } private class ConnectivityListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.w("MmsRadio", "Got connectivity change..."); issueConnectivityChange(); } } }
4,389
29.915493
108
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MmsRadioException.java
package org.thoughtcrime.securesms.mms; public class MmsRadioException extends Throwable { public MmsRadioException(String s) { super(s); } }
151
18
50
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/MmsSendResult.java
package org.thoughtcrime.securesms.mms; public class MmsSendResult { private final byte[] messageId; private final int responseStatus; public MmsSendResult(byte[] messageId, int responseStatus) { this.messageId = messageId; this.responseStatus = responseStatus; } public int getResponseStatus() { return responseStatus; } public byte[] getMessageId() { return messageId; } }
422
19.142857
62
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingGroupMediaMessage.java
package org.thoughtcrime.securesms.mms; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.Base64; import org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class OutgoingGroupMediaMessage extends OutgoingSecureMediaMessage { private final GroupContext group; public OutgoingGroupMediaMessage(@NonNull Recipients recipients, @NonNull String encodedGroupContext, @NonNull List<Attachment> avatar, long sentTimeMillis) throws IOException { super(recipients, encodedGroupContext, avatar, sentTimeMillis, ThreadDatabase.DistributionTypes.CONVERSATION); this.group = GroupContext.parseFrom(Base64.decode(encodedGroupContext)); } public OutgoingGroupMediaMessage(@NonNull Recipients recipients, @NonNull GroupContext group, @Nullable final Attachment avatar, long sentTimeMillis) { super(recipients, Base64.encodeBytes(group.toByteArray()), new LinkedList<Attachment>() {{if (avatar != null) add(avatar);}}, System.currentTimeMillis(), ThreadDatabase.DistributionTypes.CONVERSATION); this.group = group; } @Override public boolean isGroup() { return true; } public boolean isGroupUpdate() { return group.getType().getNumber() == GroupContext.Type.UPDATE_VALUE; } public boolean isGroupQuit() { return group.getType().getNumber() == GroupContext.Type.QUIT_VALUE; } public GroupContext getGroupContext() { return group; } }
2,009
31.419355
81
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingLegacyMmsConnection.java
/** * Copyright (C) 2015 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.mms; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPostHC4; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntityHC4; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import java.io.IOException; import ws.com.google.android.mms.pdu.PduParser; import ws.com.google.android.mms.pdu.SendConf; @SuppressWarnings("deprecation") public class OutgoingLegacyMmsConnection extends LegacyMmsConnection implements OutgoingMmsConnection { private final static String TAG = OutgoingLegacyMmsConnection.class.getSimpleName(); public OutgoingLegacyMmsConnection(Context context) throws ApnUnavailableException { super(context); } private HttpUriRequest constructRequest(byte[] pduBytes, boolean useProxy) throws IOException { try { HttpPostHC4 request = new HttpPostHC4(apn.getMmsc()); for (Header header : getBaseHeaders()) { request.addHeader(header); } request.setEntity(new ByteArrayEntityHC4(pduBytes)); if (useProxy) { HttpHost proxy = new HttpHost(apn.getProxy(), apn.getPort()); request.setConfig(RequestConfig.custom().setProxy(proxy).build()); } return request; } catch (IllegalArgumentException iae) { throw new IOException(iae); } } public void sendNotificationReceived(byte[] pduBytes, boolean usingMmsRadio, boolean useProxyIfAvailable) throws IOException { sendBytes(pduBytes, usingMmsRadio, useProxyIfAvailable); } @Override public @Nullable SendConf send(@NonNull byte[] pduBytes) throws UndeliverableMessageException { try { MmsRadio radio = MmsRadio.getInstance(context); if (isCdmaDevice()) { Log.w(TAG, "Sending MMS directly without radio change..."); try { return send(pduBytes, false, false); } catch (IOException e) { Log.w(TAG, e); } } Log.w(TAG, "Sending MMS with radio change and proxy..."); radio.connect(); try { try { return send(pduBytes, true, true); } catch (IOException e) { Log.w(TAG, e); } Log.w(TAG, "Sending MMS with radio change and without proxy..."); try { return send(pduBytes, true, false); } catch (IOException ioe) { Log.w(TAG, ioe); throw new UndeliverableMessageException(ioe); } } finally { radio.disconnect(); } } catch (MmsRadioException e) { Log.w(TAG, e); throw new UndeliverableMessageException(e); } } private SendConf send(byte[] pduBytes, boolean useMmsRadio, boolean useProxyIfAvailable) throws IOException { byte[] response = sendBytes(pduBytes, useMmsRadio, useProxyIfAvailable); return (SendConf) new PduParser(response).parse(); } private byte[] sendBytes(byte[] pduBytes, boolean useMmsRadio, boolean useProxyIfAvailable) throws IOException { final boolean useProxy = useProxyIfAvailable && apn.hasProxy(); final String targetHost = useProxy ? apn.getProxy() : Uri.parse(apn.getMmsc()).getHost(); Log.w(TAG, "Sending MMS of length: " + pduBytes.length + (useMmsRadio ? ", using mms radio" : "") + (useProxy ? ", using proxy" : "")); try { if (checkRouteToHost(context, targetHost, useMmsRadio)) { Log.w(TAG, "got successful route to host " + targetHost); byte[] response = execute(constructRequest(pduBytes, useProxy)); if (response != null) return response; } } catch (IOException ioe) { Log.w(TAG, ioe); } throw new IOException("Connection manager could not obtain route to host."); } public static boolean isConnectionPossible(Context context) { try { ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getNetworkInfo(MmsRadio.TYPE_MOBILE_MMS); if (networkInfo == null) { Log.w(TAG, "MMS network info was null, unsupported by this device"); return false; } getApn(context); return true; } catch (ApnUnavailableException e) { Log.w(TAG, e); return false; } } }
5,447
32.62963
124
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingLollipopMmsConnection.java
/** * Copyright (C) 2015 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.mms; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.telephony.SmsManager; import android.util.Log; import org.thoughtcrime.securesms.providers.MmsBodyProvider; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import org.thoughtcrime.securesms.util.Util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.concurrent.TimeoutException; import ws.com.google.android.mms.pdu.PduParser; import ws.com.google.android.mms.pdu.SendConf; public class OutgoingLollipopMmsConnection extends LollipopMmsConnection implements OutgoingMmsConnection { private static final String TAG = OutgoingLollipopMmsConnection.class.getSimpleName(); private static final String ACTION = OutgoingLollipopMmsConnection.class.getCanonicalName() + "MMS_SENT_ACTION"; private byte[] response; public OutgoingLollipopMmsConnection(Context context) { super(context, ACTION); } @TargetApi(VERSION_CODES.LOLLIPOP_MR1) @Override public synchronized void onResult(Context context, Intent intent) { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP_MR1) { Log.w(TAG, "HTTP status: " + intent.getIntExtra(SmsManager.EXTRA_MMS_HTTP_STATUS, -1)); } response = intent.getByteArrayExtra(SmsManager.EXTRA_MMS_DATA); } @Override @TargetApi(VERSION_CODES.LOLLIPOP) public @Nullable synchronized SendConf send(@NonNull byte[] pduBytes) throws UndeliverableMessageException { beginTransaction(); try { MmsBodyProvider.Pointer pointer = MmsBodyProvider.makeTemporaryPointer(getContext()); Util.copy(new ByteArrayInputStream(pduBytes), pointer.getOutputStream()); SmsManager.getDefault().sendMultimediaMessage(getContext(), pointer.getUri(), null, null, getPendingIntent()); waitForResult(); Log.w(TAG, "MMS broadcast received and processed."); pointer.close(); if (response == null) { throw new UndeliverableMessageException("Null response."); } return (SendConf) new PduParser(response).parse(); } catch (IOException | TimeoutException e) { throw new UndeliverableMessageException(e); } finally { endTransaction(); } } }
3,357
35.5
114
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingMediaMessage.java
package org.thoughtcrime.securesms.mms; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.recipients.Recipients; import java.util.List; public class OutgoingMediaMessage { private final Recipients recipients; protected final String body; protected final List<Attachment> attachments; private final long sentTimeMillis; private final int distributionType; public OutgoingMediaMessage(Recipients recipients, String message, List<Attachment> attachments, long sentTimeMillis, int distributionType) { this.recipients = recipients; this.body = message; this.sentTimeMillis = sentTimeMillis; this.distributionType = distributionType; this.attachments = attachments; } public OutgoingMediaMessage(Recipients recipients, SlideDeck slideDeck, String message, long sentTimeMillis, int distributionType) { this(recipients, message, slideDeck.asAttachments(), sentTimeMillis, distributionType); } public OutgoingMediaMessage(OutgoingMediaMessage that) { this.recipients = that.getRecipients(); this.body = that.body; this.distributionType = that.distributionType; this.attachments = that.attachments; this.sentTimeMillis = that.sentTimeMillis; } public Recipients getRecipients() { return recipients; } public String getBody() { return body; } public List<Attachment> getAttachments() { return attachments; } public int getDistributionType() { return distributionType; } public boolean isSecure() { return false; } public boolean isGroup() { return false; } public long getSentTimeMillis() { return sentTimeMillis; } }
1,847
25.782609
132
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingMmsConnection.java
package org.thoughtcrime.securesms.mms; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.transport.UndeliverableMessageException; import ws.com.google.android.mms.pdu.SendConf; public interface OutgoingMmsConnection { @Nullable SendConf send(@NonNull byte[] pduBytes) throws UndeliverableMessageException; }
386
28.769231
89
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/OutgoingSecureMediaMessage.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.recipients.Recipients; import java.util.List; import ws.com.google.android.mms.pdu.PduBody; public class OutgoingSecureMediaMessage extends OutgoingMediaMessage { public OutgoingSecureMediaMessage(Recipients recipients, String body, List<Attachment> attachments, long sentTimeMillis, int distributionType) { super(recipients, body, attachments, sentTimeMillis, distributionType); } public OutgoingSecureMediaMessage(OutgoingMediaMessage base) { super(base); } @Override public boolean isSecure() { return true; } }
823
25.580645
75
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/PartAuthority.java
package org.thoughtcrime.securesms.mms; import android.content.ContentUris; import android.content.Context; import android.content.UriMatcher; import android.net.Uri; import android.support.annotation.NonNull; import org.thoughtcrime.securesms.attachments.AttachmentId; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.providers.PersistentBlobProvider; import org.thoughtcrime.securesms.providers.PartProvider; import org.thoughtcrime.securesms.providers.SingleUseBlobProvider; import java.io.IOException; import java.io.InputStream; public class PartAuthority { private static final String PART_URI_STRING = "content://org.thoughtcrime.securesms/part"; private static final String THUMB_URI_STRING = "content://org.thoughtcrime.securesms/thumb"; private static final Uri PART_CONTENT_URI = Uri.parse(PART_URI_STRING); private static final Uri THUMB_CONTENT_URI = Uri.parse(THUMB_URI_STRING); private static final int PART_ROW = 1; private static final int THUMB_ROW = 2; private static final int PERSISTENT_ROW = 3; private static final int SINGLE_USE_ROW = 4; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("org.thoughtcrime.securesms", "part/*/#", PART_ROW); uriMatcher.addURI("org.thoughtcrime.securesms", "thumb/*/#", THUMB_ROW); uriMatcher.addURI(PersistentBlobProvider.AUTHORITY, PersistentBlobProvider.EXPECTED_PATH, PERSISTENT_ROW); uriMatcher.addURI(SingleUseBlobProvider.AUTHORITY, SingleUseBlobProvider.PATH, SINGLE_USE_ROW); } public static InputStream getAttachmentStream(@NonNull Context context, @NonNull MasterSecret masterSecret, @NonNull Uri uri) throws IOException { int match = uriMatcher.match(uri); try { switch (match) { case PART_ROW: PartUriParser partUri = new PartUriParser(uri); return DatabaseFactory.getAttachmentDatabase(context).getAttachmentStream(masterSecret, partUri.getPartId()); case THUMB_ROW: partUri = new PartUriParser(uri); return DatabaseFactory.getAttachmentDatabase(context).getThumbnailStream(masterSecret, partUri.getPartId()); case PERSISTENT_ROW: return PersistentBlobProvider.getInstance(context).getStream(masterSecret, ContentUris.parseId(uri)); case SINGLE_USE_ROW: return SingleUseBlobProvider.getInstance().getStream(ContentUris.parseId(uri)); default: return context.getContentResolver().openInputStream(uri); } } catch (SecurityException se) { throw new IOException(se); } } public static Uri getAttachmentPublicUri(Uri uri) { PartUriParser partUri = new PartUriParser(uri); return PartProvider.getContentUri(partUri.getPartId()); } public static Uri getAttachmentDataUri(AttachmentId attachmentId) { Uri uri = Uri.withAppendedPath(PART_CONTENT_URI, String.valueOf(attachmentId.getUniqueId())); return ContentUris.withAppendedId(uri, attachmentId.getRowId()); } public static Uri getAttachmentThumbnailUri(AttachmentId attachmentId) { Uri uri = Uri.withAppendedPath(THUMB_CONTENT_URI, String.valueOf(attachmentId.getUniqueId())); return ContentUris.withAppendedId(uri, attachmentId.getRowId()); } }
3,375
41.2
127
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/PartParser.java
package org.thoughtcrime.securesms.mms; import android.util.Log; import org.thoughtcrime.securesms.util.Util; import java.io.UnsupportedEncodingException; import ws.com.google.android.mms.ContentType; import ws.com.google.android.mms.pdu.CharacterSets; import ws.com.google.android.mms.pdu.PduBody; import ws.com.google.android.mms.pdu.PduPart; public class PartParser { public static String getMessageText(PduBody body) { String bodyText = null; for (int i=0;i<body.getPartsNum();i++) { if (ContentType.isTextType(Util.toIsoString(body.getPart(i).getContentType()))) { String partText; try { String characterSet = CharacterSets.getMimeName(body.getPart(i).getCharset()); if (characterSet.equals(CharacterSets.MIMENAME_ANY_CHARSET)) characterSet = CharacterSets.MIMENAME_ISO_8859_1; if (body.getPart(i).getData() != null) { partText = new String(body.getPart(i).getData(), characterSet); } else { partText = ""; } } catch (UnsupportedEncodingException e) { Log.w("PartParser", e); partText = "Unsupported Encoding!"; } bodyText = (bodyText == null) ? partText : bodyText + " " + partText; } } return bodyText; } public static PduBody getSupportedMediaParts(PduBody body) { PduBody stripped = new PduBody(); for (int i=0;i<body.getPartsNum();i++) { if (isDisplayableMedia(body.getPart(i))) { stripped.addPart(body.getPart(i)); } } return stripped; } public static int getSupportedMediaPartCount(PduBody body) { int partCount = 0; for (int i=0;i<body.getPartsNum();i++) { if (isDisplayableMedia(body.getPart(i))) { partCount++; } } return partCount; } public static boolean isImage(PduPart part) { return ContentType.isImageType(Util.toIsoString(part.getContentType())); } public static boolean isAudio(PduPart part) { return ContentType.isAudioType(Util.toIsoString(part.getContentType())); } public static boolean isVideo(PduPart part) { return ContentType.isVideoType(Util.toIsoString(part.getContentType())); } public static boolean isText(PduPart part) { return ContentType.isTextType(Util.toIsoString(part.getContentType())); } public static boolean isDisplayableMedia(PduPart part) { return isImage(part) || isAudio(part) || isVideo(part); } }
2,469
26.752809
88
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/PartUriParser.java
package org.thoughtcrime.securesms.mms; import android.content.ContentUris; import android.net.Uri; import org.thoughtcrime.securesms.attachments.AttachmentId; public class PartUriParser { private final Uri uri; public PartUriParser(Uri uri) { this.uri = uri; } public AttachmentId getPartId() { return new AttachmentId(getId(), getUniqueId()); } private long getId() { return ContentUris.parseId(uri); } private long getUniqueId() { return Long.parseLong(uri.getPathSegments().get(1)); } }
534
17.448276
59
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/PushMediaConstraints.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import org.thoughtcrime.securesms.util.Util; public class PushMediaConstraints extends MediaConstraints { private static final int MAX_IMAGE_DIMEN_LOWMEM = 768; private static final int MAX_IMAGE_DIMEN = 1280; private static final int KB = 1024; private static final int MB = 1024 * KB; @Override public int getImageMaxWidth(Context context) { return Util.isLowMemory(context) ? MAX_IMAGE_DIMEN_LOWMEM : MAX_IMAGE_DIMEN; } @Override public int getImageMaxHeight(Context context) { return getImageMaxWidth(context); } @Override public int getImageMaxSize() { return 420 * KB; } @Override public int getGifMaxSize() { return 5 * MB; } @Override public int getVideoMaxSize() { return 100 * MB; } @Override public int getAudioMaxSize() { return 100 * MB; } }
951
21.139535
80
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/RoundedCorners.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; import com.bumptech.glide.load.resource.bitmap.TransformationUtils; import org.thoughtcrime.securesms.util.ResUtil; public class RoundedCorners extends BitmapTransformation { private final boolean crop; private final int radius; private final int colorHint; public RoundedCorners(@NonNull Context context, boolean crop, int radius, int colorHint) { super(context); this.crop = crop; this.radius = radius; this.colorHint = colorHint; } public RoundedCorners(@NonNull Context context, int radius) { this(context, true, radius, ResUtil.getColor(context, android.R.attr.windowBackground)); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { final Bitmap toRound = crop ? centerCrop(pool, toTransform, outWidth, outHeight) : fitCenter(pool, toTransform, outWidth, outHeight); final Bitmap rounded = round(pool, toRound); if (toRound != null && toRound != rounded && !pool.put(toRound)) { toRound.recycle(); } return rounded; } private Bitmap centerCrop(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { final Bitmap toReuse = pool.get(outWidth, outHeight, getSafeConfig(toTransform)); final Bitmap transformed = TransformationUtils.centerCrop(toReuse, toTransform, outWidth, outHeight); if (toReuse != null && toReuse != transformed && !pool.put(toReuse)) { toReuse.recycle(); } return transformed; } private Bitmap fitCenter(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return TransformationUtils.fitCenter(toTransform, pool, outWidth, outHeight); } private Bitmap round(@NonNull BitmapPool pool, @Nullable Bitmap toRound) { if (toRound == null) { return null; } final Bitmap result; final Bitmap toReuse = pool.get(toRound.getWidth(), toRound.getHeight(), getSafeConfig(toRound)); if (toReuse != null) { result = toReuse; } else { result = Bitmap.createBitmap(toRound.getWidth(), toRound.getHeight(), getSafeConfig(toRound)); } final Canvas canvas = new Canvas(result); final Paint cornerPaint = new Paint(); final Paint shaderPaint = new Paint(Paint.ANTI_ALIAS_FLAG); shaderPaint.setShader(new BitmapShader(toRound, TileMode.CLAMP, TileMode.CLAMP)); cornerPaint.setColor(colorHint); if (Config.RGB_565.equals(result.getConfig())) { canvas.drawRect(0, 0, radius, radius, cornerPaint); canvas.drawRect(0, toRound.getHeight() - radius, radius, toRound.getHeight(), cornerPaint); canvas.drawRect(toRound.getWidth() - radius, 0, toRound.getWidth(), radius, cornerPaint); canvas.drawRect(toRound.getWidth() - radius, toRound.getHeight() - radius, toRound.getWidth(), toRound.getHeight(), cornerPaint); } canvas.drawRoundRect(new RectF(0, 0, toRound.getWidth(), toRound.getHeight()), radius, radius, shaderPaint); // Log.w("RoundedCorners", "in was " + toRound.getWidth() + "x" + toRound.getHeight() + ", out to " + result.getWidth() + "x" + result.getHeight()); return result; } private static Bitmap.Config getSafeConfig(Bitmap bitmap) { return bitmap.getConfig() != null ? bitmap.getConfig() : Bitmap.Config.ARGB_8888; } @Override public String getId() { return RoundedCorners.class.getCanonicalName(); } }
3,981
39.222222
151
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/Slide.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.content.res.Resources.Theme; import android.net.Uri; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.attachments.UriAttachment; import org.thoughtcrime.securesms.database.AttachmentDatabase; import org.thoughtcrime.securesms.util.MediaUtil; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.io.IOException; public abstract class Slide { protected final Attachment attachment; protected final Context context; public Slide(@NonNull Context context, @NonNull Attachment attachment) { this.context = context; this.attachment = attachment; } public String getContentType() { return attachment.getContentType(); } @Nullable public Uri getUri() { return attachment.getDataUri(); } @Nullable public Uri getThumbnailUri() { return attachment.getThumbnailUri(); } public boolean hasImage() { return false; } public boolean hasVideo() { return false; } public boolean hasAudio() { return false; } public @NonNull String getContentDescription() { return ""; } public Attachment asAttachment() { return attachment; } public boolean isInProgress() { return attachment.isInProgress(); } public boolean isPendingDownload() { return getTransferState() == AttachmentDatabase.TRANSFER_PROGRESS_FAILED || getTransferState() == AttachmentDatabase.TRANSFER_PROGRESS_AUTO_PENDING; } public long getTransferState() { return attachment.getTransferState(); } public @DrawableRes int getPlaceholderRes(Theme theme) { throw new AssertionError("getPlaceholderRes() called for non-drawable slide"); } public boolean hasPlaceholder() { return false; } protected static Attachment constructAttachmentFromUri(@NonNull Context context, @NonNull Uri uri, @NonNull String defaultMime, long size) throws IOException { Optional<String> resolvedType = Optional.fromNullable(MediaUtil.getMimeType(context, uri)); return new UriAttachment(uri, resolvedType.or(defaultMime), AttachmentDatabase.TRANSFER_PROGRESS_STARTED, size); } @Override public boolean equals(Object other) { if (!(other instanceof Slide)) return false; Slide that = (Slide)other; return Util.equals(this.getContentType(), that.getContentType()) && this.hasAudio() == that.hasAudio() && this.hasImage() == that.hasImage() && this.hasVideo() == that.hasVideo() && this.getTransferState() == that.getTransferState() && Util.equals(this.getUri(), that.getUri()) && Util.equals(this.getThumbnailUri(), that.getThumbnailUri()); } @Override public int hashCode() { return Util.hashCode(getContentType(), hasAudio(), hasImage(), hasVideo(), getUri(), getThumbnailUri(), getTransferState()); } }
4,122
30.715385
116
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/SlideClickListener.java
package org.thoughtcrime.securesms.mms; import android.view.View; public interface SlideClickListener { void onClick(View v, Slide slide); }
145
17.25
39
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/SlideDeck.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.util.MediaUtil; import java.util.LinkedList; import java.util.List; public class SlideDeck { private final List<Slide> slides = new LinkedList<>(); public SlideDeck(Context context, List<Attachment> attachments) { for (Attachment attachment : attachments) { Slide slide = MediaUtil.getSlideForAttachment(context, attachment); if (slide != null) slides.add(slide); } } public SlideDeck(Context context, Attachment attachment) { Slide slide = MediaUtil.getSlideForAttachment(context, attachment); if (slide != null) slides.add(slide); } public SlideDeck() { } public void clear() { slides.clear(); } public List<Attachment> asAttachments() { List<Attachment> attachments = new LinkedList<>(); for (Slide slide : slides) { attachments.add(slide.asAttachment()); } return attachments; } public void addSlide(Slide slide) { slides.add(slide); } public List<Slide> getSlides() { return slides; } public boolean containsMediaSlide() { for (Slide slide : slides) { if (slide.hasImage() || slide.hasVideo() || slide.hasAudio()) { return true; } } return false; } public @Nullable Slide getThumbnailSlide() { for (Slide slide : slides) { if (slide.hasImage()) { return slide; } } return null; } public @Nullable AudioSlide getAudioSlide() { for (Slide slide : slides) { if (slide.hasAudio()) { return (AudioSlide)slide; } } return null; } }
2,456
24.071429
73
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/TextSecureGlideModule.java
package org.thoughtcrime.securesms.mms; import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.engine.cache.DiskCache; import com.bumptech.glide.load.engine.cache.DiskCacheAdapter; import com.bumptech.glide.module.GlideModule; import org.thoughtcrime.securesms.mms.AttachmentStreamUriLoader.AttachmentModel; import org.thoughtcrime.securesms.mms.ContactPhotoUriLoader.ContactPhotoUri; import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri; import java.io.InputStream; public class TextSecureGlideModule implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { builder.setDiskCache(new NoopDiskCacheFactory()); } @Override public void registerComponents(Context context, Glide glide) { glide.register(DecryptableUri.class, InputStream.class, new DecryptableStreamUriLoader.Factory()); glide.register(ContactPhotoUri.class, InputStream.class, new ContactPhotoUriLoader.Factory()); glide.register(AttachmentModel.class, InputStream.class, new AttachmentStreamUriLoader.Factory()); } public static class NoopDiskCacheFactory implements DiskCache.Factory { @Override public DiskCache build() { return new DiskCacheAdapter(); } } }
1,334
35.081081
102
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/TextTransport.java
/** * Copyright (C) 2011 Whisper Systems * 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.mms; import org.thoughtcrime.securesms.util.Base64; import java.io.IOException; public class TextTransport { public byte[] getDecodedMessage(byte[] encodedMessageBytes) throws IOException { return Base64.decode(encodedMessageBytes); } public byte[] getEncodedMessage(byte[] messageWithMac) { return Base64.encodeBytes(messageWithMac).getBytes(); } }
1,148
31.828571
82
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/mms/VideoSlide.java
/** * Copyright (C) 2011 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.mms; import android.content.Context; import android.content.res.Resources.Theme; import android.net.Uri; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.util.ResUtil; import java.io.IOException; import ws.com.google.android.mms.ContentType; import ws.com.google.android.mms.pdu.PduPart; public class VideoSlide extends Slide { public VideoSlide(Context context, Uri uri, long dataSize) throws IOException { super(context, constructAttachmentFromUri(context, uri, ContentType.VIDEO_UNSPECIFIED, dataSize)); } public VideoSlide(Context context, Attachment attachment) { super(context, attachment); } @Override @Nullable public Uri getThumbnailUri() { return null; } @Override public boolean hasPlaceholder() { return true; } @Override public @DrawableRes int getPlaceholderRes(Theme theme) { return ResUtil.getDrawableRes(theme, R.attr.conversation_icon_attach_video); } @Override public boolean hasImage() { return true; } @Override public boolean hasVideo() { return true; } @NonNull @Override public String getContentDescription() { return context.getString(R.string.Slide_video); } }
2,123
27.32
102
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/AbstractNotificationBuilder.java
package org.thoughtcrime.securesms.notifications; import android.app.Notification; import android.content.Context; import android.graphics.Color; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.text.SpannableStringBuilder; import android.text.TextUtils; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase; import org.thoughtcrime.securesms.preferences.NotificationPrivacyPreference; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; public abstract class AbstractNotificationBuilder extends NotificationCompat.Builder { protected Context context; protected NotificationPrivacyPreference privacy; public AbstractNotificationBuilder(Context context, NotificationPrivacyPreference privacy) { super(context); this.context = context; this.privacy = privacy; } protected CharSequence getStyledMessage(@NonNull Recipient recipient, @Nullable CharSequence message) { SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(Util.getBoldedString(recipient.toShortString())); builder.append(": "); builder.append(message == null ? "" : message); return builder; } public void setAlarms(@Nullable Uri ringtone, RecipientPreferenceDatabase.VibrateState vibrate) { String defaultRingtoneName = TextSecurePreferences.getNotificationRingtone(context); boolean defaultVibrate = TextSecurePreferences.isNotificationVibrateEnabled(context); String ledColor = TextSecurePreferences.getNotificationLedColor(context); String ledBlinkPattern = TextSecurePreferences.getNotificationLedPattern(context); String ledBlinkPatternCustom = TextSecurePreferences.getNotificationLedPatternCustom(context); String[] blinkPatternArray = parseBlinkPattern(ledBlinkPattern, ledBlinkPatternCustom); if (ringtone != null) setSound(ringtone); else if (!TextUtils.isEmpty(defaultRingtoneName)) setSound(Uri.parse(defaultRingtoneName)); if (vibrate == RecipientPreferenceDatabase.VibrateState.ENABLED || (vibrate == RecipientPreferenceDatabase.VibrateState.DEFAULT && defaultVibrate)) { setDefaults(Notification.DEFAULT_VIBRATE); } if (!ledColor.equals("none")) { setLights(Color.parseColor(ledColor), Integer.parseInt(blinkPatternArray[0]), Integer.parseInt(blinkPatternArray[1])); } } private String[] parseBlinkPattern(String blinkPattern, String blinkPatternCustom) { if (blinkPattern.equals("custom")) blinkPattern = blinkPatternCustom; return blinkPattern.split(","); } }
2,883
39.619718
105
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/FailedNotificationBuilder.java
package org.thoughtcrime.securesms.notifications; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase; import org.thoughtcrime.securesms.preferences.NotificationPrivacyPreference; public class FailedNotificationBuilder extends AbstractNotificationBuilder { public FailedNotificationBuilder(Context context, NotificationPrivacyPreference privacy, Intent intent) { super(context, privacy); setSmallIcon(R.drawable.icon_notification); setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_warning_red)); setContentTitle(context.getString(R.string.MessageNotifier_message_delivery_failed)); setContentText(context.getString(R.string.MessageNotifier_failed_to_deliver_message)); setTicker(context.getString(R.string.MessageNotifier_error_delivering_message)); setContentIntent(PendingIntent.getActivity(context, 0, intent, 0)); setAutoCancel(true); setAlarms(null, RecipientPreferenceDatabase.VibrateState.DEFAULT); } }
1,234
38.83871
107
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/MarkReadReceiver.java
package org.thoughtcrime.securesms.notifications; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; public class MarkReadReceiver extends MasterSecretBroadcastReceiver { private static final String TAG = MarkReadReceiver.class.getSimpleName(); public static final String CLEAR_ACTION = "org.thoughtcrime.securesms.notifications.CLEAR"; public static final String THREAD_IDS_EXTRA = "thread_ids"; @Override protected void onReceive(final Context context, Intent intent, @Nullable final MasterSecret masterSecret) { if (!CLEAR_ACTION.equals(intent.getAction())) return; final long[] threadIds = intent.getLongArrayExtra(THREAD_IDS_EXTRA); if (threadIds != null) { Log.w("TAG", "threadIds length: " + threadIds.length); ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(MessageNotifier.NOTIFICATION_ID); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { for (long threadId : threadIds) { Log.w(TAG, "Marking as read: " + threadId); DatabaseFactory.getThreadDatabase(context).setRead(threadId); } MessageNotifier.updateNotification(context, masterSecret); return null; } }.execute(); } } }
1,713
33.28
98
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/MasterSecretBroadcastReceiver.java
package org.thoughtcrime.securesms.notifications; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.service.KeyCachingService; public abstract class MasterSecretBroadcastReceiver extends BroadcastReceiver { @Override public final void onReceive(Context context, Intent intent) { onReceive(context, intent, KeyCachingService.getMasterSecret(context)); } protected abstract void onReceive(Context context, Intent intent, @Nullable MasterSecret masterSecret); }
664
32.25
105
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/MessageNotifier.java
/** * Copyright (C) 2011 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.notifications; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.StyleSpan; import android.util.Log; import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MmsSmsDatabase; import org.thoughtcrime.securesms.database.PushDatabase; import org.thoughtcrime.securesms.database.SmsDatabase; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord; import org.thoughtcrime.securesms.database.model.MessageRecord; import org.thoughtcrime.securesms.mms.SlideDeck; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.SpanUtil; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.textsecure.api.messages.TextSecureEnvelope; import java.io.IOException; import java.util.List; import java.util.ListIterator; import java.util.concurrent.TimeUnit; import me.leolin.shortcutbadger.ShortcutBadger; /** * Handles posting system notifications for new messages. * * * @author Moxie Marlinspike */ public class MessageNotifier { private static final String TAG = MessageNotifier.class.getSimpleName(); public static final int NOTIFICATION_ID = 1338; private volatile static long visibleThread = -1; public static final String EXTRA_VOICE_REPLY = "extra_voice_reply"; public static void setVisibleThread(long threadId) { visibleThread = threadId; } public static void notifyMessageDeliveryFailed(Context context, Recipients recipients, long threadId) { if (visibleThread == threadId) { sendInThreadNotification(context, recipients); } else { Intent intent = new Intent(context, ConversationActivity.class); intent.putExtra(ConversationActivity.RECIPIENTS_EXTRA, recipients.getIds()); intent.putExtra(ConversationActivity.THREAD_ID_EXTRA, threadId); intent.setData((Uri.parse("custom://" + System.currentTimeMillis()))); FailedNotificationBuilder builder = new FailedNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context), intent); ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify((int)threadId, builder.build()); } } public static void updateNotification(@NonNull Context context, @Nullable MasterSecret masterSecret) { if (!TextSecurePreferences.isNotificationsEnabled(context)) { return; } updateNotification(context, masterSecret, false, false, 0); } public static void updateNotification(@NonNull Context context, @Nullable MasterSecret masterSecret, long threadId) { updateNotification(context, masterSecret, false, threadId); } public static void updateNotification(@NonNull Context context, @Nullable MasterSecret masterSecret, boolean includePushDatabase, long threadId) { boolean isVisible = visibleThread == threadId; ThreadDatabase threads = DatabaseFactory.getThreadDatabase(context); Recipients recipients = DatabaseFactory.getThreadDatabase(context) .getRecipientsForThreadId(threadId); if (isVisible) { threads.setRead(threadId); } if (!TextSecurePreferences.isNotificationsEnabled(context) || (recipients != null && recipients.isMuted())) { return; } if (isVisible) { sendInThreadNotification(context, threads.getRecipientsForThreadId(threadId)); } else { updateNotification(context, masterSecret, true, includePushDatabase, 0); } } private static void updateNotification(@NonNull Context context, @Nullable MasterSecret masterSecret, boolean signal, boolean includePushDatabase, int reminderCount) { Cursor telcoCursor = null; Cursor pushCursor = null; try { telcoCursor = DatabaseFactory.getMmsSmsDatabase(context).getUnread(); pushCursor = DatabaseFactory.getPushDatabase(context).getPending(); if ((telcoCursor == null || telcoCursor.isAfterLast()) && (pushCursor == null || pushCursor.isAfterLast())) { ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(NOTIFICATION_ID); updateBadge(context, 0); clearReminder(context); return; } NotificationState notificationState = constructNotificationState(context, masterSecret, telcoCursor); if (includePushDatabase) { appendPushNotificationState(context, notificationState, pushCursor); } if (notificationState.hasMultipleThreads()) { sendMultipleThreadNotification(context, notificationState, signal); } else { sendSingleThreadNotification(context, masterSecret, notificationState, signal); } updateBadge(context, notificationState.getMessageCount()); if (signal) { scheduleReminder(context, reminderCount); } } finally { if (telcoCursor != null) telcoCursor.close(); if (pushCursor != null) pushCursor.close(); } } private static void sendSingleThreadNotification(@NonNull Context context, @Nullable MasterSecret masterSecret, @NonNull NotificationState notificationState, boolean signal) { if (notificationState.getNotifications().isEmpty()) { ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .cancel(NOTIFICATION_ID); return; } SingleRecipientNotificationBuilder builder = new SingleRecipientNotificationBuilder(context, masterSecret, TextSecurePreferences.getNotificationPrivacy(context)); List<NotificationItem> notifications = notificationState.getNotifications(); builder.setSender(notifications.get(0).getIndividualRecipient()); builder.setMessageCount(notificationState.getMessageCount()); builder.setPrimaryMessageBody(notifications.get(0).getText(), notifications.get(0).getSlideDeck()); builder.setContentIntent(notifications.get(0).getPendingIntent(context)); long timestamp = notifications.get(0).getTimestamp(); if (timestamp != 0) builder.setWhen(timestamp); builder.addActions(masterSecret, notificationState.getMarkAsReadIntent(context), notificationState.getQuickReplyIntent(context, notifications.get(0).getRecipients()), notificationState.getWearableReplyIntent(context, notifications.get(0).getRecipients())); ListIterator<NotificationItem> iterator = notifications.listIterator(notifications.size()); while(iterator.hasPrevious()) { builder.addMessageBody(iterator.previous().getText()); } if (signal) { builder.setAlarms(notificationState.getRingtone(), notificationState.getVibrate()); builder.setTicker(notifications.get(0).getIndividualRecipient(), notifications.get(0).getText()); } ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFICATION_ID, builder.build()); } private static void sendMultipleThreadNotification(@NonNull Context context, @NonNull NotificationState notificationState, boolean signal) { MultipleRecipientNotificationBuilder builder = new MultipleRecipientNotificationBuilder(context, TextSecurePreferences.getNotificationPrivacy(context)); List<NotificationItem> notifications = notificationState.getNotifications(); builder.setMessageCount(notificationState.getMessageCount(), notificationState.getThreadCount()); builder.setMostRecentSender(notifications.get(0).getIndividualRecipient()); long timestamp = notifications.get(0).getTimestamp(); if (timestamp != 0) builder.setWhen(timestamp); builder.addActions(notificationState.getMarkAsReadIntent(context)); ListIterator<NotificationItem> iterator = notifications.listIterator(notifications.size()); while(iterator.hasPrevious()) { NotificationItem item = iterator.previous(); builder.addMessageBody(item.getIndividualRecipient(), item.getText()); } if (signal) { builder.setAlarms(notificationState.getRingtone(), notificationState.getVibrate()); builder.setTicker(notifications.get(0).getText()); } ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFICATION_ID, builder.build()); } private static void sendInThreadNotification(Context context, Recipients recipients) { try { if (!TextSecurePreferences.isInThreadNotifications(context)) { return; } Uri uri = recipients != null ? recipients.getRingtone() : null; if (uri == null) { String ringtone = TextSecurePreferences.getNotificationRingtone(context); if (ringtone == null) { Log.w(TAG, "ringtone preference was null."); return; } else { uri = Uri.parse(ringtone); } } if (uri == null) { Log.w(TAG, "couldn't parse ringtone uri " + TextSecurePreferences.getNotificationRingtone(context)); return; } MediaPlayer player = new MediaPlayer(); player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); player.setDataSource(context, uri); player.setLooping(false); player.setVolume(0.25f, 0.25f); player.prepare(); final AudioManager audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE)); audioManager.requestAudioFocus(null, AudioManager.STREAM_NOTIFICATION, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { audioManager.abandonAudioFocus(null); } }); player.start(); } catch (IOException ioe) { Log.w("MessageNotifier", ioe); } } private static void appendPushNotificationState(@NonNull Context context, @NonNull NotificationState notificationState, @NonNull Cursor cursor) { PushDatabase.Reader reader = null; TextSecureEnvelope envelope; try { reader = DatabaseFactory.getPushDatabase(context).readerFor(cursor); while ((envelope = reader.getNext()) != null) { Recipients recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false); Recipient recipient = recipients.getPrimaryRecipient(); long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients); SpannableString body = new SpannableString(context.getString(R.string.MessageNotifier_locked_message)); body.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, body.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (!recipients.isMuted()) { notificationState.addNotification(new NotificationItem(recipient, recipients, null, threadId, body, 0, null)); } } } finally { if (reader != null) reader.close(); } } private static NotificationState constructNotificationState(@NonNull Context context, @Nullable MasterSecret masterSecret, @NonNull Cursor cursor) { NotificationState notificationState = new NotificationState(); MessageRecord record; MmsSmsDatabase.Reader reader; if (masterSecret == null) reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor); else reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor, masterSecret); while ((record = reader.getNext()) != null) { Recipient recipient = record.getIndividualRecipient(); Recipients recipients = record.getRecipients(); long threadId = record.getThreadId(); CharSequence body = record.getDisplayBody(); Recipients threadRecipients = null; SlideDeck slideDeck = null; long timestamp; if (record.isPush()) timestamp = record.getDateSent(); else timestamp = record.getDateReceived(); if (threadId != -1) { threadRecipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId); } if (SmsDatabase.Types.isDecryptInProgressType(record.getType()) || !record.getBody().isPlaintext()) { body = SpanUtil.italic(context.getString(R.string.MessageNotifier_locked_message)); } else if (record.isMms() && TextUtils.isEmpty(body)) { body = SpanUtil.italic(context.getString(R.string.MessageNotifier_media_message)); slideDeck = ((MediaMmsMessageRecord)record).getSlideDeck(); } else if (record.isMms() && !record.isMmsNotification()) { String message = context.getString(R.string.MessageNotifier_media_message_with_text, body); int italicLength = message.length() - body.length(); body = SpanUtil.italic(message, italicLength); slideDeck = ((MediaMmsMessageRecord)record).getSlideDeck(); } if (threadRecipients == null || !threadRecipients.isMuted()) { notificationState.addNotification(new NotificationItem(recipient, recipients, threadRecipients, threadId, body, timestamp, slideDeck)); } } reader.close(); return notificationState; } private static void updateBadge(Context context, int count) { try { ShortcutBadger.setBadge(context.getApplicationContext(), count); } catch (Throwable t) { // NOTE :: I don't totally trust this thing, so I'm catching // everything. Log.w("MessageNotifier", t); } } private static void scheduleReminder(Context context, int count) { if (count >= TextSecurePreferences.getRepeatAlertsCount(context)) { return; } AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION); alarmIntent.putExtra("reminder_count", count); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); long timeout = TimeUnit.MINUTES.toMillis(2); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, pendingIntent); } private static void clearReminder(Context context) { Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); } public static class ReminderReceiver extends BroadcastReceiver { public static final String REMINDER_ACTION = "org.thoughtcrime.securesms.MessageNotifier.REMINDER_ACTION"; @Override public void onReceive(final Context context, final Intent intent) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { MasterSecret masterSecret = KeyCachingService.getMasterSecret(context); int reminderCount = intent.getIntExtra("reminder_count", 0); MessageNotifier.updateNotification(context, masterSecret, true, true, reminderCount + 1); return null; } }.execute(); } } public static class DeleteReceiver extends BroadcastReceiver { public static final String DELETE_REMINDER_ACTION = "org.thoughtcrime.securesms.MessageNotifier.DELETE_REMINDER_ACTION"; @Override public void onReceive(Context context, Intent intent) { clearReminder(context); } } }
18,219
39.488889
172
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/MultipleRecipientNotificationBuilder.java
package org.thoughtcrime.securesms.notifications; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import org.thoughtcrime.securesms.ConversationListActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.preferences.NotificationPrivacyPreference; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.Util; import java.util.LinkedList; import java.util.List; public class MultipleRecipientNotificationBuilder extends AbstractNotificationBuilder { private final List<CharSequence> messageBodies = new LinkedList<>(); public MultipleRecipientNotificationBuilder(Context context, NotificationPrivacyPreference privacy) { super(context, privacy); setColor(context.getResources().getColor(R.color.textsecure_primary)); setSmallIcon(R.drawable.icon_notification); setContentTitle(context.getString(R.string.app_name)); setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, ConversationListActivity.class), 0)); setCategory(NotificationCompat.CATEGORY_MESSAGE); setPriority(NotificationCompat.PRIORITY_HIGH); setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(MessageNotifier.DeleteReceiver.DELETE_REMINDER_ACTION), 0)); } public void setMessageCount(int messageCount, int threadCount) { setSubText(context.getString(R.string.MessageNotifier_d_new_messages_in_d_conversations, messageCount, threadCount)); setContentInfo(String.valueOf(messageCount)); setNumber(messageCount); } public void setMostRecentSender(Recipient recipient) { if (privacy.isDisplayContact()) { setContentText(context.getString(R.string.MessageNotifier_most_recent_from_s, recipient.toShortString())); } } public void addActions(PendingIntent markAsReadIntent) { NotificationCompat.Action markAllAsReadAction = new NotificationCompat.Action(R.drawable.check, context.getString(R.string.MessageNotifier_mark_all_as_read), markAsReadIntent); addAction(markAllAsReadAction); extend(new NotificationCompat.WearableExtender().addAction(markAllAsReadAction)); } public void addMessageBody(@NonNull Recipient sender, @Nullable CharSequence body) { if (privacy.isDisplayMessage()) { messageBodies.add(getStyledMessage(sender, body)); } else if (privacy.isDisplayContact()) { messageBodies.add(Util.getBoldedString(sender.toShortString())); } if (privacy.isDisplayContact() && sender.getContactUri() != null) { addPerson(sender.getContactUri().toString()); } } @Override public Notification build() { if (privacy.isDisplayMessage() || privacy.isDisplayContact()) { NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); for (CharSequence body : messageBodies) { style.addLine(body); } setStyle(style); } return super.build(); } }
3,284
37.647059
130
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/NotificationItem.java
package org.thoughtcrime.securesms.notifications; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.mms.SlideDeck; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.ListenableFutureTask; import org.thoughtcrime.securesms.util.concurrent.ListenableFuture; public class NotificationItem { private final Recipients recipients; private final Recipient individualRecipient; private final Recipients threadRecipients; private final long threadId; private final CharSequence text; private final long timestamp; private final @Nullable SlideDeck slideDeck; public NotificationItem(Recipient individualRecipient, Recipients recipients, Recipients threadRecipients, long threadId, CharSequence text, long timestamp, @Nullable SlideDeck slideDeck) { this.individualRecipient = individualRecipient; this.recipients = recipients; this.threadRecipients = threadRecipients; this.text = text; this.threadId = threadId; this.timestamp = timestamp; this.slideDeck = slideDeck; } public Recipients getRecipients() { return threadRecipients == null ? recipients : threadRecipients; } public Recipient getIndividualRecipient() { return individualRecipient; } public CharSequence getText() { return text; } public long getTimestamp() { return timestamp; } public long getThreadId() { return threadId; } public @Nullable SlideDeck getSlideDeck() { return slideDeck; } public PendingIntent getPendingIntent(Context context) { Intent intent = new Intent(context, ConversationActivity.class); Recipients notifyRecipients = threadRecipients != null ? threadRecipients : recipients; if (notifyRecipients != null) intent.putExtra("recipients", notifyRecipients.getIds()); intent.putExtra("thread_id", threadId); intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } }
2,563
32.298701
92
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/NotificationState.java
package org.thoughtcrime.securesms.notifications; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.ConversationActivity; import org.thoughtcrime.securesms.ConversationPopupActivity; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.VibrateState; import org.thoughtcrime.securesms.recipients.Recipients; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; public class NotificationState { private final LinkedList<NotificationItem> notifications = new LinkedList<>(); private final Set<Long> threads = new HashSet<>(); private int notificationCount = 0; public void addNotification(NotificationItem item) { notifications.addFirst(item); threads.add(item.getThreadId()); notificationCount++; } public @Nullable Uri getRingtone() { if (!notifications.isEmpty()) { Recipients recipients = notifications.getFirst().getRecipients(); if (recipients != null) { return recipients.getRingtone(); } } return null; } public VibrateState getVibrate() { if (!notifications.isEmpty()) { Recipients recipients = notifications.getFirst().getRecipients(); if (recipients != null) { return recipients.getVibrate(); } } return VibrateState.DEFAULT; } public boolean hasMultipleThreads() { return threads.size() > 1; } public int getThreadCount() { return threads.size(); } public int getMessageCount() { return notificationCount; } public List<NotificationItem> getNotifications() { return notifications; } public PendingIntent getMarkAsReadIntent(Context context) { long[] threadArray = new long[threads.size()]; int index = 0; for (long thread : threads) { Log.w("NotificationState", "Added thread: " + thread); threadArray[index++] = thread; } Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION); intent.putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, threadArray); intent.setPackage(context.getPackageName()); // XXX : This is an Android bug. If we don't pull off the extra // once before handing off the PendingIntent, the array will be // truncated to one element when the PendingIntent fires. Thanks guys! Log.w("NotificationState", "Pending array off intent length: " + intent.getLongArrayExtra("thread_ids").length); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public PendingIntent getWearableReplyIntent(Context context, Recipients recipients) { if (threads.size() != 1) throw new AssertionError("We only support replies to single thread notifications!"); Intent intent = new Intent(WearReplyReceiver.REPLY_ACTION); intent.putExtra(WearReplyReceiver.RECIPIENT_IDS_EXTRA, recipients.getIds()); intent.setPackage(context.getPackageName()); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public PendingIntent getQuickReplyIntent(Context context, Recipients recipients) { if (threads.size() != 1) throw new AssertionError("We only support replies to single thread notifications!"); Intent intent = new Intent(context, ConversationPopupActivity.class); intent.putExtra(ConversationActivity.RECIPIENTS_EXTRA, recipients.getIds()); intent.putExtra(ConversationActivity.THREAD_ID_EXTRA, (long)threads.toArray()[0]); intent.setData((Uri.parse("custom://"+System.currentTimeMillis()))); return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } }
3,841
31.559322
113
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/SingleRecipientNotificationBuilder.java
package org.thoughtcrime.securesms.notifications; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat.Action; import android.support.v4.app.RemoteInput; import android.text.SpannableStringBuilder; import com.bumptech.glide.Glide; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader; import org.thoughtcrime.securesms.mms.Slide; import org.thoughtcrime.securesms.mms.SlideDeck; import org.thoughtcrime.securesms.preferences.NotificationPrivacyPreference; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.util.BitmapUtil; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; public class SingleRecipientNotificationBuilder extends AbstractNotificationBuilder { private static final String TAG = SingleRecipientNotificationBuilder.class.getSimpleName(); private final List<CharSequence> messageBodies = new LinkedList<>(); private SlideDeck slideDeck; private final MasterSecret masterSecret; public SingleRecipientNotificationBuilder(@NonNull Context context, @Nullable MasterSecret masterSecret, @NonNull NotificationPrivacyPreference privacy) { super(context, privacy); this.masterSecret = masterSecret; setSmallIcon(R.drawable.icon_notification); setColor(context.getResources().getColor(R.color.textsecure_primary)); setPriority(NotificationCompat.PRIORITY_HIGH); setCategory(NotificationCompat.CATEGORY_MESSAGE); setDeleteIntent(PendingIntent.getBroadcast(context, 0, new Intent(MessageNotifier.DeleteReceiver.DELETE_REMINDER_ACTION), 0)); } public void setSender(@NonNull Recipient recipient) { if (privacy.isDisplayContact()) { setContentTitle(recipient.toShortString()); if (recipient.getContactUri() != null) { addPerson(recipient.getContactUri().toString()); } setLargeIcon(recipient.getContactPhoto() .asDrawable(context, recipient.getColor() .toConversationColor(context))); } else { setContentTitle(context.getString(R.string.SingleRecipientNotificationBuilder_new_signal_message)); setLargeIcon(Recipient.getUnknownRecipient() .getContactPhoto() .asDrawable(context, Recipient.getUnknownRecipient() .getColor() .toConversationColor(context))); } } public void setMessageCount(int messageCount) { setContentInfo(String.valueOf(messageCount)); setNumber(messageCount); } public void setPrimaryMessageBody(CharSequence message, @Nullable SlideDeck slideDeck) { if (privacy.isDisplayMessage()) { setContentText(message); this.slideDeck = slideDeck; } else { setContentText(context.getString(R.string.SingleRecipientNotificationBuilder_contents_hidden)); } } public void addActions(@Nullable MasterSecret masterSecret, @NonNull PendingIntent markReadIntent, @NonNull PendingIntent quickReplyIntent, @NonNull PendingIntent wearableReplyIntent) { Action markAsReadAction = new Action(R.drawable.check, context.getString(R.string.MessageNotifier_mark_read), markReadIntent); if (masterSecret != null) { Action replyAction = new Action(R.drawable.ic_reply_white_36dp, context.getString(R.string.MessageNotifier_reply), quickReplyIntent); Action wearableReplyAction = new Action.Builder(R.drawable.ic_reply, context.getString(R.string.MessageNotifier_reply), wearableReplyIntent) .addRemoteInput(new RemoteInput.Builder(MessageNotifier.EXTRA_VOICE_REPLY) .setLabel(context.getString(R.string.MessageNotifier_reply)).build()) .build(); addAction(markAsReadAction); addAction(replyAction); extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction) .addAction(wearableReplyAction)); } else { addAction(markAsReadAction); extend(new NotificationCompat.WearableExtender().addAction(markAsReadAction)); } } public void addMessageBody(@Nullable CharSequence messageBody) { if (privacy.isDisplayMessage()) { messageBodies.add(messageBody == null ? "" : messageBody); } } public void setTicker(@NonNull Recipient recipient, @Nullable CharSequence message) { if (privacy.isDisplayMessage()) { setTicker(getStyledMessage(recipient, message)); } else if (privacy.isDisplayContact()) { setTicker(getStyledMessage(recipient, context.getString(R.string.SingleRecipientNotificationBuilder_new_signal_message))); } else { setTicker(context.getString(R.string.SingleRecipientNotificationBuilder_new_signal_message)); } } @Override public Notification build() { if (privacy.isDisplayMessage()) { if (messageBodies.size() == 1 && hasBigPictureSlide(slideDeck)) { assert masterSecret != null; setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(getBigPicture(masterSecret, slideDeck)) .setSummaryText(getBigText(messageBodies))); } else { setStyle(new NotificationCompat.BigTextStyle().bigText(getBigText(messageBodies))); } } return super.build(); } private void setLargeIcon(@Nullable Drawable drawable) { if (drawable != null) { int largeIconTargetSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_target_size); Bitmap recipientPhotoBitmap = BitmapUtil.createFromDrawable(drawable, largeIconTargetSize, largeIconTargetSize); if (recipientPhotoBitmap != null) { setLargeIcon(recipientPhotoBitmap); } } } private boolean hasBigPictureSlide(@Nullable SlideDeck slideDeck) { if (masterSecret == null || slideDeck == null || Build.VERSION.SDK_INT < 16) { return false; } Slide thumbnailSlide = slideDeck.getThumbnailSlide(); return thumbnailSlide != null && thumbnailSlide.hasImage() && !thumbnailSlide.isInProgress() && thumbnailSlide.getThumbnailUri() != null; } private Bitmap getBigPicture(@NonNull MasterSecret masterSecret, @NonNull SlideDeck slideDeck) { try { @SuppressWarnings("ConstantConditions") Uri uri = slideDeck.getThumbnailSlide().getThumbnailUri(); return Glide.with(context) .load(new DecryptableStreamUriLoader.DecryptableUri(masterSecret, uri)) .asBitmap() .into(500, 500) .get(); } catch (InterruptedException | ExecutionException e) { throw new AssertionError(e); } } private CharSequence getBigText(List<CharSequence> messageBodies) { SpannableStringBuilder content = new SpannableStringBuilder(); for (CharSequence message : messageBodies) { content.append(message); content.append('\n'); } return content; } }
8,052
37.5311
130
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/notifications/WearReplyReceiver.java
/** * Copyright (C) 2011 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.notifications; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.RemoteInput; import org.thoughtcrime.securesms.attachments.Attachment; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.mms.OutgoingMediaMessage; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.sms.MessageSender; import org.thoughtcrime.securesms.sms.OutgoingTextMessage; import java.util.LinkedList; import ws.com.google.android.mms.pdu.PduBody; /** * Get the response text from the Wearable Device and sends an message as a reply */ public class WearReplyReceiver extends MasterSecretBroadcastReceiver { public static final String TAG = WearReplyReceiver.class.getSimpleName(); public static final String REPLY_ACTION = "org.thoughtcrime.securesms.notifications.WEAR_REPLY"; public static final String RECIPIENT_IDS_EXTRA = "recipient_ids"; @Override protected void onReceive(final Context context, Intent intent, final @Nullable MasterSecret masterSecret) { if (!REPLY_ACTION.equals(intent.getAction())) return; Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput == null) return; final long[] recipientIds = intent.getLongArrayExtra(RECIPIENT_IDS_EXTRA); final CharSequence responseText = remoteInput.getCharSequence(MessageNotifier.EXTRA_VOICE_REPLY); final Recipients recipients = RecipientFactory.getRecipientsForIds(context, recipientIds, false); if (masterSecret != null && responseText != null) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { long threadId; if (recipients.isGroupRecipient()) { OutgoingMediaMessage reply = new OutgoingMediaMessage(recipients, responseText.toString(), new LinkedList<Attachment>(), System.currentTimeMillis(), 0); threadId = MessageSender.send(context, masterSecret, reply, -1, false); } else { OutgoingTextMessage reply = new OutgoingTextMessage(recipients, responseText.toString()); threadId = MessageSender.send(context, masterSecret, reply, -1, false); } DatabaseFactory.getThreadDatabase(context).setRead(threadId); MessageNotifier.updateNotification(context, masterSecret); return null; } }.execute(); } } }
3,454
38.712644
164
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/AdvancedPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.preference.PreferenceFragment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore; import org.thoughtcrime.redphone.signaling.UnauthorizedException; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.LogSubmitActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.RegistrationActivity; import org.thoughtcrime.securesms.contacts.ContactAccessor; import org.thoughtcrime.securesms.contacts.ContactIdentityManager; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory; import org.thoughtcrime.securesms.util.ProgressDialogAsyncTask; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.AuthorizationFailedException; import java.io.IOException; public class AdvancedPreferenceFragment extends PreferenceFragment { private static final String TAG = AdvancedPreferenceFragment.class.getSimpleName(); private static final String PUSH_MESSAGING_PREF = "pref_toggle_push_messaging"; private static final String SUBMIT_DEBUG_LOG_PREF = "pref_submit_debug_logs"; private static final int PICK_IDENTITY_CONTACT = 1; private MasterSecret masterSecret; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); masterSecret = getArguments().getParcelable("master_secret"); addPreferencesFromResource(R.xml.preferences_advanced); initializePushMessagingToggle(); initializeIdentitySelection(); Preference submitDebugLog = this.findPreference(SUBMIT_DEBUG_LOG_PREF); submitDebugLog.setOnPreferenceClickListener(new SubmitDebugLogListener()); submitDebugLog.setSummary(getVersion(getActivity())); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__advanced); } @Override public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data); Log.w(TAG, "Got result: " + resultCode + " for req: " + reqCode); if (resultCode == Activity.RESULT_OK && reqCode == PICK_IDENTITY_CONTACT) { handleIdentitySelection(data); } } private void initializePushMessagingToggle() { CheckBoxPreference preference = (CheckBoxPreference)this.findPreference(PUSH_MESSAGING_PREF); preference.setChecked(TextSecurePreferences.isPushRegistered(getActivity())); preference.setOnPreferenceChangeListener(new PushMessagingClickListener()); } private void initializeIdentitySelection() { ContactIdentityManager identity = ContactIdentityManager.getInstance(getActivity()); Preference preference = this.findPreference(TextSecurePreferences.IDENTITY_PREF); if (identity.isSelfIdentityAutoDetected()) { this.getPreferenceScreen().removePreference(preference); } else { Uri contactUri = identity.getSelfIdentityUri(); if (contactUri != null) { String contactName = ContactAccessor.getInstance().getNameFromContact(getActivity(), contactUri); preference.setSummary(String.format(getString(R.string.ApplicationPreferencesActivity_currently_s), contactName)); } preference.setOnPreferenceClickListener(new IdentityPreferenceClickListener()); } } private @NonNull String getVersion(@Nullable Context context) { try { if (context == null) return ""; String app = context.getString(R.string.app_name); String version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; return String.format("%s %s", app, version); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, e); return context.getString(R.string.app_name); } } private class IdentityPreferenceClickListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForResult(intent, PICK_IDENTITY_CONTACT); return true; } } private void handleIdentitySelection(Intent data) { Uri contactUri = data.getData(); if (contactUri != null) { TextSecurePreferences.setIdentityContactUri(getActivity(), contactUri.toString()); initializeIdentitySelection(); } } private class SubmitDebugLogListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { final Intent intent = new Intent(getActivity(), LogSubmitActivity.class); startActivity(intent); return true; } } private class PushMessagingClickListener implements Preference.OnPreferenceChangeListener { private static final int SUCCESS = 0; private static final int NETWORK_ERROR = 1; private class DisablePushMessagesTask extends ProgressDialogAsyncTask<Void, Void, Integer> { private final CheckBoxPreference checkBoxPreference; public DisablePushMessagesTask(final CheckBoxPreference checkBoxPreference) { super(getActivity(), R.string.ApplicationPreferencesActivity_unregistering, R.string.ApplicationPreferencesActivity_unregistering_from_signal_messages_and_calls); this.checkBoxPreference = checkBoxPreference; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); switch (result) { case NETWORK_ERROR: Toast.makeText(getActivity(), R.string.ApplicationPreferencesActivity_error_connecting_to_server, Toast.LENGTH_LONG).show(); break; case SUCCESS: checkBoxPreference.setChecked(false); TextSecurePreferences.setPushRegistered(getActivity(), false); break; } } @Override protected Integer doInBackground(Void... params) { try { Context context = getActivity(); TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context); RedPhoneAccountManager redPhoneAccountManager = new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL, new RedPhoneTrustStore(context), TextSecurePreferences.getLocalNumber(context), TextSecurePreferences.getPushServerPassword(context)); try { accountManager.setGcmId(Optional.<String>absent()); } catch (AuthorizationFailedException e) { Log.w(TAG, e); } try { redPhoneAccountManager.setGcmId(Optional.<String>absent()); } catch (UnauthorizedException e) { Log.w(TAG, e); } GoogleCloudMessaging.getInstance(context).unregister(); return SUCCESS; } catch (IOException ioe) { Log.w(TAG, ioe); return NETWORK_ERROR; } } } @Override public boolean onPreferenceChange(final Preference preference, Object newValue) { if (((CheckBoxPreference)preference).isChecked()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIconAttribute(R.attr.dialog_info_icon); builder.setTitle(R.string.ApplicationPreferencesActivity_disable_signal_messages_and_calls); builder.setMessage(R.string.ApplicationPreferencesActivity_disable_signal_messages_and_calls_by_unregistering); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new DisablePushMessagesTask((CheckBoxPreference)preference).execute(); } }); builder.show(); } else { Intent nextIntent = new Intent(getActivity(), ApplicationPreferencesActivity.class); Intent intent = new Intent(getActivity(), RegistrationActivity.class); intent.putExtra("cancel_button", true); intent.putExtra("next_intent", nextIntent); intent.putExtra("master_secret", masterSecret); startActivity(intent); } return false; } } }
9,639
39.334728
170
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/AdvancedRingtonePreference.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.net.Uri; import android.preference.RingtonePreference; import android.util.AttributeSet; public class AdvancedRingtonePreference extends RingtonePreference { private Uri currentRingtone; public AdvancedRingtonePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public AdvancedRingtonePreference(Context context, AttributeSet attrs) { super(context, attrs); } public AdvancedRingtonePreference(Context context) { super(context); } @Override protected Uri onRestoreRingtone() { return currentRingtone; } public void setCurrentRingtone(Uri uri) { currentRingtone = uri; } }
773
23.1875
92
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/AppProtectionPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceScreen; import android.support.v4.preference.PreferenceFragment; import android.support.v7.app.AlertDialog; import android.widget.Toast; import com.doomonafireball.betterpickers.hmspicker.HmsPickerBuilder; import com.doomonafireball.betterpickers.hmspicker.HmsPickerDialogFragment; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.BlockedContactsActivity; import org.thoughtcrime.securesms.PassphraseChangeActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.TextSecurePreferences; import java.util.concurrent.TimeUnit; public class AppProtectionPreferenceFragment extends PreferenceFragment { private static final String PREFERENCE_CATEGORY_BLOCKED = "preference_category_blocked"; private MasterSecret masterSecret; private CheckBoxPreference disablePassphrase; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_app_protection); masterSecret = getArguments().getParcelable("master_secret"); disablePassphrase = (CheckBoxPreference) this.findPreference("pref_enable_passphrase_temporary"); this.findPreference(TextSecurePreferences.CHANGE_PASSPHRASE_PREF) .setOnPreferenceClickListener(new ChangePassphraseClickListener()); this.findPreference(TextSecurePreferences.PASSPHRASE_TIMEOUT_INTERVAL_PREF) .setOnPreferenceClickListener(new PassphraseIntervalClickListener()); this.findPreference(PREFERENCE_CATEGORY_BLOCKED) .setOnPreferenceClickListener(new BlockedContactsClickListener()); disablePassphrase .setOnPreferenceChangeListener(new DisablePassphraseClickListener()); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__privacy); initializePlatformSpecificOptions(); initializeTimeoutSummary(); disablePassphrase.setChecked(!TextSecurePreferences.isPasswordDisabled(getActivity())); } private void initializePlatformSpecificOptions() { PreferenceScreen preferenceScreen = getPreferenceScreen(); Preference screenSecurityPreference = findPreference(TextSecurePreferences.SCREEN_SECURITY_PREF); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH && screenSecurityPreference != null) { preferenceScreen.removePreference(screenSecurityPreference); } } private void initializeTimeoutSummary() { int timeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(getActivity()); this.findPreference(TextSecurePreferences.PASSPHRASE_TIMEOUT_INTERVAL_PREF) .setSummary(getString(R.string.AppProtectionPreferenceFragment_minutes, timeoutMinutes)); } private class BlockedContactsClickListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(getActivity(), BlockedContactsActivity.class); startActivity(intent); return true; } } private class ChangePassphraseClickListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { if (MasterSecretUtil.isPassphraseInitialized(getActivity())) { startActivity(new Intent(getActivity(), PassphraseChangeActivity.class)); } else { Toast.makeText(getActivity(), R.string.ApplicationPreferenceActivity_you_havent_set_a_passphrase_yet, Toast.LENGTH_LONG).show(); } return true; } } private class PassphraseIntervalClickListener implements Preference.OnPreferenceClickListener, HmsPickerDialogFragment.HmsPickerDialogHandler { @Override public boolean onPreferenceClick(Preference preference) { int[] attributes = {R.attr.app_protect_timeout_picker_color}; TypedArray hmsStyle = getActivity().obtainStyledAttributes(attributes); new HmsPickerBuilder().setFragmentManager(getFragmentManager()) .setStyleResId(hmsStyle.getResourceId(0, R.style.BetterPickersDialogFragment_Light)) .addHmsPickerDialogHandler(this) .show(); hmsStyle.recycle(); return true; } @Override public void onDialogHmsSet(int reference, int hours, int minutes, int seconds) { int timeoutMinutes = Math.max((int)TimeUnit.HOURS.toMinutes(hours) + minutes + (int)TimeUnit.SECONDS.toMinutes(seconds), 1); TextSecurePreferences.setPassphraseTimeoutInterval(getActivity(), timeoutMinutes); initializeTimeoutSummary(); } } private class DisablePassphraseClickListener implements Preference.OnPreferenceChangeListener { @Override public boolean onPreferenceChange(final Preference preference, Object newValue) { if (((CheckBoxPreference)preference).isChecked()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.ApplicationPreferencesActivity_disable_passphrase); builder.setMessage(R.string.ApplicationPreferencesActivity_disable_lock_screen); builder.setIconAttribute(R.attr.dialog_alert_icon); builder.setPositiveButton(R.string.ApplicationPreferencesActivity_disable, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MasterSecretUtil.changeMasterSecretPassphrase(getActivity(), masterSecret, MasterSecretUtil.UNENCRYPTED_PASSPHRASE); TextSecurePreferences.setPasswordDisabled(getActivity(), true); ((CheckBoxPreference)preference).setChecked(false); Intent intent = new Intent(getActivity(), KeyCachingService.class); intent.setAction(KeyCachingService.DISABLE_ACTION); getActivity().startService(intent); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } else { Intent intent = new Intent(getActivity(), PassphraseChangeActivity.class); startActivity(intent); } return false; } } private static CharSequence getPassphraseSummary(Context context) { final int passphraseResId = R.string.preferences__passphrase_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isPasswordDisabled(context)) { return context.getString(passphraseResId, offRes); } else { return context.getString(passphraseResId, onRes); } } private static CharSequence getScreenSecuritySummary(Context context) { final int screenSecurityResId = R.string.preferences__screen_security_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isScreenSecurityEnabled(context)) { return context.getString(screenSecurityResId, onRes); } else { return context.getString(screenSecurityResId, offRes); } } public static CharSequence getSummary(Context context) { return getPassphraseSummary(context) + ", " + getScreenSecuritySummary(context); } }
8,298
41.126904
145
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/AppearancePreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.os.Bundle; import android.preference.ListPreference; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.TextSecurePreferences; import java.util.Arrays; public class AppearancePreferenceFragment extends ListSummaryPreferenceFragment { @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_appearance); this.findPreference(TextSecurePreferences.THEME_PREF).setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(TextSecurePreferences.LANGUAGE_PREF).setOnPreferenceChangeListener(new ListSummaryListener()); initializeListSummary((ListPreference)findPreference(TextSecurePreferences.THEME_PREF)); initializeListSummary((ListPreference)findPreference(TextSecurePreferences.LANGUAGE_PREF)); } @Override public void onStart() { super.onStart(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener((ApplicationPreferencesActivity)getActivity()); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__appearance); } @Override public void onStop() { super.onStop(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener((ApplicationPreferencesActivity) getActivity()); } public static CharSequence getSummary(Context context) { String[] languageEntries = context.getResources().getStringArray(R.array.language_entries); String[] languageEntryValues = context.getResources().getStringArray(R.array.language_values); String[] themeEntries = context.getResources().getStringArray(R.array.pref_theme_entries); String[] themeEntryValues = context.getResources().getStringArray(R.array.pref_theme_values); int langIndex = Arrays.asList(languageEntryValues).indexOf(TextSecurePreferences.getLanguage(context)); int themeIndex = Arrays.asList(themeEntryValues).indexOf(TextSecurePreferences.getTheme(context)); if (langIndex == -1) langIndex = 0; if (themeIndex == -1) themeIndex = 0; return context.getString(R.string.preferences__theme_summary, themeEntries[themeIndex]) + ", " + context.getString(R.string.preferences__language_summary, languageEntries[langIndex]); } }
2,564
41.75
140
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/BlockedContactListItem.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; import android.widget.TextView; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.components.AvatarImageView; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.Util; public class BlockedContactListItem extends RelativeLayout implements Recipients.RecipientsModifiedListener { private AvatarImageView contactPhotoImage; private TextView nameView; private Recipients recipients; public BlockedContactListItem(Context context) { super(context); } public BlockedContactListItem(Context context, AttributeSet attrs) { super(context, attrs); } public BlockedContactListItem(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void onFinishInflate() { super.onFinishInflate(); this.contactPhotoImage = (AvatarImageView)findViewById(R.id.contact_photo_image); this.nameView = (TextView) findViewById(R.id.name); } public void set(Recipients recipients) { this.recipients = recipients; onModified(recipients); recipients.addListener(this); } @Override public void onModified(final Recipients recipients) { final AvatarImageView contactPhotoImage = this.contactPhotoImage; final TextView nameView = this.nameView; Util.runOnMain(new Runnable() { @Override public void run() { contactPhotoImage.setAvatar(recipients, false); nameView.setText(recipients.toShortString()); } }); } public Recipients getRecipients() { return recipients; } }
1,791
27.444444
109
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/ChatsPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.support.v4.preference.PreferenceFragment; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Trimmer; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ChatsPreferenceFragment extends PreferenceFragment { private static final String TAG = ChatsPreferenceFragment.class.getSimpleName(); @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_chats); findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_MOBILE_PREF) .setOnPreferenceChangeListener(new MediaDownloadChangeListener()); findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_WIFI_PREF) .setOnPreferenceChangeListener(new MediaDownloadChangeListener()); findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_ROAMING_PREF) .setOnPreferenceChangeListener(new MediaDownloadChangeListener()); findPreference(TextSecurePreferences.THREAD_TRIM_NOW) .setOnPreferenceClickListener(new TrimNowClickListener()); findPreference(TextSecurePreferences.THREAD_TRIM_LENGTH) .setOnPreferenceChangeListener(new TrimLengthValidationListener()); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity)getActivity()).getSupportActionBar().setTitle(R.string.preferences__chats); setMediaDownloadSummaries(); } private void setMediaDownloadSummaries() { findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_MOBILE_PREF) .setSummary(getSummaryForMediaPreference(TextSecurePreferences.getMobileMediaDownloadAllowed(getActivity()))); findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_WIFI_PREF) .setSummary(getSummaryForMediaPreference(TextSecurePreferences.getWifiMediaDownloadAllowed(getActivity()))); findPreference(TextSecurePreferences.MEDIA_DOWNLOAD_ROAMING_PREF) .setSummary(getSummaryForMediaPreference(TextSecurePreferences.getRoamingMediaDownloadAllowed(getActivity()))); } private CharSequence getSummaryForMediaPreference(Set<String> allowedNetworks) { String[] keys = getResources().getStringArray(R.array.pref_media_download_entries); String[] values = getResources().getStringArray(R.array.pref_media_download_values); List<String> outValues = new ArrayList<>(allowedNetworks.size()); for (int i=0; i < keys.length; i++) { if (allowedNetworks.contains(keys[i])) outValues.add(values[i]); } return outValues.isEmpty() ? getResources().getString(R.string.preferences__none) : TextUtils.join(", ", outValues); } private class TrimNowClickListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { final int threadLengthLimit = TextSecurePreferences.getThreadTrimLength(getActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.ApplicationPreferencesActivity_delete_all_old_messages_now); builder.setMessage(getString(R.string.ApplicationPreferencesActivity_are_you_sure_you_would_like_to_immediately_trim_all_conversation_threads_to_the_s_most_recent_messages, threadLengthLimit)); builder.setPositiveButton(R.string.ApplicationPreferencesActivity_delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Trimmer.trimAllThreads(getActivity(), threadLengthLimit); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); return true; } } private class MediaDownloadChangeListener implements OnPreferenceChangeListener { @SuppressWarnings("unchecked") @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Log.w(TAG, "onPreferenceChange"); preference.setSummary(getSummaryForMediaPreference((Set<String>)newValue)); return true; } } private class TrimLengthValidationListener implements Preference.OnPreferenceChangeListener { public TrimLengthValidationListener() { EditTextPreference preference = (EditTextPreference)findPreference(TextSecurePreferences.THREAD_TRIM_LENGTH); preference.setSummary(getString(R.string.ApplicationPreferencesActivity_messages_per_conversation, preference.getText())); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (newValue == null || ((String)newValue).trim().length() == 0) { return false; } try { Integer.parseInt((String)newValue); } catch (NumberFormatException nfe) { Log.w(TAG, nfe); return false; } if (Integer.parseInt((String)newValue) < 1) { return false; } preference.setSummary(getString(R.string.ApplicationPreferencesActivity_messages_per_conversation, newValue)); return true; } } public static CharSequence getSummary(Context context) { return null; } }
5,695
39.978417
178
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/ColorPreference.java
package org.thoughtcrime.securesms.preferences; /* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.preference.Preference; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayout; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import org.thoughtcrime.securesms.R; /** * A preference that allows the user to choose an application or shortcut. */ public class ColorPreference extends Preference { private int[] mColorChoices = {}; private int mValue = 0; private int mItemLayoutId = R.layout.color_preference_item; private int mNumColumns = 5; private View mPreviewView; public ColorPreference(Context context) { super(context); initAttrs(null, 0); } public ColorPreference(Context context, AttributeSet attrs) { super(context, attrs); initAttrs(attrs, 0); } public ColorPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAttrs(attrs, defStyle); } private void initAttrs(AttributeSet attrs, int defStyle) { TypedArray a = getContext().getTheme().obtainStyledAttributes( attrs, R.styleable.ColorPreference, defStyle, defStyle); try { mItemLayoutId = a.getResourceId(R.styleable.ColorPreference_itemLayout, mItemLayoutId); mNumColumns = a.getInteger(R.styleable.ColorPreference_numColumns, mNumColumns); // int choicesResId = a.getResourceId(R.styleable.ColorPreference_choices, // R.array.default_color_choice_values); // if (choicesResId > 0) { // String[] choices = a.getResources().getStringArray(choicesResId); // mColorChoices = new int[choices.length]; // for (int i = 0; i < choices.length; i++) { // mColorChoices[i] = Color.parseColor(choices[i]); // } // } } finally { a.recycle(); } setWidgetLayoutResource(mItemLayoutId); } @Override protected void onBindView(View view) { super.onBindView(view); mPreviewView = view.findViewById(R.id.color_view); setColorViewValue(mPreviewView, mValue, false); } public void setValue(int value) { if (callChangeListener(value)) { mValue = value; persistInt(value); notifyChanged(); } } public void setChoices(int[] values) { mColorChoices = values; } @Override protected void onClick() { super.onClick(); ColorDialogFragment fragment = ColorDialogFragment.newInstance(); fragment.setPreference(this); ((AppCompatActivity) getContext()).getSupportFragmentManager().beginTransaction() .add(fragment, getFragmentTag()) .commit(); } @Override protected void onAttachedToActivity() { super.onAttachedToActivity(); AppCompatActivity activity = (AppCompatActivity) getContext(); ColorDialogFragment fragment = (ColorDialogFragment) activity .getSupportFragmentManager().findFragmentByTag(getFragmentTag()); if (fragment != null) { // re-bind preference to fragment fragment.setPreference(this); } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getInt(index, 0); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue); } public String getFragmentTag() { return "color_" + getKey(); } public int getValue() { return mValue; } public static class ColorDialogFragment extends android.support.v4.app.DialogFragment { private ColorPreference mPreference; private GridLayout mColorGrid; public ColorDialogFragment() { } public static ColorDialogFragment newInstance() { return new ColorDialogFragment(); } public void setPreference(ColorPreference preference) { mPreference = preference; repopulateItems(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); repopulateItems(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater layoutInflater = LayoutInflater.from(getActivity()); View rootView = layoutInflater.inflate(R.layout.color_preference_items, null); mColorGrid = (GridLayout) rootView.findViewById(R.id.color_grid); mColorGrid.setColumnCount(mPreference.mNumColumns); repopulateItems(); return new AlertDialog.Builder(getActivity()) .setView(rootView) .create(); } private void repopulateItems() { if (mPreference == null || mColorGrid == null) { return; } Context context = mColorGrid.getContext(); mColorGrid.removeAllViews(); for (final int color : mPreference.mColorChoices) { View itemView = LayoutInflater.from(context) .inflate(R.layout.color_preference_item, mColorGrid, false); setColorViewValue(itemView.findViewById(R.id.color_view), color, color == mPreference.getValue()); itemView.setClickable(true); itemView.setFocusable(true); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mPreference.setValue(color); dismiss(); } }); mColorGrid.addView(itemView); } sizeDialog(); } @Override public void onStart() { super.onStart(); sizeDialog(); } private void sizeDialog() { // if (mPreference == null || mColorGrid == null) { // return; // } // // Dialog dialog = getDialog(); // if (dialog == null) { // return; // } // // final Resources res = mColorGrid.getContext().getResources(); // DisplayMetrics dm = res.getDisplayMetrics(); // // // Can't use Integer.MAX_VALUE here (weird issue observed otherwise on 4.2) // mColorGrid.measure( // View.MeasureSpec.makeMeasureSpec(dm.widthPixels, View.MeasureSpec.AT_MOST), // View.MeasureSpec.makeMeasureSpec(dm.heightPixels, View.MeasureSpec.AT_MOST)); // int width = mColorGrid.getMeasuredWidth(); // int height = mColorGrid.getMeasuredHeight(); // // int extraPadding = res.getDimensionPixelSize(R.dimen.color_grid_extra_padding); // // width += extraPadding; // height += extraPadding; // // dialog.getWindow().setLayout(width, height); } } private static void setColorViewValue(View view, int color, boolean selected) { if (view instanceof ImageView) { ImageView imageView = (ImageView) view; Resources res = imageView.getContext().getResources(); Drawable currentDrawable = imageView.getDrawable(); GradientDrawable colorChoiceDrawable; if (currentDrawable instanceof GradientDrawable) { // Reuse drawable colorChoiceDrawable = (GradientDrawable) currentDrawable; } else { colorChoiceDrawable = new GradientDrawable(); colorChoiceDrawable.setShape(GradientDrawable.OVAL); } // Set stroke to dark version of color // int darkenedColor = Color.rgb( // Color.red(color) * 192 / 256, // Color.green(color) * 192 / 256, // Color.blue(color) * 192 / 256); colorChoiceDrawable.setColor(color); // colorChoiceDrawable.setStroke((int) TypedValue.applyDimension( // TypedValue.COMPLEX_UNIT_DIP, 2, res.getDisplayMetrics()), darkenedColor); Drawable drawable = colorChoiceDrawable; if (selected) { BitmapDrawable checkmark = (BitmapDrawable) res.getDrawable(R.drawable.check); checkmark.setGravity(Gravity.CENTER); drawable = new LayerDrawable(new Drawable[]{ colorChoiceDrawable, checkmark}); } imageView.setImageDrawable(drawable); } else if (view instanceof TextView) { ((TextView) view).setTextColor(color); } } }
9,212
30.230508
98
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/LedBlinkPatternListPreference.java
/** * Copyright (C) 2011 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.preferences; import android.content.Context; import android.content.DialogInterface; import android.os.Parcelable; import android.preference.ListPreference; import android.support.v7.app.AlertDialog; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.TextSecurePreferences; /** * List preference for LED blink pattern notification. * * @author Moxie Marlinspike */ public class LedBlinkPatternListPreference extends ListPreference implements OnSeekBarChangeListener { private Context context; private SeekBar seekBarOn; private SeekBar seekBarOff; private TextView seekBarOnLabel; private TextView seekBarOffLabel; private boolean dialogInProgress; public LedBlinkPatternListPreference(Context context) { super(context); this.context = context; } public LedBlinkPatternListPreference(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { String blinkPattern = TextSecurePreferences.getNotificationLedPattern(context); if (blinkPattern.equals("custom")) showDialog(); } } private void initializeSeekBarValues() { String patternString = TextSecurePreferences.getNotificationLedPatternCustom(context); String[] patternArray = patternString.split(","); seekBarOn.setProgress(Integer.parseInt(patternArray[0])); seekBarOff.setProgress(Integer.parseInt(patternArray[1])); } private void initializeDialog(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIconAttribute(R.attr.dialog_info_icon); builder.setTitle(R.string.preferences__pref_led_blink_custom_pattern_title); builder.setView(view); builder.setOnCancelListener(new CustomDialogCancelListener()); builder.setNegativeButton(android.R.string.cancel, new CustomDialogCancelListener()); builder.setPositiveButton(android.R.string.ok, new CustomDialogClickListener()); builder.show(); } private void showDialog() { LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.led_pattern_dialog, null); this.seekBarOn = (SeekBar)view.findViewById(R.id.SeekBarOn); this.seekBarOff = (SeekBar)view.findViewById(R.id.SeekBarOff); this.seekBarOnLabel = (TextView)view.findViewById(R.id.SeekBarOnMsLabel); this.seekBarOffLabel = (TextView)view.findViewById(R.id.SeekBarOffMsLabel); this.seekBarOn.setOnSeekBarChangeListener(this); this.seekBarOff.setOnSeekBarChangeListener(this); initializeSeekBarValues(); initializeDialog(view); dialogInProgress = true; } @Override protected void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); if (dialogInProgress) { showDialog(); } } @Override protected View onCreateDialogView() { dialogInProgress = false; return super.onCreateDialogView(); } public void onProgressChanged(SeekBar seekbar, int progress, boolean fromTouch) { if (seekbar.equals(seekBarOn)) { seekBarOnLabel.setText(Integer.toString(progress)); } else if (seekbar.equals(seekBarOff)) { seekBarOffLabel.setText(Integer.toString(progress)); } } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } private class CustomDialogCancelListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { public void onClick(DialogInterface dialog, int which) { dialogInProgress = false; } public void onCancel(DialogInterface dialog) { dialogInProgress = false; } } private class CustomDialogClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { String pattern = seekBarOnLabel.getText() + "," + seekBarOffLabel.getText(); dialogInProgress = false; TextSecurePreferences.setNotificationLedPatternCustom(context, pattern); Toast.makeText(context, R.string.preferences__pref_led_blink_custom_pattern_set, Toast.LENGTH_LONG).show(); } } }
5,300
32.339623
121
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/ListSummaryPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.preference.ListPreference; import android.preference.Preference; import android.support.v4.preference.PreferenceFragment; import org.thoughtcrime.securesms.R; import java.util.Arrays; public abstract class ListSummaryPreferenceFragment extends PreferenceFragment { protected class ListSummaryListener implements Preference.OnPreferenceChangeListener { @Override public boolean onPreferenceChange(Preference preference, Object value) { ListPreference listPref = (ListPreference) preference; int entryIndex = Arrays.asList(listPref.getEntryValues()).indexOf(value); listPref.setSummary(entryIndex >= 0 && entryIndex < listPref.getEntries().length ? listPref.getEntries()[entryIndex] : getString(R.string.preferences__led_color_unknown)); return true; } } protected void initializeListSummary(ListPreference pref) { pref.setSummary(pref.getEntry()); } }
1,034
33.5
90
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/MmsPreferencesActivity.java
/** * Copyright (C) 2011 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.preferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.MenuItem; import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.DynamicTheme; public class MmsPreferencesActivity extends PassphraseRequiredActionBarActivity { private final DynamicTheme dynamicTheme = new DynamicTheme(); private final DynamicLanguage dynamicLanguage = new DynamicLanguage(); @Override protected void onPreCreate() { dynamicTheme.onCreate(this); dynamicLanguage.onCreate(this); } @Override protected void onCreate(Bundle icicle, @NonNull MasterSecret masterSecret) { this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); Fragment fragment = new MmsPreferencesFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(android.R.id.content, fragment); fragmentTransaction.commit(); } @Override public void onResume() { super.onResume(); dynamicTheme.onResume(this); dynamicLanguage.onResume(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return false; } @Override public void onBackPressed() { super.onBackPressed(); } }
2,440
30.294872
81
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/MmsPreferencesFragment.java
/** * 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.preferences; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.preference.PreferenceFragment; import android.util.Log; import org.thoughtcrime.securesms.PassphraseRequiredActionBarActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.components.CustomDefaultPreference; import org.thoughtcrime.securesms.database.ApnDatabase; import org.thoughtcrime.securesms.mms.LegacyMmsConnection; import org.thoughtcrime.securesms.util.TelephonyUtil; import org.thoughtcrime.securesms.util.TextSecurePreferences; import java.io.IOException; public class MmsPreferencesFragment extends PreferenceFragment { private static final String TAG = MmsPreferencesFragment.class.getSimpleName(); @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_manual_mms); ((PassphraseRequiredActionBarActivity) getActivity()).getSupportActionBar() .setTitle(R.string.preferences__advanced_mms_access_point_names); } @Override public void onResume() { super.onResume(); new LoadApnDefaultsTask().execute(); } private class LoadApnDefaultsTask extends AsyncTask<Void, Void, LegacyMmsConnection.Apn> { @Override protected LegacyMmsConnection.Apn doInBackground(Void... params) { try { Context context = getActivity(); if (context != null) { return ApnDatabase.getInstance(context) .getDefaultApnParameters(TelephonyUtil.getMccMnc(context), TelephonyUtil.getApn(context)); } } catch (IOException e) { Log.w(TAG, e); } return null; } @Override protected void onPostExecute(LegacyMmsConnection.Apn apnDefaults) { ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMSC_HOST_PREF)) .setValidator(new CustomDefaultPreference.UriValidator()) .setDefaultValue(apnDefaults.getMmsc()); ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMSC_PROXY_HOST_PREF)) .setValidator(new CustomDefaultPreference.HostnameValidator()) .setDefaultValue(apnDefaults.getProxy()); ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMSC_PROXY_PORT_PREF)) .setValidator(new CustomDefaultPreference.PortValidator()) .setDefaultValue(apnDefaults.getPort()); ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMSC_USERNAME_PREF)) .setDefaultValue(apnDefaults.getPort()); ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMSC_PASSWORD_PREF)) .setDefaultValue(apnDefaults.getPassword()); ((CustomDefaultPreference)findPreference(TextSecurePreferences.MMS_USER_AGENT)) .setDefaultValue(LegacyMmsConnection.USER_AGENT); } } }
3,683
35.84
92
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/NotificationPrivacyPreference.java
package org.thoughtcrime.securesms.preferences; public class NotificationPrivacyPreference { private final String preference; public NotificationPrivacyPreference(String preference) { this.preference = preference; } public boolean isDisplayContact() { return "all".equals(preference) || "contact".equals(preference); } public boolean isDisplayMessage() { return "all".equals(preference); } }
424
20.25
68
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/NotificationsPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.content.SharedPreferences; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceManager; import android.preference.RingtonePreference; import android.text.TextUtils; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.notifications.MessageNotifier; import org.thoughtcrime.securesms.util.TextSecurePreferences; public class NotificationsPreferenceFragment extends ListSummaryPreferenceFragment { private MasterSecret masterSecret; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); masterSecret = getArguments().getParcelable("master_secret"); addPreferencesFromResource(R.xml.preferences_notifications); this.findPreference(TextSecurePreferences.LED_COLOR_PREF) .setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(TextSecurePreferences.LED_BLINK_PREF) .setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(TextSecurePreferences.RINGTONE_PREF) .setOnPreferenceChangeListener(new RingtoneSummaryListener()); this.findPreference(TextSecurePreferences.REPEAT_ALERTS_PREF) .setOnPreferenceChangeListener(new ListSummaryListener()); this.findPreference(TextSecurePreferences.NOTIFICATION_PRIVACY_PREF) .setOnPreferenceChangeListener(new NotificationPrivacyListener()); initializeListSummary((ListPreference) findPreference(TextSecurePreferences.LED_COLOR_PREF)); initializeListSummary((ListPreference) findPreference(TextSecurePreferences.LED_BLINK_PREF)); initializeListSummary((ListPreference) findPreference(TextSecurePreferences.REPEAT_ALERTS_PREF)); initializeListSummary((ListPreference) findPreference(TextSecurePreferences.NOTIFICATION_PRIVACY_PREF)); initializeRingtoneSummary((RingtonePreference) findPreference(TextSecurePreferences.RINGTONE_PREF)); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__notifications); } private class RingtoneSummaryListener implements Preference.OnPreferenceChangeListener { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String value = (String) newValue; if (TextUtils.isEmpty(value)) { preference.setSummary(R.string.preferences__default); } else { Ringtone tone = RingtoneManager.getRingtone(getActivity(), Uri.parse(value)); if (tone != null) { preference.setSummary(tone.getTitle(getActivity())); } } return true; } } private void initializeRingtoneSummary(RingtonePreference pref) { RingtoneSummaryListener listener = (RingtoneSummaryListener) pref.getOnPreferenceChangeListener(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); listener.onPreferenceChange(pref, sharedPreferences.getString(pref.getKey(), "")); } public static CharSequence getSummary(Context context) { final int onCapsResId = R.string.ApplicationPreferencesActivity_On; final int offCapsResId = R.string.ApplicationPreferencesActivity_Off; return context.getString(TextSecurePreferences.isNotificationsEnabled(context) ? onCapsResId : offCapsResId); } private class NotificationPrivacyListener extends ListSummaryListener { @Override public boolean onPreferenceChange(Preference preference, Object value) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { MessageNotifier.updateNotification(getActivity(), masterSecret); return null; } }.execute(); return super.onPreferenceChange(preference, value); } } }
4,232
39.314286
121
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/preferences/SmsMmsPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceScreen; import android.provider.Settings; import android.provider.Telephony; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.preference.PreferenceFragment; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; public class SmsMmsPreferenceFragment extends PreferenceFragment { private static final String KITKAT_DEFAULT_PREF = "pref_set_default"; private static final String MMS_PREF = "pref_mms_preferences"; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); addPreferencesFromResource(R.xml.preferences_sms_mms); this.findPreference(MMS_PREF) .setOnPreferenceClickListener(new ApnPreferencesClickListener()); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__sms_mms); initializePlatformSpecificOptions(); } private void initializePlatformSpecificOptions() { PreferenceScreen preferenceScreen = getPreferenceScreen(); Preference defaultPreference = findPreference(KITKAT_DEFAULT_PREF); Preference allSmsPreference = findPreference(TextSecurePreferences.ALL_SMS_PREF); Preference allMmsPreference = findPreference(TextSecurePreferences.ALL_MMS_PREF); Preference manualMmsPreference = findPreference(MMS_PREF); if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { if (allSmsPreference != null) preferenceScreen.removePreference(allSmsPreference); if (allMmsPreference != null) preferenceScreen.removePreference(allMmsPreference); if (Util.isDefaultSmsProvider(getActivity())) { defaultPreference.setIntent(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_enabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_change_your_default_sms_app)); } else { Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT); intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getActivity().getPackageName()); defaultPreference.setIntent(intent); defaultPreference.setTitle(getString(R.string.ApplicationPreferencesActivity_sms_disabled)); defaultPreference.setSummary(getString(R.string.ApplicationPreferencesActivity_touch_to_make_signal_your_default_sms_app)); } } else if (defaultPreference != null) { preferenceScreen.removePreference(defaultPreference); } if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && manualMmsPreference != null) { preferenceScreen.removePreference(manualMmsPreference); } } private class ApnPreferencesClickListener implements Preference.OnPreferenceClickListener { @Override public boolean onPreferenceClick(Preference preference) { Fragment fragment = new MmsPreferencesFragment(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(android.R.id.content, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); return true; } } public static CharSequence getSummary(Context context) { final String on = context.getString(R.string.ApplicationPreferencesActivity_on); final String onCaps = context.getString(R.string.ApplicationPreferencesActivity_On); final String off = context.getString(R.string.ApplicationPreferencesActivity_off); final String offCaps = context.getString(R.string.ApplicationPreferencesActivity_Off); final int smsMmsSummaryResId = R.string.ApplicationPreferencesActivity_sms_mms_summary; boolean postKitkatSMS = Util.isDefaultSmsProvider(context); boolean preKitkatSMS = TextSecurePreferences.isInterceptAllSmsEnabled(context); boolean preKitkatMMS = TextSecurePreferences.isInterceptAllMmsEnabled(context); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (postKitkatSMS) return onCaps; else return offCaps; } else { if (preKitkatSMS && preKitkatMMS) return onCaps; else if (preKitkatSMS && !preKitkatMMS) return context.getString(smsMmsSummaryResId, on, off); else if (!preKitkatSMS && preKitkatMMS) return context.getString(smsMmsSummaryResId, off, on); else return offCaps; } } }
5,235
46.171171
131
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/providers/MmsBodyProvider.java
/** * Copyright (C) 2015 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.providers; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; public class MmsBodyProvider extends ContentProvider { private static final String TAG = MmsBodyProvider.class.getSimpleName(); private static final String CONTENT_URI_STRING = "content://org.thoughtcrime.provider.securesms.mms/mms"; public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING); private static final int SINGLE_ROW = 1; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("org.thoughtcrime.provider.securesms.mms", "mms/#", SINGLE_ROW); } @Override public boolean onCreate() { return true; } private File getFile(Uri uri) { long id = Long.parseLong(uri.getPathSegments().get(1)); return new File(getContext().getCacheDir(), id + ".mmsbody"); } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { Log.w(TAG, "openFile(" + uri + ", " + mode + ")"); switch (uriMatcher.match(uri)) { case SINGLE_ROW: Log.w(TAG, "Fetching message body for a single row..."); File tmpFile = getFile(uri); final int fileMode; switch (mode) { case "w": fileMode = ParcelFileDescriptor.MODE_TRUNCATE | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_WRITE_ONLY; break; case "r": fileMode = ParcelFileDescriptor.MODE_READ_ONLY; break; default: throw new IllegalArgumentException("requested file mode unsupported"); } Log.w(TAG, "returning file " + tmpFile.getAbsolutePath()); return ParcelFileDescriptor.open(tmpFile, fileMode); } throw new FileNotFoundException("Request for bad message."); } @Override public int delete(Uri uri, String arg1, String[] arg2) { switch (uriMatcher.match(uri)) { case SINGLE_ROW: return getFile(uri).delete() ? 1 : 0; } return 0; } @Override public String getType(Uri arg0) { return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { return null; } @Override public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { return null; } @Override public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { return 0; } public static Pointer makeTemporaryPointer(Context context) { return new Pointer(context, ContentUris.withAppendedId(MmsBodyProvider.CONTENT_URI, System.currentTimeMillis())); } public static class Pointer { private final Context context; private final Uri uri; public Pointer(Context context, Uri uri) { this.context = context; this.uri = uri; } public Uri getUri() { return uri; } public OutputStream getOutputStream() throws FileNotFoundException { return context.getContentResolver().openOutputStream(uri, "w"); } public InputStream getInputStream() throws FileNotFoundException { return context.getContentResolver().openInputStream(uri); } public void close() { context.getContentResolver().delete(uri, null, null); } } }
4,346
29.829787
117
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/providers/PartProvider.java
/** * Copyright (C) 2011 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.providers; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.support.annotation.NonNull; import android.util.Log; import org.thoughtcrime.securesms.attachments.AttachmentId; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.mms.PartUriParser; import org.thoughtcrime.securesms.service.KeyCachingService; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class PartProvider extends ContentProvider { private static final String TAG = PartProvider.class.getSimpleName(); private static final String CONTENT_URI_STRING = "content://org.thoughtcrime.provider.securesms/part"; private static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING); private static final int SINGLE_ROW = 1; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("org.thoughtcrime.provider.securesms", "part/*/#", SINGLE_ROW); } @Override public boolean onCreate() { Log.w(TAG, "onCreate()"); return true; } public static Uri getContentUri(AttachmentId attachmentId) { Uri uri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(attachmentId.getUniqueId())); return ContentUris.withAppendedId(uri, attachmentId.getRowId()); } @SuppressWarnings("ConstantConditions") private File copyPartToTemporaryFile(MasterSecret masterSecret, AttachmentId attachmentId) throws IOException { InputStream in = DatabaseFactory.getAttachmentDatabase(getContext()).getAttachmentStream(masterSecret, attachmentId); File tmpDir = getContext().getDir("tmp", 0); File tmpFile = File.createTempFile("test", ".jpg", tmpDir); FileOutputStream fout = new FileOutputStream(tmpFile); byte[] buffer = new byte[512]; int read; while ((read = in.read(buffer)) != -1) fout.write(buffer, 0, read); in.close(); return tmpFile; } @Override public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException { MasterSecret masterSecret = KeyCachingService.getMasterSecret(getContext()); Log.w(TAG, "openFile() called!"); if (masterSecret == null) { Log.w(TAG, "masterSecret was null, abandoning."); return null; } switch (uriMatcher.match(uri)) { case SINGLE_ROW: Log.w(TAG, "Parting out a single row..."); try { PartUriParser partUri = new PartUriParser(uri); File tmpFile = copyPartToTemporaryFile(masterSecret, partUri.getPartId()); ParcelFileDescriptor pdf = ParcelFileDescriptor.open(tmpFile, ParcelFileDescriptor.MODE_READ_ONLY); if (!tmpFile.delete()) { Log.w(TAG, "Failed to delete temp file."); } return pdf; } catch (IOException ioe) { Log.w(TAG, ioe); throw new FileNotFoundException("Error opening file"); } } throw new FileNotFoundException("Request for bad part."); } @Override public int delete(@NonNull Uri arg0, String arg1, String[] arg2) { return 0; } @Override public String getType(@NonNull Uri arg0) { return null; } @Override public Uri insert(@NonNull Uri arg0, ContentValues arg1) { return null; } @Override public Cursor query(@NonNull Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { return null; } @Override public int update(@NonNull Uri arg0, ContentValues arg1, String arg2, String[] arg3) { return 0; } }
4,644
31.943262
128
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/providers/PersistentBlobProvider.java
package org.thoughtcrime.securesms.providers; import android.content.ContentUris; import android.content.Context; import android.content.UriMatcher; import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.util.Log; import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream; import org.thoughtcrime.securesms.crypto.EncryptingPartOutputStream; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.Util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class PersistentBlobProvider { private static final String TAG = PersistentBlobProvider.class.getSimpleName(); private static final String URI_STRING = "content://org.thoughtcrime.securesms/capture"; public static final Uri CONTENT_URI = Uri.parse(URI_STRING); public static final String AUTHORITY = "org.thoughtcrime.securesms"; public static final String EXPECTED_PATH = "capture/*/#"; private static final int MATCH = 1; private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH) {{ addURI(AUTHORITY, EXPECTED_PATH, MATCH); }}; private static volatile PersistentBlobProvider instance; public static PersistentBlobProvider getInstance(Context context) { if (instance == null) { synchronized (PersistentBlobProvider.class) { if (instance == null) { instance = new PersistentBlobProvider(context); } } } return instance; } private final Context context; private final Map<Long, byte[]> cache = new HashMap<>(); private PersistentBlobProvider(Context context) { this.context = context.getApplicationContext(); } public Uri create(@NonNull MasterSecret masterSecret, @NonNull Recipients recipients, @NonNull byte[] imageBytes) { final long id = generateId(recipients); cache.put(id, imageBytes); return create(masterSecret, new ByteArrayInputStream(imageBytes), id); } public Uri create(@NonNull MasterSecret masterSecret, @NonNull InputStream input) { return create(masterSecret, input, System.currentTimeMillis()); } private Uri create(MasterSecret masterSecret, InputStream input, long id) { persistToDisk(masterSecret, id, input); final Uri uniqueUri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(System.currentTimeMillis())); return ContentUris.withAppendedId(uniqueUri, id); } private void persistToDisk(final MasterSecret masterSecret, final long id, final InputStream input) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { final OutputStream output = new EncryptingPartOutputStream(getFile(id), masterSecret); Util.copy(input, output); } catch (IOException e) { Log.w(TAG, e); } return null; } @Override protected void onPostExecute(Void aVoid) { cache.remove(id); } }.execute(); } public Uri createForExternal(@NonNull Recipients recipients) throws IOException { return Uri.fromFile(new File(getExternalDir(context), String.valueOf(generateId(recipients)) + ".jpg")) .buildUpon() .appendQueryParameter("unique", String.valueOf(System.currentTimeMillis())) .build(); } public boolean delete(@NonNull Uri uri) { switch (MATCHER.match(uri)) { case MATCH: return getFile(ContentUris.parseId(uri)).delete(); default: return new File(uri.getPath()).delete(); } } public @NonNull InputStream getStream(MasterSecret masterSecret, long id) throws IOException { final byte[] cached = cache.get(id); return cached != null ? new ByteArrayInputStream(cached) : new DecryptingPartInputStream(getFile(id), masterSecret); } private int generateId(Recipients recipients) { return Math.abs(Arrays.hashCode(recipients.getIds())); } private File getFile(long id) { return new File(context.getDir("captures", Context.MODE_PRIVATE), id + ".jpg"); } private static @NonNull File getExternalDir(Context context) throws IOException { final File externalDir = context.getExternalFilesDir(null); if (externalDir == null) throw new IOException("no external files directory"); return externalDir; } public static boolean isAuthority(@NonNull Context context, @NonNull Uri uri) { try { return MATCHER.match(uri) == MATCH || uri.getPath().startsWith(getExternalDir(context).getAbsolutePath()); } catch (IOException ioe) { return false; } } }
4,969
34.5
112
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/providers/SingleUseBlobProvider.java
package org.thoughtcrime.securesms.providers; import android.content.ContentUris; import android.content.Context; import android.content.UriMatcher; import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.util.Log; import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream; import org.thoughtcrime.securesms.crypto.EncryptingPartOutputStream; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.Util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class SingleUseBlobProvider { private static final String TAG = SingleUseBlobProvider.class.getSimpleName(); public static final String AUTHORITY = "org.thoughtcrime.securesms"; public static final String PATH = "memory/*/#"; private static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/memory"); private final Map<Long, byte[]> cache = new HashMap<>(); private static final SingleUseBlobProvider instance = new SingleUseBlobProvider(); public static SingleUseBlobProvider getInstance() { return instance; } private SingleUseBlobProvider() {} public synchronized Uri createUri(@NonNull byte[] blob) { try { long id = Math.abs(SecureRandom.getInstance("SHA1PRNG").nextLong()); cache.put(id, blob); Uri uniqueUri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(System.currentTimeMillis())); return ContentUris.withAppendedId(uniqueUri, id); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } public synchronized @NonNull InputStream getStream(long id) throws IOException { byte[] cached = cache.get(id); cache.remove(id); if (cached != null) return new ByteArrayInputStream(cached); else throw new IOException("ID not found: " + id); } }
2,179
31.058824
100
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/push/SecurityEventListener.java
package org.thoughtcrime.securesms.push; import android.content.Context; import org.thoughtcrime.securesms.crypto.SecurityEvent; import org.whispersystems.textsecure.api.TextSecureMessageSender; import org.whispersystems.textsecure.api.push.TextSecureAddress; public class SecurityEventListener implements TextSecureMessageSender.EventListener { private static final String TAG = SecurityEventListener.class.getSimpleName(); private final Context context; public SecurityEventListener(Context context) { this.context = context.getApplicationContext(); } @Override public void onSecurityEvent(TextSecureAddress textSecureAddress) { SecurityEvent.broadcastSecurityUpdateEvent(context); } }
717
28.916667
85
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/push/TextSecureCommunicationFactory.java
package org.thoughtcrime.securesms.push; import android.content.Context; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.crypto.SecurityEvent; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.storage.TextSecureAxolotlStore; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.recipients.Recipients; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.TextSecureMessageReceiver; import org.whispersystems.textsecure.api.TextSecureMessageSender; import static org.whispersystems.textsecure.api.TextSecureMessageSender.EventListener; public class TextSecureCommunicationFactory { public static TextSecureAccountManager createManager(Context context) { return new TextSecureAccountManager(BuildConfig.TEXTSECURE_URL, new TextSecurePushTrustStore(context), TextSecurePreferences.getLocalNumber(context), TextSecurePreferences.getPushServerPassword(context), BuildConfig.USER_AGENT); } public static TextSecureAccountManager createManager(Context context, String number, String password) { return new TextSecureAccountManager(BuildConfig.TEXTSECURE_URL, new TextSecurePushTrustStore(context), number, password, BuildConfig.USER_AGENT); } }
1,785
47.27027
106
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/push/TextSecurePushTrustStore.java
package org.thoughtcrime.securesms.push; import android.content.Context; import org.thoughtcrime.securesms.R; import org.whispersystems.textsecure.api.push.TrustStore; import org.whispersystems.textsecure.internal.push.PushServiceSocket; import java.io.InputStream; public class TextSecurePushTrustStore implements TrustStore { private final Context context; public TextSecurePushTrustStore(Context context) { this.context = context.getApplicationContext(); } @Override public InputStream getKeyStoreInputStream() { return context.getResources().openRawResource(R.raw.whisper); } @Override public String getKeyStorePassword() { return "whisper"; } }
688
22.758621
69
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/Recipient.java
/** * Copyright (C) 2011 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.recipients; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.color.MaterialColor; import org.thoughtcrime.securesms.contacts.avatars.ContactColors; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.contacts.avatars.ContactPhotoFactory; import org.thoughtcrime.securesms.recipients.RecipientProvider.RecipientDetails; import org.thoughtcrime.securesms.util.FutureTaskListener; import org.thoughtcrime.securesms.util.GroupUtil; import org.thoughtcrime.securesms.util.ListenableFutureTask; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.WeakHashMap; public class Recipient { private final static String TAG = Recipient.class.getSimpleName(); private final Set<RecipientModifiedListener> listeners = Collections.newSetFromMap(new WeakHashMap<RecipientModifiedListener, Boolean>()); private final long recipientId; private @NonNull String number; private @Nullable String name; private boolean stale; private ContactPhoto contactPhoto; private Uri contactUri; @Nullable private MaterialColor color; Recipient(long recipientId, @NonNull String number, @Nullable Recipient stale, @NonNull ListenableFutureTask<RecipientDetails> future) { this.recipientId = recipientId; this.number = number; this.contactPhoto = ContactPhotoFactory.getLoadingPhoto(); this.color = null; if (stale != null) { this.name = stale.name; this.contactUri = stale.contactUri; this.contactPhoto = stale.contactPhoto; this.color = stale.color; } future.addListener(new FutureTaskListener<RecipientDetails>() { @Override public void onSuccess(RecipientDetails result) { if (result != null) { synchronized (Recipient.this) { Recipient.this.name = result.name; Recipient.this.number = result.number; Recipient.this.contactUri = result.contactUri; Recipient.this.contactPhoto = result.avatar; Recipient.this.color = result.color; } notifyListeners(); } } @Override public void onFailure(Throwable error) { Log.w(TAG, error); } }); } Recipient(long recipientId, RecipientDetails details) { this.recipientId = recipientId; this.number = details.number; this.contactUri = details.contactUri; this.name = details.name; this.contactPhoto = details.avatar; this.color = details.color; } public synchronized Uri getContactUri() { return this.contactUri; } public synchronized @Nullable String getName() { return this.name; } public synchronized @NonNull MaterialColor getColor() { if (color != null) return color; else if (name != null) return ContactColors.generateFor(name); else return ContactColors.UNKNOWN_COLOR; } public void setColor(@NonNull MaterialColor color) { synchronized (this) { this.color = color; } notifyListeners(); } public @NonNull String getNumber() { return number; } public long getRecipientId() { return recipientId; } public boolean isGroupRecipient() { return GroupUtil.isEncodedGroup(number); } public synchronized void addListener(RecipientModifiedListener listener) { listeners.add(listener); } public synchronized void removeListener(RecipientModifiedListener listener) { listeners.remove(listener); } public synchronized String toShortString() { return (name == null ? number : name); } public synchronized @NonNull ContactPhoto getContactPhoto() { return contactPhoto; } public static Recipient getUnknownRecipient() { return new Recipient(-1, new RecipientDetails("Unknown", "Unknown", null, ContactPhotoFactory.getDefaultContactPhoto(null), null)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Recipient)) return false; Recipient that = (Recipient) o; return this.recipientId == that.recipientId; } @Override public int hashCode() { return 31 + (int)this.recipientId; } private void notifyListeners() { Set<RecipientModifiedListener> localListeners; synchronized (this) { localListeners = new HashSet<>(listeners); } for (RecipientModifiedListener listener : localListeners) listener.onModified(this); } public interface RecipientModifiedListener { public void onModified(Recipient recipient); } boolean isStale() { return stale; } void setStale() { this.stale = true; } }
5,679
27.832487
140
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/RecipientFactory.java
/** * Copyright (C) 2011 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.recipients; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; public class RecipientFactory { private static final RecipientProvider provider = new RecipientProvider(); public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) { if (TextUtils.isEmpty(recipientIds)) return new Recipients(); return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous); } public static @NonNull Recipients getRecipientsFor(Context context, Collection<Recipient> recipients, boolean asynchronous) { long[] ids = new long[recipients.size()]; int i = 0; for (Recipient recipient : recipients) { ids[i++] = recipient.getRecipientId(); } return provider.getRecipients(context, ids, asynchronous); } public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) { long[] ids = new long[1]; ids[0] = recipient.getRecipientId(); return provider.getRecipients(context, ids, asynchronous); } public @NonNull static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) { return provider.getRecipient(context, recipientId, asynchronous); } public @NonNull static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) { return provider.getRecipients(context, recipientIds, asynchronous); } public static Recipients getRecipientsFromString(Context context, @NonNull String rawText, boolean asynchronous) { StringTokenizer tokenizer = new StringTokenizer(rawText, ","); List<String> ids = new LinkedList<>(); while (tokenizer.hasMoreTokens()) { Optional<Long> id = getRecipientIdFromNumber(context, tokenizer.nextToken()); if (id.isPresent()) { ids.add(String.valueOf(id.get())); } } return getRecipientsForIds(context, ids, asynchronous); } public static Recipients getRecipientsFromStrings(@NonNull Context context, @NonNull List<String> numbers, boolean asynchronous) { List<String> ids = new LinkedList<>(); for (String number : numbers) { Optional<Long> id = getRecipientIdFromNumber(context, number); if (id.isPresent()) { ids.add(String.valueOf(id.get())); } } return getRecipientsForIds(context, ids, asynchronous); } private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) { long[] ids = new long[idStrings.size()]; int i = 0; for (String id : idStrings) { ids[i++] = Long.parseLong(id); } return provider.getRecipients(context, ids, asynchronous); } private static Optional<Long> getRecipientIdFromNumber(Context context, String number) { number = number.trim(); if (number.isEmpty()) return Optional.absent(); if (hasBracketedNumber(number)) { number = parseBracketedNumber(number); } return Optional.of(CanonicalAddressDatabase.getInstance(context).getCanonicalAddressId(number)); } private static boolean hasBracketedNumber(String recipient) { int openBracketIndex = recipient.indexOf('<'); return (openBracketIndex != -1) && (recipient.indexOf('>', openBracketIndex) != -1); } private static String parseBracketedNumber(String recipient) { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>', begin); String value = recipient.substring(begin + 1, end); return value; } public static void clearCache() { provider.clearCache(); } }
4,703
32.361702
132
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/RecipientFormattingException.java
/** * Copyright (C) 2011 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.recipients; public class RecipientFormattingException extends Exception { public RecipientFormattingException() { super(); } public RecipientFormattingException(String message) { super(message); } public RecipientFormattingException(String message, Throwable nested) { super(message, nested); } public RecipientFormattingException(Throwable nested) { super(nested); } }
1,136
30.583333
73
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/RecipientProvider.java
/** * Copyright (C) 2011 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.recipients; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.color.MaterialColor; import org.thoughtcrime.securesms.contacts.avatars.ContactColors; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.contacts.avatars.ContactPhotoFactory; import org.thoughtcrime.securesms.database.CanonicalAddressDatabase; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.GroupDatabase; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.RecipientsPreferences; import org.thoughtcrime.securesms.util.GroupUtil; import org.thoughtcrime.securesms.util.LRUCache; import org.thoughtcrime.securesms.util.ListenableFutureTask; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.util.guava.Optional; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; public class RecipientProvider { private static final String TAG = RecipientProvider.class.getSimpleName(); private static final RecipientCache recipientCache = new RecipientCache(); private static final RecipientsCache recipientsCache = new RecipientsCache(); private static final ExecutorService asyncRecipientResolver = Util.newSingleThreadedLifoExecutor(); private static final String[] CALLER_ID_PROJECTION = new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup.LOOKUP_KEY, PhoneLookup._ID, PhoneLookup.NUMBER }; private static final Map<String, RecipientDetails> STATIC_DETAILS = new HashMap<String, RecipientDetails>() {{ put("262966", new RecipientDetails("Amazon", "262966", null, ContactPhotoFactory.getResourceContactPhoto(R.drawable.ic_amazon), ContactColors.UNKNOWN_COLOR)); }}; @NonNull Recipient getRecipient(Context context, long recipientId, boolean asynchronous) { Recipient cachedRecipient = recipientCache.get(recipientId); if (cachedRecipient != null && !cachedRecipient.isStale()) return cachedRecipient; String number = CanonicalAddressDatabase.getInstance(context).getAddressFromId(recipientId); if (asynchronous) { cachedRecipient = new Recipient(recipientId, number, cachedRecipient, getRecipientDetailsAsync(context, recipientId, number)); } else { cachedRecipient = new Recipient(recipientId, getRecipientDetailsSync(context, recipientId, number)); } recipientCache.set(recipientId, cachedRecipient); return cachedRecipient; } @NonNull Recipients getRecipients(Context context, long[] recipientIds, boolean asynchronous) { Recipients cachedRecipients = recipientsCache.get(new RecipientIds(recipientIds)); if (cachedRecipients != null && !cachedRecipients.isStale()) return cachedRecipients; List<Recipient> recipientList = new LinkedList<>(); for (long recipientId : recipientIds) { recipientList.add(getRecipient(context, recipientId, asynchronous)); } if (asynchronous) cachedRecipients = new Recipients(recipientList, cachedRecipients, getRecipientsPreferencesAsync(context, recipientIds)); else cachedRecipients = new Recipients(recipientList, getRecipientsPreferencesSync(context, recipientIds)); recipientsCache.set(new RecipientIds(recipientIds), cachedRecipients); return cachedRecipients; } void clearCache() { recipientCache.reset(); recipientsCache.reset(); } private @NonNull ListenableFutureTask<RecipientDetails> getRecipientDetailsAsync(final Context context, final long recipientId, final @NonNull String number) { Callable<RecipientDetails> task = new Callable<RecipientDetails>() { @Override public RecipientDetails call() throws Exception { return getRecipientDetailsSync(context, recipientId, number); } }; ListenableFutureTask<RecipientDetails> future = new ListenableFutureTask<>(task); asyncRecipientResolver.submit(future); return future; } private @NonNull RecipientDetails getRecipientDetailsSync(Context context, long recipientId, @NonNull String number) { if (GroupUtil.isEncodedGroup(number)) return getGroupRecipientDetails(context, number); else return getIndividualRecipientDetails(context, recipientId, number); } private @NonNull RecipientDetails getIndividualRecipientDetails(Context context, long recipientId, @NonNull String number) { Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(context).getRecipientsPreferences(new long[]{recipientId}); MaterialColor color = preferences.isPresent() ? preferences.get().getColor() : null; Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Cursor cursor = context.getContentResolver().query(uri, CALLER_ID_PROJECTION, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { Uri contactUri = Contacts.getLookupUri(cursor.getLong(2), cursor.getString(1)); String name = cursor.getString(3).equals(cursor.getString(0)) ? null : cursor.getString(0); ContactPhoto contactPhoto = ContactPhotoFactory.getContactPhoto(context, Uri.withAppendedPath(Contacts.CONTENT_URI, cursor.getLong(2) + ""), name); return new RecipientDetails(cursor.getString(0), cursor.getString(3), contactUri, contactPhoto, color); } } finally { if (cursor != null) cursor.close(); } if (STATIC_DETAILS.containsKey(number)) return STATIC_DETAILS.get(number); else return new RecipientDetails(null, number, null, ContactPhotoFactory.getDefaultContactPhoto(null), color); } private @NonNull RecipientDetails getGroupRecipientDetails(Context context, String groupId) { try { GroupDatabase.GroupRecord record = DatabaseFactory.getGroupDatabase(context) .getGroup(GroupUtil.getDecodedId(groupId)); if (record != null) { ContactPhoto contactPhoto = ContactPhotoFactory.getGroupContactPhoto(record.getAvatar()); return new RecipientDetails(record.getTitle(), groupId, null, contactPhoto, null); } return new RecipientDetails(null, groupId, null, ContactPhotoFactory.getDefaultGroupPhoto(), null); } catch (IOException e) { Log.w("RecipientProvider", e); return new RecipientDetails(null, groupId, null, ContactPhotoFactory.getDefaultGroupPhoto(), null); } } private @Nullable RecipientsPreferences getRecipientsPreferencesSync(Context context, long[] recipientIds) { return DatabaseFactory.getRecipientPreferenceDatabase(context) .getRecipientsPreferences(recipientIds) .orNull(); } private ListenableFutureTask<RecipientsPreferences> getRecipientsPreferencesAsync(final Context context, final long[] recipientIds) { ListenableFutureTask<RecipientsPreferences> task = new ListenableFutureTask<>(new Callable<RecipientsPreferences>() { @Override public RecipientsPreferences call() throws Exception { return getRecipientsPreferencesSync(context, recipientIds); } }); asyncRecipientResolver.execute(task); return task; } public static class RecipientDetails { @Nullable public final String name; @NonNull public final String number; @NonNull public final ContactPhoto avatar; @Nullable public final Uri contactUri; @Nullable public final MaterialColor color; public RecipientDetails(@Nullable String name, @NonNull String number, @Nullable Uri contactUri, @NonNull ContactPhoto avatar, @Nullable MaterialColor color) { this.name = name; this.number = number; this.avatar = avatar; this.contactUri = contactUri; this.color = color; } } private static class RecipientIds { private final long[] ids; private RecipientIds(long[] ids) { this.ids = ids; } public boolean equals(Object other) { if (other == null || !(other instanceof RecipientIds)) return false; return Arrays.equals(this.ids, ((RecipientIds) other).ids); } public int hashCode() { return Arrays.hashCode(ids); } } private static class RecipientCache { private final Map<Long,Recipient> cache = new LRUCache<>(1000); public synchronized Recipient get(long recipientId) { return cache.get(recipientId); } public synchronized void set(long recipientId, Recipient recipient) { cache.put(recipientId, recipient); } public synchronized void reset() { for (Recipient recipient : cache.values()) { recipient.setStale(); } } } private static class RecipientsCache { private final Map<RecipientIds,Recipients> cache = new LRUCache<>(1000); public synchronized Recipients get(RecipientIds ids) { return cache.get(ids); } public synchronized void set(RecipientIds ids, Recipients recipients) { cache.put(ids, recipients); } public synchronized void reset() { for (Recipients recipients : cache.values()) { recipients.setStale(); } } } }
11,089
39.772059
156
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/Recipients.java
/** * Copyright (C) 2015 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.recipients; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.util.Patterns; import org.thoughtcrime.securesms.color.MaterialColor; import org.thoughtcrime.securesms.contacts.avatars.ContactColors; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.contacts.avatars.ContactPhotoFactory; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.RecipientsPreferences; import org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.VibrateState; import org.thoughtcrime.securesms.recipients.Recipient.RecipientModifiedListener; import org.thoughtcrime.securesms.util.FutureTaskListener; import org.thoughtcrime.securesms.util.GroupUtil; import org.thoughtcrime.securesms.util.ListenableFutureTask; import org.thoughtcrime.securesms.util.NumberUtil; import org.thoughtcrime.securesms.util.Util; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.WeakHashMap; public class Recipients implements Iterable<Recipient>, RecipientModifiedListener { private static final String TAG = Recipients.class.getSimpleName(); private final Set<RecipientsModifiedListener> listeners = Collections.newSetFromMap(new WeakHashMap<RecipientsModifiedListener, Boolean>()); private final List<Recipient> recipients; private Uri ringtone = null; private long mutedUntil = 0; private boolean blocked = false; private VibrateState vibrate = VibrateState.DEFAULT; private boolean stale = false; Recipients() { this(new LinkedList<Recipient>(), null); } Recipients(List<Recipient> recipients, @Nullable RecipientsPreferences preferences) { this.recipients = recipients; if (preferences != null) { ringtone = preferences.getRingtone(); mutedUntil = preferences.getMuteUntil(); vibrate = preferences.getVibrateState(); blocked = preferences.isBlocked(); } } Recipients(@NonNull List<Recipient> recipients, @Nullable Recipients stale, @NonNull ListenableFutureTask<RecipientsPreferences> preferences) { this.recipients = recipients; if (stale != null) { ringtone = stale.ringtone; mutedUntil = stale.mutedUntil; vibrate = stale.vibrate; blocked = stale.blocked; } preferences.addListener(new FutureTaskListener<RecipientsPreferences>() { @Override public void onSuccess(RecipientsPreferences result) { if (result != null) { Set<RecipientsModifiedListener> localListeners; synchronized (Recipients.this) { ringtone = result.getRingtone(); mutedUntil = result.getMuteUntil(); vibrate = result.getVibrateState(); blocked = result.isBlocked(); localListeners = new HashSet<>(listeners); } for (RecipientsModifiedListener listener : localListeners) { listener.onModified(Recipients.this); } } } @Override public void onFailure(Throwable error) { Log.w(TAG, error); } }); } public synchronized @Nullable Uri getRingtone() { return ringtone; } public void setRingtone(Uri ringtone) { synchronized (this) { this.ringtone = ringtone; } notifyListeners(); } public synchronized boolean isMuted() { return System.currentTimeMillis() <= mutedUntil; } public void setMuted(long mutedUntil) { synchronized (this) { this.mutedUntil = mutedUntil; } notifyListeners(); } public synchronized boolean isBlocked() { return blocked; } public void setBlocked(boolean blocked) { synchronized (this) { this.blocked = blocked; } notifyListeners(); } public synchronized VibrateState getVibrate() { return vibrate; } public void setVibrate(VibrateState vibrate) { synchronized (this) { this.vibrate = vibrate; } notifyListeners(); } public @NonNull ContactPhoto getContactPhoto() { if (recipients.size() == 1) return recipients.get(0).getContactPhoto(); else return ContactPhotoFactory.getDefaultGroupPhoto(); } public synchronized @NonNull MaterialColor getColor() { if (!isSingleRecipient() || isGroupRecipient()) return MaterialColor.GROUP; else if (isEmpty()) return ContactColors.UNKNOWN_COLOR; else return recipients.get(0).getColor(); } public synchronized void setColor(@NonNull MaterialColor color) { if (!isSingleRecipient() || isGroupRecipient()) throw new AssertionError("Groups don't have colors!"); else if (!isEmpty()) recipients.get(0).setColor(color); } public synchronized void addListener(RecipientsModifiedListener listener) { if (listeners.isEmpty()) { for (Recipient recipient : recipients) { recipient.addListener(this); } } listeners.add(listener); } public synchronized void removeListener(RecipientsModifiedListener listener) { listeners.remove(listener); if (listeners.isEmpty()) { for (Recipient recipient : recipients) { recipient.removeListener(this); } } } public boolean isEmailRecipient() { for (Recipient recipient : recipients) { if (NumberUtil.isValidEmail(recipient.getNumber())) return true; } return false; } public boolean isGroupRecipient() { return isSingleRecipient() && GroupUtil.isEncodedGroup(recipients.get(0).getNumber()); } public boolean isEmpty() { return this.recipients.isEmpty(); } public boolean isSingleRecipient() { return this.recipients.size() == 1; } public @Nullable Recipient getPrimaryRecipient() { if (!isEmpty()) return this.recipients.get(0); else return null; } public List<Recipient> getRecipientsList() { return this.recipients; } public long[] getIds() { long[] ids = new long[recipients.size()]; for (int i=0; i<recipients.size(); i++) { ids[i] = recipients.get(i).getRecipientId(); } return ids; } public String getSortedIdsString() { Set<Long> recipientSet = new HashSet<>(); for (Recipient recipient : this.recipients) { recipientSet.add(recipient.getRecipientId()); } long[] recipientArray = new long[recipientSet.size()]; int i = 0; for (Long recipientId : recipientSet) { recipientArray[i++] = recipientId; } Arrays.sort(recipientArray); return Util.join(recipientArray, " "); } public @NonNull String[] toNumberStringArray(boolean scrub) { String[] recipientsArray = new String[recipients.size()]; Iterator<Recipient> iterator = recipients.iterator(); int i = 0; while (iterator.hasNext()) { String number = iterator.next().getNumber(); if (scrub && number != null && !Patterns.EMAIL_ADDRESS.matcher(number).matches() && !GroupUtil.isEncodedGroup(number)) { number = number.replaceAll("[^0-9+]", ""); } recipientsArray[i++] = number; } return recipientsArray; } public @NonNull List<String> toNumberStringList(boolean scrub) { List<String> results = new LinkedList<>(); Collections.addAll(results, toNumberStringArray(scrub)); return results; } public String toShortString() { String fromString = ""; for (int i=0;i<recipients.size();i++) { fromString += recipients.get(i).toShortString(); if (i != recipients.size() -1 ) fromString += ", "; } return fromString; } @Override public Iterator<Recipient> iterator() { return recipients.iterator(); } @Override public void onModified(Recipient recipient) { notifyListeners(); } private void notifyListeners() { Set<RecipientsModifiedListener> localListeners; synchronized (this) { localListeners = new HashSet<>(listeners); } for (RecipientsModifiedListener listener : localListeners) { listener.onModified(this); } } boolean isStale() { return stale; } void setStale() { this.stale = true; } public interface RecipientsModifiedListener { public void onModified(Recipients recipient); } }
9,375
26.904762
142
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/recipients/RecipientsFormatter.java
/** * Copyright (C) 2011 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.recipients; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class RecipientsFormatter { private static String parseBracketedNumber(String recipient) throws RecipientFormattingException { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>'); String value = recipient.substring(begin + 1, end); if (PhoneNumberUtils.isWellFormedSmsAddress(value)) return value; else throw new RecipientFormattingException("Bracketed value: " + value + " is not valid."); } private static String parseRecipient(String recipient) throws RecipientFormattingException { recipient = recipient.trim(); if ((recipient.indexOf('<') != -1) && (recipient.indexOf('>') != -1)) return parseBracketedNumber(recipient); if (PhoneNumberUtils.isWellFormedSmsAddress(recipient)) return recipient; throw new RecipientFormattingException("Recipient: " + recipient + " is badly formatted."); } public static List<String> getRecipients(String rawText) throws RecipientFormattingException { ArrayList<String> results = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(rawText, ","); while (tokenizer.hasMoreTokens()) { results.add(parseRecipient(tokenizer.nextToken())); } return results; } public static String formatNameAndNumber(String name, String number) { // Format like this: Mike Cleron <(650) 555-1234> // Erick Tseng <(650) 555-1212> // Tutankhamun <[email protected]> // (408) 555-1289 String formattedNumber = PhoneNumberUtils.formatNumber(number); if (!TextUtils.isEmpty(name) && !name.equals(number)) { return name + " <" + formattedNumber + ">"; } else { return formattedNumber; } } }
2,673
33.727273
100
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/AccountAuthenticatorService.java
package org.thoughtcrime.securesms.service; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; import android.accounts.NetworkErrorException; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; public class AccountAuthenticatorService extends Service { private static AccountAuthenticatorImpl accountAuthenticator = null; @Override public IBinder onBind(Intent intent) { if (intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) { return getAuthenticator().getIBinder(); } else { return null; } } private synchronized AccountAuthenticatorImpl getAuthenticator() { if (accountAuthenticator == null) { accountAuthenticator = new AccountAuthenticatorImpl(this); } return accountAuthenticator; } private static class AccountAuthenticatorImpl extends AbstractAccountAuthenticator { public AccountAuthenticatorImpl(Context context) { super(context); } @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { return null; } public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) { return null; } @Override public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) { return null; } @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { return null; } @Override public String getAuthTokenLabel(String authTokenType) { return null; } @Override public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features) throws NetworkErrorException { return null; } @Override public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) { return null; } } }
2,401
28.654321
113
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/AccountVerificationTimeoutException.java
package org.thoughtcrime.securesms.service; public class AccountVerificationTimeoutException extends Exception { public AccountVerificationTimeoutException() { } public AccountVerificationTimeoutException(String detailMessage) { super(detailMessage); } public AccountVerificationTimeoutException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public AccountVerificationTimeoutException(Throwable throwable) { super(throwable); } }
496
25.157895
89
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/ApplicationMigrationService.java
package org.thoughtcrime.securesms.service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.support.v4.app.NotificationCompat; import android.util.Log; import org.thoughtcrime.securesms.ConversationListActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.SmsMigrator; import org.thoughtcrime.securesms.database.SmsMigrator.ProgressDescription; import java.lang.ref.WeakReference; import java.util.concurrent.Executor; import java.util.concurrent.Executors; // FIXME: This class is nuts. public class ApplicationMigrationService extends Service implements SmsMigrator.SmsMigrationProgressListener { private static final String TAG = ApplicationMigrationService.class.getSimpleName(); public static final String MIGRATE_DATABASE = "org.thoughtcrime.securesms.ApplicationMigration.MIGRATE_DATABSE"; public static final String COMPLETED_ACTION = "org.thoughtcrime.securesms.ApplicationMigrationService.COMPLETED"; private static final String PREFERENCES_NAME = "SecureSMS"; private static final String DATABASE_MIGRATED = "migrated"; private final BroadcastReceiver completedReceiver = new CompletedReceiver(); private final Binder binder = new ApplicationMigrationBinder(); private final Executor executor = Executors.newSingleThreadExecutor(); private WeakReference<Handler> handler = null; private NotificationCompat.Builder notification = null; private ImportState state = new ImportState(ImportState.STATE_IDLE, null); @Override public void onCreate() { registerCompletedReceiver(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) return START_NOT_STICKY; if (intent.getAction() != null && intent.getAction().equals(MIGRATE_DATABASE)) { executor.execute(new ImportRunnable(intent)); } return START_NOT_STICKY; } @Override public void onDestroy() { unregisterCompletedReceiver(); } @Override public IBinder onBind(Intent intent) { return binder; } public void setImportStateHandler(Handler handler) { this.handler = new WeakReference<>(handler); } private void registerCompletedReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(COMPLETED_ACTION); registerReceiver(completedReceiver, filter); } private void unregisterCompletedReceiver() { unregisterReceiver(completedReceiver); } private void notifyImportComplete() { Intent intent = new Intent(); intent.setAction(COMPLETED_ACTION); sendOrderedBroadcast(intent, null); } @Override public void progressUpdate(ProgressDescription progress) { setState(new ImportState(ImportState.STATE_MIGRATING_IN_PROGRESS, progress)); } public ImportState getState() { return state; } private void setState(ImportState state) { this.state = state; if (this.handler != null) { Handler handler = this.handler.get(); if (handler != null) { handler.obtainMessage(state.state, state.progress).sendToTarget(); } } if (state.progress != null && state.progress.secondaryComplete == 0) { updateBackgroundNotification(state.progress.primaryTotal, state.progress.primaryComplete); } } private void updateBackgroundNotification(int total, int complete) { notification.setProgress(total, complete, false); ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)) .notify(4242, notification.build()); } private NotificationCompat.Builder initializeBackgroundNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.icon_notification); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon_notification)); builder.setContentTitle(getString(R.string.ApplicationMigrationService_importing_text_messages)); builder.setContentText(getString(R.string.ApplicationMigrationService_import_in_progress)); builder.setOngoing(true); builder.setProgress(100, 0, false); builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ConversationListActivity.class), 0)); stopForeground(true); startForeground(4242, builder.build()); return builder; } private class ImportRunnable implements Runnable { private final MasterSecret masterSecret; public ImportRunnable(Intent intent) { this.masterSecret = intent.getParcelableExtra("master_secret"); Log.w(TAG, "Service got mastersecret: " + masterSecret); } @Override public void run() { notification = initializeBackgroundNotification(); PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE); WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Migration"); try { wakeLock.acquire(); setState(new ImportState(ImportState.STATE_MIGRATING_BEGIN, null)); SmsMigrator.migrateDatabase(ApplicationMigrationService.this, masterSecret, ApplicationMigrationService.this); setState(new ImportState(ImportState.STATE_MIGRATING_COMPLETE, null)); setDatabaseImported(ApplicationMigrationService.this); stopForeground(true); notifyImportComplete(); stopSelf(); } finally { wakeLock.release(); } } } public class ApplicationMigrationBinder extends Binder { public ApplicationMigrationService getService() { return ApplicationMigrationService.this; } } private static class CompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(R.drawable.icon_notification); builder.setContentTitle("Import Complete"); builder.setContentText("TextSecure system database import is complete."); builder.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, ConversationListActivity.class), 0)); builder.setWhen(System.currentTimeMillis()); builder.setDefaults(Notification.DEFAULT_VIBRATE); builder.setAutoCancel(true); Notification notification = builder.build(); ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(31337, notification); } } public static class ImportState { public static final int STATE_IDLE = 0; public static final int STATE_MIGRATING_BEGIN = 1; public static final int STATE_MIGRATING_IN_PROGRESS = 2; public static final int STATE_MIGRATING_COMPLETE = 3; public int state; public ProgressDescription progress; public ImportState(int state, ProgressDescription progress) { this.state = state; this.progress = progress; } } public static boolean isDatabaseImported(Context context) { return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) .getBoolean(DATABASE_MIGRATED, false); } public static void setDatabaseImported(Context context) { context.getSharedPreferences(PREFERENCES_NAME, 0).edit().putBoolean(DATABASE_MIGRATED, true).apply(); } }
7,962
34.079295
126
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/ContactsSyncAdapterService.java
package org.thoughtcrime.securesms.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import org.thoughtcrime.securesms.contacts.ContactsSyncAdapter; public class ContactsSyncAdapterService extends Service { private static ContactsSyncAdapter syncAdapter; @Override public synchronized void onCreate() { if (syncAdapter == null) { syncAdapter = new ContactsSyncAdapter(this, true); } } @Nullable @Override public IBinder onBind(Intent intent) { return syncAdapter.getSyncAdapterBinder(); } }
620
22
63
java
cryptoguard
cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/service/DirectoryRefreshListener.java
package org.thoughtcrime.securesms.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.jobs.DirectoryRefreshJob; import org.thoughtcrime.securesms.util.TextSecurePreferences; public class DirectoryRefreshListener extends BroadcastReceiver { private static final String TAG = DirectoryRefreshListener.class.getSimpleName(); private static final String REFRESH_EVENT = "org.whispersystems.whisperpush.DIRECTORY_REFRESH"; private static final String BOOT_EVENT = "android.intent.action.BOOT_COMPLETED"; private static final long INTERVAL = 12 * 60 * 60 * 1000; // 12 hours. @Override public void onReceive(Context context, Intent intent) { if (REFRESH_EVENT.equals(intent.getAction())) handleRefreshAction(context); else if (BOOT_EVENT.equals(intent.getAction())) handleBootEvent(context); } private void handleBootEvent(Context context) { schedule(context); } private void handleRefreshAction(Context context) { schedule(context); } public static void schedule(Context context) { if (!TextSecurePreferences.isPushRegistered(context)) return; AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(DirectoryRefreshListener.REFRESH_EVENT); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); long time = TextSecurePreferences.getDirectoryRefreshTime(context); if (time <= System.currentTimeMillis()) { if (time != 0) { ApplicationContext.getInstance(context) .getJobManager() .add(new DirectoryRefreshJob(context)); } time = System.currentTimeMillis() + INTERVAL; } Log.w(TAG, "Scheduling for: " + time); alarmManager.cancel(pendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); TextSecurePreferences.setDirectoryRefreshTime(context, time); } }
2,251
33.646154
100
java