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/database/DatabaseFactory.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.DatabaseUpgradeActivity;
import org.thoughtcrime.securesms.contacts.ContactsDatabase;
import org.thoughtcrime.securesms.crypto.DecryptingPartInputStream;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.InvalidMessageException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import ws.com.google.android.mms.ContentType;
public class DatabaseFactory {
private static final int INTRODUCED_IDENTITIES_VERSION = 2;
private static final int INTRODUCED_INDEXES_VERSION = 3;
private static final int INTRODUCED_DATE_SENT_VERSION = 4;
private static final int INTRODUCED_DRAFTS_VERSION = 5;
private static final int INTRODUCED_NEW_TYPES_VERSION = 6;
private static final int INTRODUCED_MMS_BODY_VERSION = 7;
private static final int INTRODUCED_MMS_FROM_VERSION = 8;
private static final int INTRODUCED_TOFU_IDENTITY_VERSION = 9;
private static final int INTRODUCED_PUSH_DATABASE_VERSION = 10;
private static final int INTRODUCED_GROUP_DATABASE_VERSION = 11;
private static final int INTRODUCED_PUSH_FIX_VERSION = 12;
private static final int INTRODUCED_DELIVERY_RECEIPTS = 13;
private static final int INTRODUCED_PART_DATA_SIZE_VERSION = 14;
private static final int INTRODUCED_THUMBNAILS_VERSION = 15;
private static final int INTRODUCED_IDENTITY_COLUMN_VERSION = 16;
private static final int INTRODUCED_UNIQUE_PART_IDS_VERSION = 17;
private static final int INTRODUCED_RECIPIENT_PREFS_DB = 18;
private static final int INTRODUCED_ENVELOPE_CONTENT_VERSION = 19;
private static final int INTRODUCED_COLOR_PREFERENCE_VERSION = 20;
private static final int INTRODUCED_DB_OPTIMIZATIONS_VERSION = 21;
private static final int INTRODUCED_INVITE_REMINDERS_VERSION = 22;
private static final int INTRODUCED_CONVERSATION_LIST_THUMBNAILS_VERSION = 23;
private static final int DATABASE_VERSION = 23;
private static final String DATABASE_NAME = "messages.db";
private static final Object lock = new Object();
private static DatabaseFactory instance;
private DatabaseHelper databaseHelper;
private final SmsDatabase sms;
private final EncryptingSmsDatabase encryptingSms;
private final MmsDatabase mms;
private final AttachmentDatabase attachments;
private final ImageDatabase image;
private final ThreadDatabase thread;
private final CanonicalAddressDatabase address;
private final MmsAddressDatabase mmsAddress;
private final MmsSmsDatabase mmsSmsDatabase;
private final IdentityDatabase identityDatabase;
private final DraftDatabase draftDatabase;
private final PushDatabase pushDatabase;
private final GroupDatabase groupDatabase;
private final RecipientPreferenceDatabase recipientPreferenceDatabase;
private final ContactsDatabase contactsDatabase;
public static DatabaseFactory getInstance(Context context) {
synchronized (lock) {
if (instance == null)
instance = new DatabaseFactory(context.getApplicationContext());
return instance;
}
}
public static MmsSmsDatabase getMmsSmsDatabase(Context context) {
return getInstance(context).mmsSmsDatabase;
}
public static ThreadDatabase getThreadDatabase(Context context) {
return getInstance(context).thread;
}
public static SmsDatabase getSmsDatabase(Context context) {
return getInstance(context).sms;
}
public static MmsDatabase getMmsDatabase(Context context) {
return getInstance(context).mms;
}
public static CanonicalAddressDatabase getAddressDatabase(Context context) {
return getInstance(context).address;
}
public static EncryptingSmsDatabase getEncryptingSmsDatabase(Context context) {
return getInstance(context).encryptingSms;
}
public static AttachmentDatabase getAttachmentDatabase(Context context) {
return getInstance(context).attachments;
}
public static ImageDatabase getImageDatabase(Context context) {
return getInstance(context).image;
}
public static MmsAddressDatabase getMmsAddressDatabase(Context context) {
return getInstance(context).mmsAddress;
}
public static IdentityDatabase getIdentityDatabase(Context context) {
return getInstance(context).identityDatabase;
}
public static DraftDatabase getDraftDatabase(Context context) {
return getInstance(context).draftDatabase;
}
public static PushDatabase getPushDatabase(Context context) {
return getInstance(context).pushDatabase;
}
public static GroupDatabase getGroupDatabase(Context context) {
return getInstance(context).groupDatabase;
}
public static RecipientPreferenceDatabase getRecipientPreferenceDatabase(Context context) {
return getInstance(context).recipientPreferenceDatabase;
}
public static ContactsDatabase getContactsDatabase(Context context) {
return getInstance(context).contactsDatabase;
}
private DatabaseFactory(Context context) {
this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
this.sms = new SmsDatabase(context, databaseHelper);
this.encryptingSms = new EncryptingSmsDatabase(context, databaseHelper);
this.mms = new MmsDatabase(context, databaseHelper);
this.attachments = new AttachmentDatabase(context, databaseHelper);
this.image = new ImageDatabase(context, databaseHelper);
this.thread = new ThreadDatabase(context, databaseHelper);
this.address = CanonicalAddressDatabase.getInstance(context);
this.mmsAddress = new MmsAddressDatabase(context, databaseHelper);
this.mmsSmsDatabase = new MmsSmsDatabase(context, databaseHelper);
this.identityDatabase = new IdentityDatabase(context, databaseHelper);
this.draftDatabase = new DraftDatabase(context, databaseHelper);
this.pushDatabase = new PushDatabase(context, databaseHelper);
this.groupDatabase = new GroupDatabase(context, databaseHelper);
this.recipientPreferenceDatabase = new RecipientPreferenceDatabase(context, databaseHelper);
this.contactsDatabase = new ContactsDatabase(context);
}
public void reset(Context context) {
DatabaseHelper old = this.databaseHelper;
this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
this.sms.reset(databaseHelper);
this.encryptingSms.reset(databaseHelper);
this.mms.reset(databaseHelper);
this.attachments.reset(databaseHelper);
this.thread.reset(databaseHelper);
this.mmsAddress.reset(databaseHelper);
this.mmsSmsDatabase.reset(databaseHelper);
this.identityDatabase.reset(databaseHelper);
this.draftDatabase.reset(databaseHelper);
this.pushDatabase.reset(databaseHelper);
this.groupDatabase.reset(databaseHelper);
this.recipientPreferenceDatabase.reset(databaseHelper);
old.close();
this.address.reset(context);
}
public void onApplicationLevelUpgrade(Context context, MasterSecret masterSecret, int fromVersion,
DatabaseUpgradeActivity.DatabaseUpgradeListener listener)
{
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.beginTransaction();
if (fromVersion < DatabaseUpgradeActivity.NO_MORE_KEY_EXCHANGE_PREFIX_VERSION) {
String KEY_EXCHANGE = "?TextSecureKeyExchange";
String PROCESSED_KEY_EXCHANGE = "?TextSecureKeyExchangd";
String STALE_KEY_EXCHANGE = "?TextSecureKeyExchangs";
int ROW_LIMIT = 500;
MasterCipher masterCipher = new MasterCipher(masterSecret);
int smsCount = 0;
int threadCount = 0;
int skip = 0;
Cursor cursor = db.query("sms", new String[] {"COUNT(*)"}, "type & " + 0x80000000 + " != 0",
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
smsCount = cursor.getInt(0);
cursor.close();
}
cursor = db.query("thread", new String[] {"COUNT(*)"}, "snippet_type & " + 0x80000000 + " != 0",
null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
threadCount = cursor.getInt(0);
cursor.close();
}
Cursor smsCursor = null;
Log.w("DatabaseFactory", "Upgrade count: " + (smsCount + threadCount));
do {
Log.w("DatabaseFactory", "Looping SMS cursor...");
if (smsCursor != null)
smsCursor.close();
smsCursor = db.query("sms", new String[] {"_id", "type", "body"},
"type & " + 0x80000000 + " != 0",
null, null, null, "_id", skip + "," + ROW_LIMIT);
while (smsCursor != null && smsCursor.moveToNext()) {
listener.setProgress(smsCursor.getPosition() + skip, smsCount + threadCount);
try {
String body = masterCipher.decryptBody(smsCursor.getString(smsCursor.getColumnIndexOrThrow("body")));
long type = smsCursor.getLong(smsCursor.getColumnIndexOrThrow("type"));
long id = smsCursor.getLong(smsCursor.getColumnIndexOrThrow("_id"));
if (body.startsWith(KEY_EXCHANGE)) {
body = body.substring(KEY_EXCHANGE.length());
body = masterCipher.encryptBody(body);
type |= 0x8000;
db.execSQL("UPDATE sms SET body = ?, type = ? WHERE _id = ?",
new String[] {body, type+"", id+""});
} else if (body.startsWith(PROCESSED_KEY_EXCHANGE)) {
body = body.substring(PROCESSED_KEY_EXCHANGE.length());
body = masterCipher.encryptBody(body);
type |= (0x8000 | 0x2000);
db.execSQL("UPDATE sms SET body = ?, type = ? WHERE _id = ?",
new String[] {body, type+"", id+""});
} else if (body.startsWith(STALE_KEY_EXCHANGE)) {
body = body.substring(STALE_KEY_EXCHANGE.length());
body = masterCipher.encryptBody(body);
type |= (0x8000 | 0x4000);
db.execSQL("UPDATE sms SET body = ?, type = ? WHERE _id = ?",
new String[] {body, type+"", id+""});
}
} catch (InvalidMessageException e) {
Log.w("DatabaseFactory", e);
}
}
skip += ROW_LIMIT;
} while (smsCursor != null && smsCursor.getCount() > 0);
Cursor threadCursor = null;
skip = 0;
do {
Log.w("DatabaseFactory", "Looping thread cursor...");
if (threadCursor != null)
threadCursor.close();
threadCursor = db.query("thread", new String[] {"_id", "snippet_type", "snippet"},
"snippet_type & " + 0x80000000 + " != 0",
null, null, null, "_id", skip + "," + ROW_LIMIT);
while (threadCursor != null && threadCursor.moveToNext()) {
listener.setProgress(smsCount + threadCursor.getPosition(), smsCount + threadCount);
try {
String snippet = threadCursor.getString(threadCursor.getColumnIndexOrThrow("snippet"));
long snippetType = threadCursor.getLong(threadCursor.getColumnIndexOrThrow("snippet_type"));
long id = threadCursor.getLong(threadCursor.getColumnIndexOrThrow("_id"));
if (!TextUtils.isEmpty(snippet)) {
snippet = masterCipher.decryptBody(snippet);
}
if (snippet.startsWith(KEY_EXCHANGE)) {
snippet = snippet.substring(KEY_EXCHANGE.length());
snippet = masterCipher.encryptBody(snippet);
snippetType |= 0x8000;
db.execSQL("UPDATE thread SET snippet = ?, snippet_type = ? WHERE _id = ?",
new String[] {snippet, snippetType+"", id+""});
} else if (snippet.startsWith(PROCESSED_KEY_EXCHANGE)) {
snippet = snippet.substring(PROCESSED_KEY_EXCHANGE.length());
snippet = masterCipher.encryptBody(snippet);
snippetType |= (0x8000 | 0x2000);
db.execSQL("UPDATE thread SET snippet = ?, snippet_type = ? WHERE _id = ?",
new String[] {snippet, snippetType+"", id+""});
} else if (snippet.startsWith(STALE_KEY_EXCHANGE)) {
snippet = snippet.substring(STALE_KEY_EXCHANGE.length());
snippet = masterCipher.encryptBody(snippet);
snippetType |= (0x8000 | 0x4000);
db.execSQL("UPDATE thread SET snippet = ?, snippet_type = ? WHERE _id = ?",
new String[] {snippet, snippetType+"", id+""});
}
} catch (InvalidMessageException e) {
Log.w("DatabaseFactory", e);
}
}
skip += ROW_LIMIT;
} while (threadCursor != null && threadCursor.getCount() > 0);
if (smsCursor != null)
smsCursor.close();
if (threadCursor != null)
threadCursor.close();
}
if (fromVersion < DatabaseUpgradeActivity.MMS_BODY_VERSION) {
Log.w("DatabaseFactory", "Update MMS bodies...");
MasterCipher masterCipher = new MasterCipher(masterSecret);
Cursor mmsCursor = db.query("mms", new String[] {"_id"},
"msg_box & " + 0x80000000L + " != 0",
null, null, null, null);
Log.w("DatabaseFactory", "Got MMS rows: " + (mmsCursor == null ? "null" : mmsCursor.getCount()));
while (mmsCursor != null && mmsCursor.moveToNext()) {
listener.setProgress(mmsCursor.getPosition(), mmsCursor.getCount());
long mmsId = mmsCursor.getLong(mmsCursor.getColumnIndexOrThrow("_id"));
String body = null;
int partCount = 0;
Cursor partCursor = db.query("part", new String[] {"_id", "ct", "_data", "encrypted"},
"mid = ?", new String[] {mmsId+""}, null, null, null);
while (partCursor != null && partCursor.moveToNext()) {
String contentType = partCursor.getString(partCursor.getColumnIndexOrThrow("ct"));
if (ContentType.isTextType(contentType)) {
try {
long partId = partCursor.getLong(partCursor.getColumnIndexOrThrow("_id"));
String dataLocation = partCursor.getString(partCursor.getColumnIndexOrThrow("_data"));
boolean encrypted = partCursor.getInt(partCursor.getColumnIndexOrThrow("encrypted")) == 1;
File dataFile = new File(dataLocation);
InputStream is;
if (encrypted) is = new DecryptingPartInputStream(dataFile, masterSecret);
else is = new FileInputStream(dataFile);
body = (body == null) ? Util.readFullyAsString(is) : body + " " + Util.readFullyAsString(is);
//noinspection ResultOfMethodCallIgnored
dataFile.delete();
db.delete("part", "_id = ?", new String[] {partId+""});
} catch (IOException e) {
Log.w("DatabaseFactory", e);
}
} else if (ContentType.isAudioType(contentType) ||
ContentType.isImageType(contentType) ||
ContentType.isVideoType(contentType))
{
partCount++;
}
}
if (!TextUtils.isEmpty(body)) {
body = masterCipher.encryptBody(body);
db.execSQL("UPDATE mms SET body = ?, part_count = ? WHERE _id = ?",
new String[] {body, partCount+"", mmsId+""});
} else {
db.execSQL("UPDATE mms SET part_count = ? WHERE _id = ?",
new String[] {partCount+"", mmsId+""});
}
Log.w("DatabaseFactory", "Updated body: " + body + " and part_count: " + partCount);
}
}
if (fromVersion < DatabaseUpgradeActivity.TOFU_IDENTITIES_VERSION) {
File sessionDirectory = new File(context.getFilesDir() + File.separator + "sessions");
if (sessionDirectory.exists() && sessionDirectory.isDirectory()) {
File[] sessions = sessionDirectory.listFiles();
if (sessions != null) {
for (File session : sessions) {
String name = session.getName();
if (name.matches("[0-9]+")) {
long recipientId = Long.parseLong(name);
IdentityKey identityKey = null;
// NOTE (4/21/14) -- At this moment in time, we're forgetting the ability to parse
// V1 session records. Despite our usual attempts to avoid using shared code in the
// upgrade path, this is too complex to put here directly. Thus, unfortunately
// this operation is now lost to the ages. From the git log, it seems to have been
// almost exactly a year since this went in, so hopefully the bulk of people have
// already upgraded.
// IdentityKey identityKey = Session.getRemoteIdentityKey(context, masterSecret, recipientId);
if (identityKey != null) {
MasterCipher masterCipher = new MasterCipher(masterSecret);
String identityKeyString = Base64.encodeBytes(identityKey.serialize());
String macString = Base64.encodeBytes(masterCipher.getMacFor(recipientId +
identityKeyString));
db.execSQL("REPLACE INTO identities (recipient, key, mac) VALUES (?, ?, ?)",
new String[] {recipientId+"", identityKeyString, macString});
}
}
}
}
}
}
if (fromVersion < DatabaseUpgradeActivity.ASYMMETRIC_MASTER_SECRET_FIX_VERSION) {
if (!MasterSecretUtil.hasAsymmericMasterSecret(context)) {
MasterSecretUtil.generateAsymmetricMasterSecret(context, masterSecret);
MasterCipher masterCipher = new MasterCipher(masterSecret);
Cursor cursor = null;
try {
cursor = db.query(SmsDatabase.TABLE_NAME,
new String[] {SmsDatabase.ID, SmsDatabase.BODY, SmsDatabase.TYPE},
SmsDatabase.TYPE + " & ? == 0",
new String[] {String.valueOf(SmsDatabase.Types.ENCRYPTION_MASK)},
null, null, null);
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
String body = cursor.getString(1);
long type = cursor.getLong(2);
String encryptedBody = masterCipher.encryptBody(body);
ContentValues update = new ContentValues();
update.put(SmsDatabase.BODY, encryptedBody);
update.put(SmsDatabase.TYPE, type | SmsDatabase.Types.ENCRYPTION_SYMMETRIC_BIT);
db.update(SmsDatabase.TABLE_NAME, update, SmsDatabase.ID + " = ?",
new String[] {String.valueOf(id)});
}
} finally {
if (cursor != null)
cursor.close();
}
}
}
db.setTransactionSuccessful();
db.endTransaction();
// DecryptingQueue.schedulePendingDecrypts(context, masterSecret);
MessageNotifier.updateNotification(context, masterSecret);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SmsDatabase.CREATE_TABLE);
db.execSQL(MmsDatabase.CREATE_TABLE);
db.execSQL(AttachmentDatabase.CREATE_TABLE);
db.execSQL(ThreadDatabase.CREATE_TABLE);
db.execSQL(MmsAddressDatabase.CREATE_TABLE);
db.execSQL(IdentityDatabase.CREATE_TABLE);
db.execSQL(DraftDatabase.CREATE_TABLE);
db.execSQL(PushDatabase.CREATE_TABLE);
db.execSQL(GroupDatabase.CREATE_TABLE);
db.execSQL(RecipientPreferenceDatabase.CREATE_TABLE);
executeStatements(db, SmsDatabase.CREATE_INDEXS);
executeStatements(db, MmsDatabase.CREATE_INDEXS);
executeStatements(db, AttachmentDatabase.CREATE_INDEXS);
executeStatements(db, ThreadDatabase.CREATE_INDEXS);
executeStatements(db, MmsAddressDatabase.CREATE_INDEXS);
executeStatements(db, DraftDatabase.CREATE_INDEXS);
executeStatements(db, GroupDatabase.CREATE_INDEXS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.beginTransaction();
if (oldVersion < INTRODUCED_IDENTITIES_VERSION) {
db.execSQL("CREATE TABLE identities (_id INTEGER PRIMARY KEY, key TEXT UNIQUE, name TEXT UNIQUE, mac TEXT);");
}
if (oldVersion < INTRODUCED_INDEXES_VERSION) {
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS sms_thread_id_index ON sms (thread_id);",
"CREATE INDEX IF NOT EXISTS sms_read_index ON sms (read);",
"CREATE INDEX IF NOT EXISTS sms_read_and_thread_id_index ON sms (read,thread_id);",
"CREATE INDEX IF NOT EXISTS sms_type_index ON sms (type);"
});
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS mms_thread_id_index ON mms (thread_id);",
"CREATE INDEX IF NOT EXISTS mms_read_index ON mms (read);",
"CREATE INDEX IF NOT EXISTS mms_read_and_thread_id_index ON mms (read,thread_id);",
"CREATE INDEX IF NOT EXISTS mms_message_box_index ON mms (msg_box);"
});
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS part_mms_id_index ON part (mid);"
});
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS thread_recipient_ids_index ON thread (recipient_ids);",
});
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS mms_addresses_mms_id_index ON mms_addresses (mms_id);",
});
}
if (oldVersion < INTRODUCED_DATE_SENT_VERSION) {
db.execSQL("ALTER TABLE sms ADD COLUMN date_sent INTEGER;");
db.execSQL("UPDATE sms SET date_sent = date;");
db.execSQL("ALTER TABLE mms ADD COLUMN date_received INTEGER;");
db.execSQL("UPDATE mms SET date_received = date;");
}
if (oldVersion < INTRODUCED_DRAFTS_VERSION) {
db.execSQL("CREATE TABLE drafts (_id INTEGER PRIMARY KEY, thread_id INTEGER, type TEXT, value TEXT);");
executeStatements(db, new String[] {
"CREATE INDEX IF NOT EXISTS draft_thread_index ON drafts (thread_id);",
});
}
if (oldVersion < INTRODUCED_NEW_TYPES_VERSION) {
String KEY_EXCHANGE = "?TextSecureKeyExchange";
String SYMMETRIC_ENCRYPT = "?TextSecureLocalEncrypt";
String ASYMMETRIC_ENCRYPT = "?TextSecureAsymmetricEncrypt";
String ASYMMETRIC_LOCAL_ENCRYPT = "?TextSecureAsymmetricLocalEncrypt";
String PROCESSED_KEY_EXCHANGE = "?TextSecureKeyExchangd";
String STALE_KEY_EXCHANGE = "?TextSecureKeyExchangs";
// SMS Updates
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {20L+"", 1L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {21L+"", 43L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {22L+"", 4L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {23L+"", 2L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {24L+"", 5L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(21L | 0x800000L)+"", 42L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(23L | 0x800000L)+"", 44L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L)+"", 45L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L | 0x10000000L)+"", 46L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L)+"", 47L+""});
db.execSQL("UPDATE sms SET type = ? WHERE type = ?", new String[] {(20L | 0x800000L | 0x08000000L)+"", 48L+""});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(SYMMETRIC_ENCRYPT.length()+1)+"",
0x80000000L+"",
SYMMETRIC_ENCRYPT + "%"});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(ASYMMETRIC_LOCAL_ENCRYPT.length()+1)+"",
0x40000000L+"",
ASYMMETRIC_LOCAL_ENCRYPT + "%"});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(ASYMMETRIC_ENCRYPT.length()+1)+"",
(0x800000L | 0x20000000L)+"",
ASYMMETRIC_ENCRYPT + "%"});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(KEY_EXCHANGE.length()+1)+"",
0x8000L+"",
KEY_EXCHANGE + "%"});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(PROCESSED_KEY_EXCHANGE.length()+1)+"",
(0x8000L | 0x2000L)+"",
PROCESSED_KEY_EXCHANGE + "%"});
db.execSQL("UPDATE sms SET body = substr(body, ?), type = type | ? WHERE body LIKE ?",
new String[] {(STALE_KEY_EXCHANGE.length()+1)+"",
(0x8000L | 0x4000L)+"",
STALE_KEY_EXCHANGE + "%"});
// MMS Updates
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x80000000L)+"", 1+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(23L | 0x80000000L)+"", 2+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(21L | 0x80000000L)+"", 4+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(24L | 0x80000000L)+"", 12+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(21L | 0x80000000L | 0x800000L) +"", 5+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(23L | 0x80000000L | 0x800000L) +"", 6+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x20000000L | 0x800000L) +"", 7+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x80000000L | 0x800000L) +"", 8+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x08000000L | 0x800000L) +"", 9+""});
db.execSQL("UPDATE mms SET msg_box = ? WHERE msg_box = ?", new String[] {(20L | 0x10000000L | 0x800000L) +"", 10+""});
// Thread Updates
db.execSQL("ALTER TABLE thread ADD COLUMN snippet_type INTEGER;");
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(SYMMETRIC_ENCRYPT.length()+1)+"",
0x80000000L+"",
SYMMETRIC_ENCRYPT + "%"});
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(ASYMMETRIC_LOCAL_ENCRYPT.length()+1)+"",
0x40000000L+"",
ASYMMETRIC_LOCAL_ENCRYPT + "%"});
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(ASYMMETRIC_ENCRYPT.length()+1)+"",
(0x800000L | 0x20000000L)+"",
ASYMMETRIC_ENCRYPT + "%"});
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(KEY_EXCHANGE.length()+1)+"",
0x8000L+"",
KEY_EXCHANGE + "%"});
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(STALE_KEY_EXCHANGE.length()+1)+"",
(0x8000L | 0x4000L)+"",
STALE_KEY_EXCHANGE + "%"});
db.execSQL("UPDATE thread SET snippet = substr(snippet, ?), " +
"snippet_type = ? WHERE snippet LIKE ?",
new String[] {(PROCESSED_KEY_EXCHANGE.length()+1)+"",
(0x8000L | 0x2000L)+"",
PROCESSED_KEY_EXCHANGE + "%"});
}
if (oldVersion < INTRODUCED_MMS_BODY_VERSION) {
db.execSQL("ALTER TABLE mms ADD COLUMN body TEXT");
db.execSQL("ALTER TABLE mms ADD COLUMN part_count INTEGER");
}
if (oldVersion < INTRODUCED_MMS_FROM_VERSION) {
db.execSQL("ALTER TABLE mms ADD COLUMN address TEXT");
Cursor cursor = db.query("mms_addresses", null, "type = ?", new String[] {0x89+""},
null, null, null);
while (cursor != null && cursor.moveToNext()) {
long mmsId = cursor.getLong(cursor.getColumnIndexOrThrow("mms_id"));
String address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
if (!TextUtils.isEmpty(address)) {
db.execSQL("UPDATE mms SET address = ? WHERE _id = ?", new String[]{address, mmsId+""});
}
}
if (cursor != null)
cursor.close();
}
if (oldVersion < INTRODUCED_TOFU_IDENTITY_VERSION) {
db.execSQL("DROP TABLE identities");
db.execSQL("CREATE TABLE identities (_id INTEGER PRIMARY KEY, recipient INTEGER UNIQUE, key TEXT, mac TEXT);");
}
if (oldVersion < INTRODUCED_PUSH_DATABASE_VERSION) {
db.execSQL("CREATE TABLE push (_id INTEGER PRIMARY KEY, type INTEGER, source TEXT, destinations TEXT, body TEXT, TIMESTAMP INTEGER);");
db.execSQL("ALTER TABLE part ADD COLUMN pending_push INTEGER;");
db.execSQL("CREATE INDEX IF NOT EXISTS pending_push_index ON part (pending_push);");
}
if (oldVersion < INTRODUCED_GROUP_DATABASE_VERSION) {
db.execSQL("CREATE TABLE groups (_id INTEGER PRIMARY KEY, group_id TEXT, title TEXT, members TEXT, avatar BLOB, avatar_id INTEGER, avatar_key BLOB, avatar_content_type TEXT, avatar_relay TEXT, timestamp INTEGER, active INTEGER DEFAULT 1);");
db.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS group_id_index ON groups (GROUP_ID);");
db.execSQL("ALTER TABLE push ADD COLUMN device_id INTEGER DEFAULT 1;");
db.execSQL("ALTER TABLE sms ADD COLUMN address_device_id INTEGER DEFAULT 1;");
db.execSQL("ALTER TABLE mms ADD COLUMN address_device_id INTEGER DEFAULT 1;");
}
if (oldVersion < INTRODUCED_PUSH_FIX_VERSION) {
db.execSQL("CREATE TEMPORARY table push_backup (_id INTEGER PRIMARY KEY, type INTEGER, source, TEXT, destinations TEXT, body TEXT, timestamp INTEGER, device_id INTEGER DEFAULT 1);");
db.execSQL("INSERT INTO push_backup(_id, type, source, body, timestamp, device_id) SELECT _id, type, source, body, timestamp, device_id FROM push;");
db.execSQL("DROP TABLE push");
db.execSQL("CREATE TABLE push (_id INTEGER PRIMARY KEY, type INTEGER, source TEXT, body TEXT, timestamp INTEGER, device_id INTEGER DEFAULT 1);");
db.execSQL("INSERT INTO push (_id, type, source, body, timestamp, device_id) SELECT _id, type, source, body, timestamp, device_id FROM push_backup;");
db.execSQL("DROP TABLE push_backup;");
}
if (oldVersion < INTRODUCED_DELIVERY_RECEIPTS) {
db.execSQL("ALTER TABLE sms ADD COLUMN delivery_receipt_count INTEGER DEFAULT 0;");
db.execSQL("ALTER TABLE mms ADD COLUMN delivery_receipt_count INTEGER DEFAULT 0;");
db.execSQL("CREATE INDEX IF NOT EXISTS sms_date_sent_index ON sms (date_sent);");
db.execSQL("CREATE INDEX IF NOT EXISTS mms_date_sent_index ON mms (date);");
}
if (oldVersion < INTRODUCED_PART_DATA_SIZE_VERSION) {
db.execSQL("ALTER TABLE part ADD COLUMN data_size INTEGER DEFAULT 0;");
}
if (oldVersion < INTRODUCED_THUMBNAILS_VERSION) {
db.execSQL("ALTER TABLE part ADD COLUMN thumbnail TEXT;");
db.execSQL("ALTER TABLE part ADD COLUMN aspect_ratio REAL;");
}
if (oldVersion < INTRODUCED_IDENTITY_COLUMN_VERSION) {
db.execSQL("ALTER TABLE sms ADD COLUMN mismatched_identities TEXT");
db.execSQL("ALTER TABLE mms ADD COLUMN mismatched_identities TEXT");
db.execSQL("ALTER TABLE mms ADD COLUMN network_failures TEXT");
}
if (oldVersion < INTRODUCED_UNIQUE_PART_IDS_VERSION) {
db.execSQL("ALTER TABLE part ADD COLUMN unique_id INTEGER NOT NULL DEFAULT 0");
}
if (oldVersion < INTRODUCED_RECIPIENT_PREFS_DB) {
db.execSQL("CREATE TABLE recipient_preferences " +
"(_id INTEGER PRIMARY KEY, recipient_ids TEXT UNIQUE, block INTEGER DEFAULT 0, " +
"notification TEXT DEFAULT NULL, vibrate INTEGER DEFAULT 0, mute_until INTEGER DEFAULT 0)");
}
if (oldVersion < INTRODUCED_ENVELOPE_CONTENT_VERSION) {
db.execSQL("ALTER TABLE push ADD COLUMN content TEXT");
}
if (oldVersion < INTRODUCED_COLOR_PREFERENCE_VERSION) {
db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN color TEXT DEFAULT NULL");
}
if (oldVersion < INTRODUCED_DB_OPTIMIZATIONS_VERSION) {
db.execSQL("UPDATE mms SET date_received = (date_received * 1000), date = (date * 1000);");
db.execSQL("CREATE INDEX IF NOT EXISTS sms_thread_date_index ON sms (thread_id, date);");
db.execSQL("CREATE INDEX IF NOT EXISTS mms_thread_date_index ON mms (thread_id, date_received);");
}
if (oldVersion < INTRODUCED_INVITE_REMINDERS_VERSION) {
db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN seen_invite_reminder INTEGER DEFAULT 0");
}
if (oldVersion < INTRODUCED_CONVERSATION_LIST_THUMBNAILS_VERSION) {
db.execSQL("ALTER TABLE thread ADD COLUMN snippet_uri TEXT DEFAULT NULL");
}
db.setTransactionSuccessful();
db.endTransaction();
}
private void executeStatements(SQLiteDatabase db, String[] statements) {
for (String statement : statements)
db.execSQL(statement);
}
}
}
| 37,190 | 45.958333 | 249 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/DraftDatabase.java | package org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class DraftDatabase extends Database {
private static final String TABLE_NAME = "drafts";
public static final String ID = "_id";
public static final String THREAD_ID = "thread_id";
public static final String DRAFT_TYPE = "type";
public static final String DRAFT_VALUE = "value";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
THREAD_ID + " INTEGER, " + DRAFT_TYPE + " TEXT, " + DRAFT_VALUE + " TEXT);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS draft_thread_index ON " + TABLE_NAME + " (" + THREAD_ID + ");",
};
public DraftDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public void insertDrafts(MasterCipher masterCipher, long threadId, List<Draft> drafts) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
for (Draft draft : drafts) {
ContentValues values = new ContentValues(3);
values.put(THREAD_ID, threadId);
values.put(DRAFT_TYPE, masterCipher.encryptBody(draft.getType()));
values.put(DRAFT_VALUE, masterCipher.encryptBody(draft.getValue()));
db.insert(TABLE_NAME, null, values);
}
}
public void clearDrafts(long threadId) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, THREAD_ID + " = ?", new String[] {threadId+""});
}
public void clearDrafts(Set<Long> threadIds) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
StringBuilder where = new StringBuilder();
List<String> arguments = new LinkedList<>();
for (long threadId : threadIds) {
where.append(" OR ")
.append(THREAD_ID)
.append(" = ?");
arguments.add(String.valueOf(threadId));
}
db.delete(TABLE_NAME, where.toString().substring(4), arguments.toArray(new String[0]));
}
public void clearAllDrafts() {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
public List<Draft> getDrafts(MasterCipher masterCipher, long threadId) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
List<Draft> results = new LinkedList<Draft>();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, null, THREAD_ID + " = ?", new String[] {threadId+""}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
try {
String encryptedType = cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_TYPE));
String encryptedValue = cursor.getString(cursor.getColumnIndexOrThrow(DRAFT_VALUE));
results.add(new Draft(masterCipher.decryptBody(encryptedType),
masterCipher.decryptBody(encryptedValue)));
} catch (InvalidMessageException ime) {
Log.w("DraftDatabase", ime);
}
}
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
public static class Draft {
public static final String TEXT = "text";
public static final String IMAGE = "image";
public static final String VIDEO = "video";
public static final String AUDIO = "audio";
private final String type;
private final String value;
public Draft(String type, String value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
public String getSnippet(Context context) {
switch (type) {
case TEXT: return value;
case IMAGE: return context.getString(R.string.DraftDatabase_Draft_image_snippet);
case VIDEO: return context.getString(R.string.DraftDatabase_Draft_video_snippet);
case AUDIO: return context.getString(R.string.DraftDatabase_Draft_audio_snippet);
default: return null;
}
}
}
public static class Drafts extends LinkedList<Draft> {
private Draft getDraftOfType(String type) {
for (Draft draft : this) {
if (type.equals(draft.getType())) {
return draft;
}
}
return null;
}
public String getSnippet(Context context) {
Draft textDraft = getDraftOfType(Draft.TEXT);
if (textDraft != null) {
return textDraft.getSnippet(context);
} else if (size() > 0) {
return get(0).getSnippet(context);
} else {
return "";
}
}
public @Nullable Uri getUriSnippet(Context context) {
Draft imageDraft = getDraftOfType(Draft.IMAGE);
if (imageDraft != null && imageDraft.getValue() != null) {
return Uri.parse(imageDraft.getValue());
}
return null;
}
}
}
| 5,382 | 30.664706 | 120 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/EncryptedBackupExporter.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.database;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class EncryptedBackupExporter {
public static void exportToSd(Context context) throws NoExternalStorageException, IOException {
verifyExternalStorageForExport();
exportDirectory(context, "");
}
public static void importFromSd(Context context) throws NoExternalStorageException, IOException {
verifyExternalStorageForImport();
importDirectory(context, "");
}
private static String getExportDirectoryPath() {
File sdDirectory = Environment.getExternalStorageDirectory();
return sdDirectory.getAbsolutePath() + File.separator + "TextSecureExport";
}
private static void verifyExternalStorageForExport() throws NoExternalStorageException {
if (!Environment.getExternalStorageDirectory().canWrite())
throw new NoExternalStorageException();
String exportDirectoryPath = getExportDirectoryPath();
File exportDirectory = new File(exportDirectoryPath);
if (!exportDirectory.exists())
exportDirectory.mkdir();
}
private static void verifyExternalStorageForImport() throws NoExternalStorageException {
if (!Environment.getExternalStorageDirectory().canRead() ||
!(new File(getExportDirectoryPath()).exists()))
throw new NoExternalStorageException();
}
private static void migrateFile(File from, File to) {
try {
if (from.exists()) {
FileChannel source = new FileInputStream(from).getChannel();
FileChannel destination = new FileOutputStream(to).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
}
} catch (IOException ioe) {
Log.w("EncryptedBackupExporter", ioe);
}
}
private static void exportDirectory(Context context, String directoryName) throws IOException {
File directory = new File(context.getFilesDir().getParent() + File.separatorChar + directoryName);
File exportDirectory = new File(getExportDirectoryPath() + File.separatorChar + directoryName);
if (directory.exists()) {
exportDirectory.mkdirs();
File[] contents = directory.listFiles();
for (int i=0;i<contents.length;i++) {
File localFile = contents[i];
if (localFile.isFile()) {
File exportedFile = new File(exportDirectory.getAbsolutePath() + File.separator + localFile.getName());
migrateFile(localFile, exportedFile);
} else {
exportDirectory(context, directoryName + File.separator + localFile.getName());
}
}
} else {
Log.w("EncryptedBackupExporter", "Could not find directory: " + directory.getAbsolutePath());
}
}
private static void importDirectory(Context context, String directoryName) throws IOException {
File directory = new File(getExportDirectoryPath() + File.separator + directoryName);
File importDirectory = new File(context.getFilesDir().getParent() + File.separator + directoryName);
if (directory.exists() && directory.isDirectory()) {
importDirectory.mkdirs();
File[] contents = directory.listFiles();
for (File exportedFile : contents) {
if (exportedFile.isFile()) {
File localFile = new File(importDirectory.getAbsolutePath() + File.separator + exportedFile.getName());
migrateFile(exportedFile, localFile);
} else if (exportedFile.isDirectory()) {
importDirectory(context, directoryName + File.separator + exportedFile.getName());
}
}
}
}
}
| 4,487 | 35.786885 | 113 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/EncryptingSmsDatabase.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.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterCipher;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.database.model.DisplayRecord;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import org.thoughtcrime.securesms.sms.IncomingTextMessage;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage;
import org.thoughtcrime.securesms.util.LRUCache;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class EncryptingSmsDatabase extends SmsDatabase {
private final PlaintextCache plaintextCache = new PlaintextCache();
public EncryptingSmsDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
private String getAsymmetricEncryptedBody(AsymmetricMasterSecret masterSecret, String body) {
AsymmetricMasterCipher bodyCipher = new AsymmetricMasterCipher(masterSecret);
return bodyCipher.encryptBody(body);
}
private String getEncryptedBody(MasterSecret masterSecret, String body) {
MasterCipher bodyCipher = new MasterCipher(masterSecret);
String ciphertext = bodyCipher.encryptBody(body);
plaintextCache.put(ciphertext, body);
return ciphertext;
}
public long insertMessageOutbox(MasterSecretUnion masterSecret, long threadId,
OutgoingTextMessage message, boolean forceSms,
long timestamp)
{
long type = Types.BASE_OUTBOX_TYPE;
if (masterSecret.getMasterSecret().isPresent()) {
message = message.withBody(getEncryptedBody(masterSecret.getMasterSecret().get(), message.getMessageBody()));
type |= Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
message = message.withBody(getAsymmetricEncryptedBody(masterSecret.getAsymmetricMasterSecret().get(), message.getMessageBody()));
type |= Types.ENCRYPTION_ASYMMETRIC_BIT;
}
return insertMessageOutbox(threadId, message, type, forceSms, timestamp);
}
public Pair<Long, Long> insertMessageInbox(@NonNull MasterSecretUnion masterSecret,
@NonNull IncomingTextMessage message)
{
if (masterSecret.getMasterSecret().isPresent()) {
return insertMessageInbox(masterSecret.getMasterSecret().get(), message);
} else {
return insertMessageInbox(masterSecret.getAsymmetricMasterSecret().get(), message);
}
}
private Pair<Long, Long> insertMessageInbox(@NonNull MasterSecret masterSecret,
@NonNull IncomingTextMessage message)
{
long type = Types.BASE_INBOX_TYPE | Types.ENCRYPTION_SYMMETRIC_BIT;
message = message.withMessageBody(getEncryptedBody(masterSecret, message.getMessageBody()));
return insertMessageInbox(message, type);
}
private Pair<Long, Long> insertMessageInbox(@NonNull AsymmetricMasterSecret masterSecret,
@NonNull IncomingTextMessage message)
{
long type = Types.BASE_INBOX_TYPE | Types.ENCRYPTION_ASYMMETRIC_BIT;
message = message.withMessageBody(getAsymmetricEncryptedBody(masterSecret, message.getMessageBody()));
return insertMessageInbox(message, type);
}
public Pair<Long, Long> updateBundleMessageBody(MasterSecretUnion masterSecret, long messageId, String body) {
long type = Types.BASE_INBOX_TYPE | Types.SECURE_MESSAGE_BIT;
String encryptedBody;
if (masterSecret.getMasterSecret().isPresent()) {
encryptedBody = getEncryptedBody(masterSecret.getMasterSecret().get(), body);
type |= Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
encryptedBody = getAsymmetricEncryptedBody(masterSecret.getAsymmetricMasterSecret().get(), body);
type |= Types.ENCRYPTION_ASYMMETRIC_BIT;
}
return updateMessageBodyAndType(messageId, encryptedBody, Types.TOTAL_MASK, type);
}
public void updateMessageBody(MasterSecretUnion masterSecret, long messageId, String body) {
long type;
if (masterSecret.getMasterSecret().isPresent()) {
body = getEncryptedBody(masterSecret.getMasterSecret().get(), body);
type = Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
body = getAsymmetricEncryptedBody(masterSecret.getAsymmetricMasterSecret().get(), body);
type = Types.ENCRYPTION_ASYMMETRIC_BIT;
}
updateMessageBodyAndType(messageId, body, Types.ENCRYPTION_MASK, type);
}
public Reader getMessages(MasterSecret masterSecret, int skip, int limit) {
Cursor cursor = super.getMessages(skip, limit);
return new DecryptingReader(masterSecret, cursor);
}
public Reader getOutgoingMessages(MasterSecret masterSecret) {
Cursor cursor = super.getOutgoingMessages();
return new DecryptingReader(masterSecret, cursor);
}
public SmsMessageRecord getMessage(MasterSecret masterSecret, long messageId) throws NoSuchMessageException {
Cursor cursor = super.getMessage(messageId);
DecryptingReader reader = new DecryptingReader(masterSecret, cursor);
SmsMessageRecord record = reader.getNext();
reader.close();
if (record == null) throw new NoSuchMessageException("No message for ID: " + messageId);
else return record;
}
public Reader getDecryptInProgressMessages(MasterSecret masterSecret) {
Cursor cursor = super.getDecryptInProgressMessages();
return new DecryptingReader(masterSecret, cursor);
}
public Reader readerFor(MasterSecret masterSecret, Cursor cursor) {
return new DecryptingReader(masterSecret, cursor);
}
public class DecryptingReader extends SmsDatabase.Reader {
private final MasterCipher masterCipher;
public DecryptingReader(MasterSecret masterSecret, Cursor cursor) {
super(cursor);
this.masterCipher = new MasterCipher(masterSecret);
}
@Override
protected DisplayRecord.Body getBody(Cursor cursor) {
long type = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.TYPE));
String ciphertext = cursor.getString(cursor.getColumnIndexOrThrow(SmsDatabase.BODY));
if (ciphertext == null) {
return new DisplayRecord.Body("", true);
}
try {
if (SmsDatabase.Types.isSymmetricEncryption(type)) {
String plaintext = plaintextCache.get(ciphertext);
if (plaintext != null)
return new DisplayRecord.Body(plaintext, true);
plaintext = masterCipher.decryptBody(ciphertext);
plaintextCache.put(ciphertext, plaintext);
return new DisplayRecord.Body(plaintext, true);
} else {
return new DisplayRecord.Body(ciphertext, true);
}
} catch (InvalidMessageException e) {
Log.w("EncryptingSmsDatabase", e);
return new DisplayRecord.Body(context.getString(R.string.EncryptingSmsDatabase_error_decrypting_message), true);
}
}
}
private static class PlaintextCache {
private static final int MAX_CACHE_SIZE = 2000;
private static final Map<String, SoftReference<String>> decryptedBodyCache =
Collections.synchronizedMap(new LRUCache<String, SoftReference<String>>(MAX_CACHE_SIZE));
public void put(String ciphertext, String plaintext) {
decryptedBodyCache.put(ciphertext, new SoftReference<String>(plaintext));
}
public String get(String ciphertext) {
SoftReference<String> plaintextReference = decryptedBodyCache.get(ciphertext);
if (plaintextReference != null) {
String plaintext = plaintextReference.get();
if (plaintext != null) {
return plaintext;
}
}
return null;
}
}
}
| 9,008 | 37.173729 | 135 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/GroupDatabase.java | package org.thoughtcrime.securesms.database;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.textsecure.api.messages.TextSecureAttachmentPointer;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.LinkedList;
import java.util.List;
public class GroupDatabase extends Database {
public static final String DATABASE_UPDATE_ACTION = "org.thoughtcrime.securesms.database.GroupDatabase.UPDATE";
private static final String TAG = GroupDatabase.class.getSimpleName();
private static final String TABLE_NAME = "groups";
private static final String ID = "_id";
private static final String GROUP_ID = "group_id";
private static final String TITLE = "title";
private static final String MEMBERS = "members";
private static final String AVATAR = "avatar";
private static final String AVATAR_ID = "avatar_id";
private static final String AVATAR_KEY = "avatar_key";
private static final String AVATAR_CONTENT_TYPE = "avatar_content_type";
private static final String AVATAR_RELAY = "avatar_relay";
private static final String TIMESTAMP = "timestamp";
private static final String ACTIVE = "active";
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME +
" (" + ID + " INTEGER PRIMARY KEY, " +
GROUP_ID + " TEXT, " +
TITLE + " TEXT, " +
MEMBERS + " TEXT, " +
AVATAR + " BLOB, " +
AVATAR_ID + " INTEGER, " +
AVATAR_KEY + " BLOB, " +
AVATAR_CONTENT_TYPE + " TEXT, " +
AVATAR_RELAY + " TEXT, " +
TIMESTAMP + " INTEGER, " +
ACTIVE + " INTEGER DEFAULT 1);";
public static final String[] CREATE_INDEXS = {
"CREATE UNIQUE INDEX IF NOT EXISTS group_id_index ON " + TABLE_NAME + " (" + GROUP_ID + ");",
};
public GroupDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public @Nullable GroupRecord getGroup(byte[] groupId) {
@SuppressLint("Recycle")
Cursor cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, null, GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(groupId)},
null, null, null);
Reader reader = new Reader(cursor);
GroupRecord record = reader.getNext();
reader.close();
return record;
}
public Reader getGroupsFilteredByTitle(String constraint) {
Cursor cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, null, TITLE + " LIKE ?",
new String[]{"%" + constraint + "%"},
null, null, null);
return new Reader(cursor);
}
public Reader getGroups() {
Cursor cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
return new Reader(cursor);
}
public @NonNull Recipients getGroupMembers(byte[] groupId, boolean includeSelf) {
String localNumber = TextSecurePreferences.getLocalNumber(context);
List<String> members = getCurrentMembers(groupId);
List<Recipient> recipients = new LinkedList<>();
for (String member : members) {
if (!includeSelf && member.equals(localNumber))
continue;
recipients.addAll(RecipientFactory.getRecipientsFromString(context, member, false)
.getRecipientsList());
}
return RecipientFactory.getRecipientsFor(context, recipients, false);
}
public void create(byte[] groupId, String title, List<String> members,
TextSecureAttachmentPointer avatar, String relay)
{
ContentValues contentValues = new ContentValues();
contentValues.put(GROUP_ID, GroupUtil.getEncodedId(groupId));
contentValues.put(TITLE, title);
contentValues.put(MEMBERS, Util.join(members, ","));
if (avatar != null) {
contentValues.put(AVATAR_ID, avatar.getId());
contentValues.put(AVATAR_KEY, avatar.getKey());
contentValues.put(AVATAR_CONTENT_TYPE, avatar.getContentType());
}
contentValues.put(AVATAR_RELAY, relay);
contentValues.put(TIMESTAMP, System.currentTimeMillis());
contentValues.put(ACTIVE, 1);
databaseHelper.getWritableDatabase().insert(TABLE_NAME, null, contentValues);
}
public void update(byte[] groupId, String title, TextSecureAttachmentPointer avatar) {
ContentValues contentValues = new ContentValues();
if (title != null) contentValues.put(TITLE, title);
if (avatar != null) {
contentValues.put(AVATAR_ID, avatar.getId());
contentValues.put(AVATAR_CONTENT_TYPE, avatar.getContentType());
contentValues.put(AVATAR_KEY, avatar.getKey());
}
databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues,
GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(groupId)});
RecipientFactory.clearCache();
notifyDatabaseListeners();
}
public void updateTitle(byte[] groupId, String title) {
ContentValues contentValues = new ContentValues();
contentValues.put(TITLE, title);
databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues, GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(groupId)});
RecipientFactory.clearCache();
notifyDatabaseListeners();
}
public void updateAvatar(byte[] groupId, Bitmap avatar) {
updateAvatar(groupId, BitmapUtil.toByteArray(avatar));
}
public void updateAvatar(byte[] groupId, byte[] avatar) {
ContentValues contentValues = new ContentValues();
contentValues.put(AVATAR, avatar);
databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues, GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(groupId)});
RecipientFactory.clearCache();
notifyDatabaseListeners();
}
public void updateMembers(byte[] id, List<String> members) {
ContentValues contents = new ContentValues();
contents.put(MEMBERS, Util.join(members, ","));
contents.put(ACTIVE, 1);
databaseHelper.getWritableDatabase().update(TABLE_NAME, contents, GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(id)});
}
public void remove(byte[] id, String source) {
List<String> currentMembers = getCurrentMembers(id);
currentMembers.remove(source);
ContentValues contents = new ContentValues();
contents.put(MEMBERS, Util.join(currentMembers, ","));
databaseHelper.getWritableDatabase().update(TABLE_NAME, contents, GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(id)});
}
private List<String> getCurrentMembers(byte[] id) {
Cursor cursor = null;
try {
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[] {MEMBERS},
GROUP_ID + " = ?",
new String[] {GroupUtil.getEncodedId(id)},
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return Util.split(cursor.getString(cursor.getColumnIndexOrThrow(MEMBERS)), ",");
}
return new LinkedList<>();
} finally {
if (cursor != null)
cursor.close();
}
}
public boolean isActive(byte[] id) {
GroupRecord record = getGroup(id);
return record != null && record.isActive();
}
public void setActive(byte[] id, boolean active) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ACTIVE, active ? 1 : 0);
database.update(TABLE_NAME, values, GROUP_ID + " = ?", new String[] {GroupUtil.getEncodedId(id)});
}
public byte[] allocateGroupId() {
try {
byte[] groupId = new byte[16];
SecureRandom.getInstance("SHA1PRNG").nextBytes(groupId);
return groupId;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
private void notifyDatabaseListeners() {
Intent intent = new Intent(DATABASE_UPDATE_ACTION);
context.sendBroadcast(intent);
}
public static class Reader {
private final Cursor cursor;
public Reader(Cursor cursor) {
this.cursor = cursor;
}
public @Nullable GroupRecord getNext() {
if (cursor == null || !cursor.moveToNext()) {
return null;
}
return new GroupRecord(cursor.getString(cursor.getColumnIndexOrThrow(GROUP_ID)),
cursor.getString(cursor.getColumnIndexOrThrow(TITLE)),
cursor.getString(cursor.getColumnIndexOrThrow(MEMBERS)),
cursor.getBlob(cursor.getColumnIndexOrThrow(AVATAR)),
cursor.getLong(cursor.getColumnIndexOrThrow(AVATAR_ID)),
cursor.getBlob(cursor.getColumnIndexOrThrow(AVATAR_KEY)),
cursor.getString(cursor.getColumnIndexOrThrow(AVATAR_CONTENT_TYPE)),
cursor.getString(cursor.getColumnIndexOrThrow(AVATAR_RELAY)),
cursor.getInt(cursor.getColumnIndexOrThrow(ACTIVE)) == 1);
}
public void close() {
if (this.cursor != null)
this.cursor.close();
}
}
public static class GroupRecord {
private final String id;
private final String title;
private final List<String> members;
private final byte[] avatar;
private final long avatarId;
private final byte[] avatarKey;
private final String avatarContentType;
private final String relay;
private final boolean active;
public GroupRecord(String id, String title, String members, byte[] avatar,
long avatarId, byte[] avatarKey, String avatarContentType,
String relay, boolean active)
{
this.id = id;
this.title = title;
this.members = Util.split(members, ",");
this.avatar = avatar;
this.avatarId = avatarId;
this.avatarKey = avatarKey;
this.avatarContentType = avatarContentType;
this.relay = relay;
this.active = active;
}
public byte[] getId() {
try {
return GroupUtil.getDecodedId(id);
} catch (IOException ioe) {
throw new AssertionError(ioe);
}
}
public String getEncodedId() {
return id;
}
public String getTitle() {
return title;
}
public List<String> getMembers() {
return members;
}
public byte[] getAvatar() {
return avatar;
}
public long getAvatarId() {
return avatarId;
}
public byte[] getAvatarKey() {
return avatarKey;
}
public String getAvatarContentType() {
return avatarContentType;
}
public String getRelay() {
return relay;
}
public boolean isActive() {
return active;
}
}
}
| 12,397 | 34.524355 | 113 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/IdentityDatabase.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.Base64;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.InvalidKeyException;
import java.io.IOException;
public class IdentityDatabase extends Database {
private static final Uri CHANGE_URI = Uri.parse("content://textsecure/identities");
private static final String TABLE_NAME = "identities";
private static final String ID = "_id";
public static final String RECIPIENT = "recipient";
public static final String IDENTITY_KEY = "key";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + ID + " INTEGER PRIMARY KEY, " +
RECIPIENT + " INTEGER UNIQUE, " +
IDENTITY_KEY + " TEXT);";
public IdentityDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public Cursor getIdentities() {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);
if (cursor != null)
cursor.setNotificationUri(context.getContentResolver(), CHANGE_URI);
return cursor;
}
public boolean isValidIdentity(long recipientId,
IdentityKey theirIdentity)
{
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, null, RECIPIENT + " = ?",
new String[] {recipientId+""}, null, null,null);
if (cursor != null && cursor.moveToFirst()) {
String serializedIdentity = cursor.getString(cursor.getColumnIndexOrThrow(IDENTITY_KEY));
IdentityKey ourIdentity = new IdentityKey(Base64.decode(serializedIdentity), 0);
return ourIdentity.equals(theirIdentity);
} else {
return true;
}
} catch (IOException e) {
Log.w("IdentityDatabase", e);
return false;
} catch (InvalidKeyException e) {
Log.w("IdentityDatabase", e);
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void saveIdentity(long recipientId, IdentityKey identityKey)
{
SQLiteDatabase database = databaseHelper.getWritableDatabase();
String identityKeyString = Base64.encodeBytes(identityKey.serialize());
ContentValues contentValues = new ContentValues();
contentValues.put(RECIPIENT, recipientId);
contentValues.put(IDENTITY_KEY, identityKeyString);
database.replace(TABLE_NAME, null, contentValues);
context.getContentResolver().notifyChange(CHANGE_URI, null);
}
public void deleteIdentity(long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, ID_WHERE, new String[] {id+""});
context.getContentResolver().notifyChange(CHANGE_URI, null);
}
public Reader readerFor(Cursor cursor) {
return new Reader(cursor);
}
public class Reader {
private final Cursor cursor;
public Reader(Cursor cursor) {
this.cursor = cursor;
}
public Identity getCurrent() {
long recipientId = cursor.getLong(cursor.getColumnIndexOrThrow(RECIPIENT));
Recipients recipients = RecipientFactory.getRecipientsForIds(context, new long[]{recipientId}, true);
try {
String identityKeyString = cursor.getString(cursor.getColumnIndexOrThrow(IDENTITY_KEY));
IdentityKey identityKey = new IdentityKey(Base64.decode(identityKeyString), 0);
return new Identity(recipients, identityKey);
} catch (IOException e) {
Log.w("IdentityDatabase", e);
return new Identity(recipients, null);
} catch (InvalidKeyException e) {
Log.w("IdentityDatabase", e);
return new Identity(recipients, null);
}
}
}
public static class Identity {
private final Recipients recipients;
private final IdentityKey identityKey;
public Identity(Recipients recipients, IdentityKey identityKey) {
this.recipients = recipients;
this.identityKey = identityKey;
}
public Recipients getRecipients() {
return recipients;
}
public IdentityKey getIdentityKey() {
return identityKey;
}
}
}
| 5,434 | 32.140244 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/ImageDatabase.java | package org.thoughtcrime.securesms.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.AttachmentId;
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
public class ImageDatabase extends Database {
private final static String IMAGES_QUERY = "SELECT " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.CONTENT_TYPE + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.THUMBNAIL_ASPECT_RATIO + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.UNIQUE_ID + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.MMS_ID + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.TRANSFER_STATE + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.SIZE + ", "
+ AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.DATA + ", "
+ MmsDatabase.TABLE_NAME + "." + MmsDatabase.NORMALIZED_DATE_RECEIVED + ", "
+ MmsDatabase.TABLE_NAME + "." + MmsDatabase.ADDRESS + " "
+ "FROM " + AttachmentDatabase.TABLE_NAME + " LEFT JOIN " + MmsDatabase.TABLE_NAME
+ " ON " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.MMS_ID + " = " + MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " "
+ "WHERE " + AttachmentDatabase.MMS_ID + " IN (SELECT " + MmsSmsColumns.ID
+ " FROM " + MmsDatabase.TABLE_NAME
+ " WHERE " + MmsDatabase.THREAD_ID + " = ?) AND "
+ AttachmentDatabase.CONTENT_TYPE + " LIKE 'image/%' "
+ "ORDER BY " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " DESC";
public ImageDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public Cursor getImagesForThread(long threadId) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = database.rawQuery(IMAGES_QUERY, new String[]{threadId+""});
setNotifyConverationListeners(cursor, threadId);
return cursor;
}
public static class ImageRecord {
private final AttachmentId attachmentId;
private final long mmsId;
private final boolean hasData;
private final String contentType;
private final String address;
private final long date;
private final int transferState;
private final long size;
private ImageRecord(AttachmentId attachmentId, long mmsId, boolean hasData,
String contentType, String address, long date,
int transferState, long size)
{
this.attachmentId = attachmentId;
this.mmsId = mmsId;
this.hasData = hasData;
this.contentType = contentType;
this.address = address;
this.date = date;
this.transferState = transferState;
this.size = size;
}
public static ImageRecord from(Cursor cursor) {
AttachmentId attachmentId = new AttachmentId(cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.ROW_ID)),
cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.UNIQUE_ID)));
return new ImageRecord(attachmentId,
cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.MMS_ID)),
!cursor.isNull(cursor.getColumnIndexOrThrow(AttachmentDatabase.DATA)),
cursor.getString(cursor.getColumnIndexOrThrow(AttachmentDatabase.CONTENT_TYPE)),
cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.ADDRESS)),
cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.NORMALIZED_DATE_RECEIVED)),
cursor.getInt(cursor.getColumnIndexOrThrow(AttachmentDatabase.TRANSFER_STATE)),
cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.SIZE)));
}
public Attachment getAttachment() {
return new DatabaseAttachment(attachmentId, mmsId, hasData, contentType, transferState, size, null, null, null);
}
public String getContentType() {
return contentType;
}
public String getAddress() {
return address;
}
public long getDate() {
return date;
}
}
}
| 4,620 | 44.752475 | 144 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MessagingDatabase.java | package org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.database.documents.Document;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatchList;
import org.thoughtcrime.securesms.util.JsonUtils;
import org.whispersystems.libaxolotl.IdentityKey;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public abstract class MessagingDatabase extends Database implements MmsSmsColumns {
private static final String TAG = MessagingDatabase.class.getSimpleName();
public MessagingDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
protected abstract String getTableName();
public void setMismatchedIdentity(long messageId, final long recipientId, final IdentityKey identityKey) {
List<IdentityKeyMismatch> items = new ArrayList<IdentityKeyMismatch>() {{
add(new IdentityKeyMismatch(recipientId, identityKey));
}};
IdentityKeyMismatchList document = new IdentityKeyMismatchList(items);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
try {
setDocument(database, messageId, MISMATCHED_IDENTITIES, document);
database.setTransactionSuccessful();
} catch (IOException ioe) {
Log.w(TAG, ioe);
} finally {
database.endTransaction();
}
}
public void addMismatchedIdentity(long messageId, long recipientId, IdentityKey identityKey) {
try {
addToDocument(messageId, MISMATCHED_IDENTITIES,
new IdentityKeyMismatch(recipientId, identityKey),
IdentityKeyMismatchList.class);
} catch (IOException e) {
Log.w(TAG, e);
}
}
public void removeMismatchedIdentity(long messageId, long recipientId, IdentityKey identityKey) {
try {
removeFromDocument(messageId, MISMATCHED_IDENTITIES,
new IdentityKeyMismatch(recipientId, identityKey),
IdentityKeyMismatchList.class);
} catch (IOException e) {
Log.w(TAG, e);
}
}
protected <D extends Document<I>, I> void removeFromDocument(long messageId, String column, I object, Class<D> clazz) throws IOException {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
try {
D document = getDocument(database, messageId, column, clazz);
Iterator<I> iterator = document.getList().iterator();
while (iterator.hasNext()) {
I item = iterator.next();
if (item.equals(object)) {
iterator.remove();
break;
}
}
setDocument(database, messageId, column, document);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
protected <T extends Document<I>, I> void addToDocument(long messageId, String column, final I object, Class<T> clazz) throws IOException {
List<I> list = new ArrayList<I>() {{
add(object);
}};
addToDocument(messageId, column, list, clazz);
}
protected <T extends Document<I>, I> void addToDocument(long messageId, String column, List<I> objects, Class<T> clazz) throws IOException {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
try {
T document = getDocument(database, messageId, column, clazz);
document.getList().addAll(objects);
setDocument(database, messageId, column, document);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
private void setDocument(SQLiteDatabase database, long messageId, String column, Document document) throws IOException {
ContentValues contentValues = new ContentValues();
if (document == null || document.size() == 0) {
contentValues.put(column, (String)null);
} else {
contentValues.put(column, JsonUtils.toJson(document));
}
database.update(getTableName(), contentValues, ID_WHERE, new String[] {String.valueOf(messageId)});
}
private <D extends Document> D getDocument(SQLiteDatabase database, long messageId,
String column, Class<D> clazz)
{
Cursor cursor = null;
try {
cursor = database.query(getTableName(), new String[] {column},
ID_WHERE, new String[] {String.valueOf(messageId)},
null, null, null);
if (cursor != null && cursor.moveToNext()) {
String document = cursor.getString(cursor.getColumnIndexOrThrow(column));
try {
if (!TextUtils.isEmpty(document)) {
return JsonUtils.fromJson(document, clazz);
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
try {
return clazz.newInstance();
} catch (InstantiationException e) {
throw new AssertionError(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
} finally {
if (cursor != null)
cursor.close();
}
}
}
| 5,493 | 31.508876 | 142 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MmsAddressDatabase.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.util.LinkedList;
import java.util.List;
import ws.com.google.android.mms.pdu.PduHeaders;
public class MmsAddressDatabase extends Database {
private static final String TAG = MmsAddressDatabase.class.getSimpleName();
private static final String TABLE_NAME = "mms_addresses";
private static final String ID = "_id";
private static final String MMS_ID = "mms_id";
private static final String TYPE = "type";
private static final String ADDRESS = "address";
private static final String ADDRESS_CHARSET = "address_charset";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
MMS_ID + " INTEGER, " + TYPE + " INTEGER, " + ADDRESS + " TEXT, " +
ADDRESS_CHARSET + " INTEGER);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS mms_addresses_mms_id_index ON " + TABLE_NAME + " (" + MMS_ID + ");",
};
public MmsAddressDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
private void insertAddress(long messageId, int type, @NonNull String value) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MMS_ID, messageId);
contentValues.put(TYPE, type);
contentValues.put(ADDRESS, value);
contentValues.put(ADDRESS_CHARSET, "UTF-8");
database.insert(TABLE_NAME, null, contentValues);
}
private void insertAddress(long messageId, int type, @NonNull List<String> addresses) {
for (String address : addresses) {
insertAddress(messageId, type, address);
}
}
public void insertAddressesForId(long messageId, MmsAddresses addresses) {
if (addresses.getFrom() != null) {
insertAddress(messageId, PduHeaders.FROM, addresses.getFrom());
}
insertAddress(messageId, PduHeaders.TO, addresses.getTo());
insertAddress(messageId, PduHeaders.CC, addresses.getCc());
insertAddress(messageId, PduHeaders.BCC, addresses.getBcc());
}
public MmsAddresses getAddressesForId(long messageId) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
String from = null;
List<String> to = new LinkedList<>();
List<String> cc = new LinkedList<>();
List<String> bcc = new LinkedList<>();
try {
cursor = database.query(TABLE_NAME, null, MMS_ID + " = ?", new String[] {messageId+""}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
long type = cursor.getLong(cursor.getColumnIndexOrThrow(TYPE));
String address = cursor.getString(cursor.getColumnIndexOrThrow(ADDRESS));
if (type == PduHeaders.FROM) from = address;
if (type == PduHeaders.TO) to.add(address);
if (type == PduHeaders.CC) cc.add(address);
if (type == PduHeaders.BCC) bcc.add(address);
}
} finally {
if (cursor != null)
cursor.close();
}
return new MmsAddresses(from, to, cc, bcc);
}
public List<String> getAddressesListForId(long messageId) {
List<String> results = new LinkedList<>();
MmsAddresses addresses = getAddressesForId(messageId);
if (addresses.getFrom() != null) {
results.add(addresses.getFrom());
}
results.addAll(addresses.getTo());
results.addAll(addresses.getCc());
results.addAll(addresses.getBcc());
return results;
}
public Recipients getRecipientsForId(long messageId) {
List<String> numbers = getAddressesListForId(messageId);
List<Recipient> results = new LinkedList<>();
for (String number : numbers) {
if (!PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.equals(number)) {
results.add(RecipientFactory.getRecipientsFromString(context, number, false)
.getPrimaryRecipient());
}
}
return RecipientFactory.getRecipientsFor(context, results, false);
}
public void deleteAddressesForId(long messageId) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, MMS_ID + " = ?", new String[] {messageId+""});
}
public void deleteAllAddresses() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, null, null);
}
}
| 5,577 | 35.697368 | 113 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MmsAddresses.java | package org.thoughtcrime.securesms.database;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.LinkedList;
import java.util.List;
public class MmsAddresses {
private final @Nullable String from;
private final @NonNull List<String> to;
private final @NonNull List<String> cc;
private final @NonNull List<String> bcc;
public MmsAddresses(@Nullable String from, @NonNull List<String> to,
@NonNull List<String> cc, @NonNull List<String> bcc)
{
this.from = from;
this.to = to;
this.cc = cc;
this.bcc = bcc;
}
@NonNull
public List<String> getTo() {
return to;
}
@NonNull
public List<String> getCc() {
return cc;
}
@NonNull
public List<String> getBcc() {
return bcc;
}
@Nullable
public String getFrom() {
return from;
}
public static MmsAddresses forTo(@NonNull List<String> to) {
return new MmsAddresses(null, to, new LinkedList<String>(), new LinkedList<String>());
}
public static MmsAddresses forBcc(@NonNull List<String> bcc) {
return new MmsAddresses(null, new LinkedList<String>(), new LinkedList<String>(), bcc);
}
public static MmsAddresses forFrom(@NonNull String from) {
return new MmsAddresses(from, new LinkedList<String>(), new LinkedList<String>(), new LinkedList<String>());
}
}
| 1,384 | 23.298246 | 112 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MmsDatabase.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterCipher;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatchList;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.database.documents.NetworkFailureList;
import org.thoughtcrime.securesms.database.model.DisplayRecord;
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.thoughtcrime.securesms.database.model.NotificationMmsMessageRecord;
import org.thoughtcrime.securesms.jobs.TrimThreadJob;
import org.thoughtcrime.securesms.mms.IncomingMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingGroupMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage;
import org.thoughtcrime.securesms.mms.SlideDeck;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.JsonUtils;
import org.thoughtcrime.securesms.util.ServiceUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobManager;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import ws.com.google.android.mms.MmsException;
import ws.com.google.android.mms.pdu.NotificationInd;
import ws.com.google.android.mms.pdu.PduHeaders;
import static org.thoughtcrime.securesms.util.Util.canonicalizeNumber;
import static org.thoughtcrime.securesms.util.Util.canonicalizeNumberOrGroup;
public class MmsDatabase extends MessagingDatabase {
private static final String TAG = MmsDatabase.class.getSimpleName();
public static final String TABLE_NAME = "mms";
static final String DATE_SENT = "date";
static final String DATE_RECEIVED = "date_received";
public static final String MESSAGE_BOX = "msg_box";
static final String CONTENT_LOCATION = "ct_l";
static final String EXPIRY = "exp";
public static final String MESSAGE_TYPE = "m_type";
static final String MESSAGE_SIZE = "m_size";
static final String STATUS = "st";
static final String TRANSACTION_ID = "tr_id";
static final String PART_COUNT = "part_count";
static final String NETWORK_FAILURE = "network_failures";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
THREAD_ID + " INTEGER, " + DATE_SENT + " INTEGER, " + DATE_RECEIVED + " INTEGER, " + MESSAGE_BOX + " INTEGER, " +
READ + " INTEGER DEFAULT 0, " + "m_id" + " TEXT, " + "sub" + " TEXT, " +
"sub_cs" + " INTEGER, " + BODY + " TEXT, " + PART_COUNT + " INTEGER, " +
"ct_t" + " TEXT, " + CONTENT_LOCATION + " TEXT, " + ADDRESS + " TEXT, " +
ADDRESS_DEVICE_ID + " INTEGER, " +
EXPIRY + " INTEGER, " + "m_cls" + " TEXT, " + MESSAGE_TYPE + " INTEGER, " +
"v" + " INTEGER, " + MESSAGE_SIZE + " INTEGER, " + "pri" + " INTEGER, " +
"rr" + " INTEGER, " + "rpt_a" + " INTEGER, " + "resp_st" + " INTEGER, " +
STATUS + " INTEGER, " + TRANSACTION_ID + " TEXT, " + "retr_st" + " INTEGER, " +
"retr_txt" + " TEXT, " + "retr_txt_cs" + " INTEGER, " + "read_status" + " INTEGER, " +
"ct_cls" + " INTEGER, " + "resp_txt" + " TEXT, " + "d_tm" + " INTEGER, " +
RECEIPT_COUNT + " INTEGER DEFAULT 0, " + MISMATCHED_IDENTITIES + " TEXT DEFAULT NULL, " +
NETWORK_FAILURE + " TEXT DEFAULT NULL," + "d_rpt" + " INTEGER);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS mms_thread_id_index ON " + TABLE_NAME + " (" + THREAD_ID + ");",
"CREATE INDEX IF NOT EXISTS mms_read_index ON " + TABLE_NAME + " (" + READ + ");",
"CREATE INDEX IF NOT EXISTS mms_read_and_thread_id_index ON " + TABLE_NAME + "(" + READ + "," + THREAD_ID + ");",
"CREATE INDEX IF NOT EXISTS mms_message_box_index ON " + TABLE_NAME + " (" + MESSAGE_BOX + ");",
"CREATE INDEX IF NOT EXISTS mms_date_sent_index ON " + TABLE_NAME + " (" + DATE_SENT + ");",
"CREATE INDEX IF NOT EXISTS mms_thread_date_index ON " + TABLE_NAME + " (" + THREAD_ID + ", " + DATE_RECEIVED + ");"
};
private static final String[] MMS_PROJECTION = new String[] {
MmsDatabase.TABLE_NAME + "." + ID + " AS " + ID,
THREAD_ID, DATE_SENT + " AS " + NORMALIZED_DATE_SENT,
DATE_RECEIVED + " AS " + NORMALIZED_DATE_RECEIVED,
MESSAGE_BOX, READ,
CONTENT_LOCATION, EXPIRY, MESSAGE_TYPE,
MESSAGE_SIZE, STATUS, TRANSACTION_ID,
BODY, PART_COUNT, ADDRESS, ADDRESS_DEVICE_ID,
RECEIPT_COUNT, MISMATCHED_IDENTITIES, NETWORK_FAILURE,
AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " AS " + AttachmentDatabase.ATTACHMENT_ID_ALIAS,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE
};
private static final String RAW_ID_WHERE = TABLE_NAME + "._id = ?";
private final JobManager jobManager;
public MmsDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
this.jobManager = ApplicationContext.getInstance(context).getJobManager();
}
@Override
protected String getTableName() {
return TABLE_NAME;
}
public int getMessageCountForThread(long threadId) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, new String[] {"COUNT(*)"}, THREAD_ID + " = ?", new String[] {threadId+""}, null, null, null);
if (cursor != null && cursor.moveToFirst())
return cursor.getInt(0);
} finally {
if (cursor != null)
cursor.close();
}
return 0;
}
public void addFailures(long messageId, List<NetworkFailure> failure) {
try {
addToDocument(messageId, NETWORK_FAILURE, failure, NetworkFailureList.class);
} catch (IOException e) {
Log.w(TAG, e);
}
}
public void removeFailure(long messageId, NetworkFailure failure) {
try {
removeFromDocument(messageId, NETWORK_FAILURE, failure, NetworkFailureList.class);
} catch (IOException e) {
Log.w(TAG, e);
}
}
public void incrementDeliveryReceiptCount(String address, long timestamp) {
MmsAddressDatabase addressDatabase = DatabaseFactory.getMmsAddressDatabase(context);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, new String[] {ID, THREAD_ID, MESSAGE_BOX}, DATE_SENT + " = ?", new String[] {String.valueOf(timestamp)}, null, null, null, null);
while (cursor.moveToNext()) {
if (Types.isOutgoingMessageType(cursor.getLong(cursor.getColumnIndexOrThrow(MESSAGE_BOX)))) {
List<String> addresses = addressDatabase.getAddressesListForId(cursor.getLong(cursor.getColumnIndexOrThrow(ID)));
for (String storedAddress : addresses) {
try {
String ourAddress = canonicalizeNumber(context, address);
String theirAddress = canonicalizeNumberOrGroup(context, storedAddress);
if (ourAddress.equals(theirAddress) || GroupUtil.isEncodedGroup(theirAddress)) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(ID));
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(THREAD_ID));
database.execSQL("UPDATE " + TABLE_NAME + " SET " +
RECEIPT_COUNT + " = " + RECEIPT_COUNT + " + 1 WHERE " + ID + " = ?",
new String[] {String.valueOf(id)});
notifyConversationListeners(threadId);
}
} catch (InvalidNumberException e) {
Log.w("MmsDatabase", e);
}
}
}
}
} finally {
if (cursor != null)
cursor.close();
}
}
public long getThreadIdForMessage(long id) {
String sql = "SELECT " + THREAD_ID + " FROM " + TABLE_NAME + " WHERE " + ID + " = ?";
String[] sqlArgs = new String[] {id+""};
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, sqlArgs);
if (cursor != null && cursor.moveToFirst())
return cursor.getLong(0);
else
return -1;
} finally {
if (cursor != null)
cursor.close();
}
}
private long getThreadIdFor(IncomingMediaMessage retrieved) throws RecipientFormattingException, MmsException {
if (retrieved.getGroupId() != null) {
Recipients groupRecipients = RecipientFactory.getRecipientsFromString(context, retrieved.getGroupId(), true);
return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(groupRecipients);
}
String localNumber;
Set<String> group = new HashSet<>();
if (retrieved.getAddresses().getFrom() == null) {
throw new MmsException("FROM value in PduHeaders did not exist.");
}
group.add(retrieved.getAddresses().getFrom());
if (TextSecurePreferences.isPushRegistered(context)) {
localNumber = TextSecurePreferences.getLocalNumber(context);
} else {
localNumber = ServiceUtil.getTelephonyManager(context).getLine1Number();
}
for (String cc : retrieved.getAddresses().getCc()) {
PhoneNumberUtil.MatchType match;
if (localNumber == null) match = PhoneNumberUtil.MatchType.NO_MATCH;
else match = PhoneNumberUtil.getInstance().isNumberMatch(localNumber, cc);
if (match == PhoneNumberUtil.MatchType.NO_MATCH ||
match == PhoneNumberUtil.MatchType.NOT_A_NUMBER)
{
group.add(cc);
}
}
if (retrieved.getAddresses().getTo().size() > 1) {
for (String to : retrieved.getAddresses().getTo()) {
PhoneNumberUtil.MatchType match;
if (localNumber == null) match = PhoneNumberUtil.MatchType.NO_MATCH;
else match = PhoneNumberUtil.getInstance().isNumberMatch(localNumber, to);
if (match == PhoneNumberUtil.MatchType.NO_MATCH ||
match == PhoneNumberUtil.MatchType.NOT_A_NUMBER)
{
group.add(to);
}
}
}
String recipientsList = Util.join(group, ",");
Recipients recipients = RecipientFactory.getRecipientsFromString(context, recipientsList, false);
return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
}
private long getThreadIdFor(@NonNull NotificationInd notification) {
String fromString = notification.getFrom() != null && notification.getFrom().getTextString() != null
? Util.toIsoString(notification.getFrom().getTextString())
: "";
Recipients recipients = RecipientFactory.getRecipientsFromString(context, fromString, false);
if (recipients.isEmpty()) recipients = RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), false);
return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
}
private Cursor rawQuery(@NonNull String where, @Nullable String[] arguments) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
return database.rawQuery("SELECT " + Util.join(MMS_PROJECTION, ",") +
" FROM " + MmsDatabase.TABLE_NAME + " LEFT OUTER JOIN " + AttachmentDatabase.TABLE_NAME +
" ON (" + MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " = " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.MMS_ID + ")" +
" WHERE " + where, arguments);
}
public Cursor getMessage(long messageId) {
Cursor cursor = rawQuery(RAW_ID_WHERE, new String[] {messageId + ""});
setNotifyConverationListeners(cursor, getThreadIdForMessage(messageId));
return cursor;
}
public Reader getDecryptInProgressMessages(MasterSecret masterSecret) {
String where = MESSAGE_BOX + " & " + (Types.ENCRYPTION_ASYMMETRIC_BIT) + " != 0";
return readerFor(masterSecret, rawQuery(where, null));
}
private void updateMailboxBitmask(long id, long maskOff, long maskOn) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME +
" SET " + MESSAGE_BOX + " = (" + MESSAGE_BOX + " & " + (Types.TOTAL_MASK - maskOff) + " | " + maskOn + " )" +
" WHERE " + ID + " = ?", new String[] {id + ""});
}
public void markAsOutbox(long messageId) {
updateMailboxBitmask(messageId, Types.BASE_TYPE_MASK, Types.BASE_OUTBOX_TYPE);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsForcedSms(long messageId) {
updateMailboxBitmask(messageId, Types.PUSH_MESSAGE_BIT, Types.MESSAGE_FORCE_SMS_BIT);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsPendingInsecureSmsFallback(long messageId) {
updateMailboxBitmask(messageId, Types.BASE_TYPE_MASK, Types.BASE_PENDING_INSECURE_SMS_FALLBACK);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsSending(long messageId) {
updateMailboxBitmask(messageId, Types.BASE_TYPE_MASK, Types.BASE_SENDING_TYPE);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsSentFailed(long messageId) {
updateMailboxBitmask(messageId, Types.BASE_TYPE_MASK, Types.BASE_SENT_FAILED_TYPE);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsSent(long messageId) {
updateMailboxBitmask(messageId, Types.BASE_TYPE_MASK, Types.BASE_SENT_TYPE);
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markDownloadState(long messageId, long state) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(STATUS, state);
database.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {messageId + ""});
notifyConversationListeners(getThreadIdForMessage(messageId));
}
public void markAsNoSession(long messageId, long threadId) {
updateMailboxBitmask(messageId, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_NO_SESSION_BIT);
notifyConversationListeners(threadId);
}
public void markAsSecure(long messageId) {
updateMailboxBitmask(messageId, 0, Types.SECURE_MESSAGE_BIT);
}
public void markAsInsecure(long messageId) {
updateMailboxBitmask(messageId, Types.SECURE_MESSAGE_BIT, 0);
}
public void markAsPush(long messageId) {
updateMailboxBitmask(messageId, 0, Types.PUSH_MESSAGE_BIT);
}
public void markAsDecryptFailed(long messageId, long threadId) {
updateMailboxBitmask(messageId, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_FAILED_BIT);
notifyConversationListeners(threadId);
}
public void markAsDecryptDuplicate(long messageId, long threadId) {
updateMailboxBitmask(messageId, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_DUPLICATE_BIT);
notifyConversationListeners(threadId);
}
public void markAsLegacyVersion(long messageId, long threadId) {
updateMailboxBitmask(messageId, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_LEGACY_BIT);
notifyConversationListeners(threadId);
}
public void setMessagesRead(long threadId) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(READ, 1);
database.update(TABLE_NAME, contentValues, THREAD_ID + " = ?", new String[] {threadId + ""});
}
public void setAllMessagesRead() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(READ, 1);
database.update(TABLE_NAME, contentValues, null, null);
}
public void updateMessageBody(MasterSecretUnion masterSecret, long messageId, String body) {
body = getEncryptedBody(masterSecret, body);
long type;
if (masterSecret.getMasterSecret().isPresent()) {
type = Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
type = Types.ENCRYPTION_ASYMMETRIC_BIT;
}
updateMessageBodyAndType(messageId, body, Types.ENCRYPTION_MASK, type);
}
private Pair<Long, Long> updateMessageBodyAndType(long messageId, String body, long maskOff, long maskOn) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME + " SET " + BODY + " = ?, " +
MESSAGE_BOX + " = (" + MESSAGE_BOX + " & " + (Types.TOTAL_MASK - maskOff) + " | " + maskOn + ") " +
"WHERE " + ID + " = ?",
new String[] {body, messageId + ""});
long threadId = getThreadIdForMessage(messageId);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
notifyConversationListListeners();
return new Pair<>(messageId, threadId);
}
public Optional<NotificationInd> getNotification(long messageId) {
Cursor cursor = null;
try {
cursor = rawQuery(RAW_ID_WHERE, new String[] {String.valueOf(messageId)});
if (cursor != null && cursor.moveToNext()) {
PduHeaders headers = new PduHeaders();
PduHeadersBuilder builder = new PduHeadersBuilder(headers, cursor);
builder.addText(CONTENT_LOCATION, PduHeaders.CONTENT_LOCATION);
builder.addLong(NORMALIZED_DATE_SENT, PduHeaders.DATE);
builder.addLong(EXPIRY, PduHeaders.EXPIRY);
builder.addLong(MESSAGE_SIZE, PduHeaders.MESSAGE_SIZE);
builder.addText(TRANSACTION_ID, PduHeaders.TRANSACTION_ID);
return Optional.of(new NotificationInd(headers));
} else {
return Optional.absent();
}
} finally {
if (cursor != null)
cursor.close();
}
}
public OutgoingMediaMessage getOutgoingMessage(MasterSecret masterSecret, long messageId)
throws MmsException, NoSuchMessageException
{
MmsAddressDatabase addr = DatabaseFactory.getMmsAddressDatabase(context);
AttachmentDatabase attachmentDatabase = DatabaseFactory.getAttachmentDatabase(context);
Cursor cursor = null;
try {
cursor = rawQuery(RAW_ID_WHERE, new String[] {String.valueOf(messageId)});
if (cursor != null && cursor.moveToNext()) {
long outboxType = cursor.getLong(cursor.getColumnIndexOrThrow(MESSAGE_BOX));
String messageText = cursor.getString(cursor.getColumnIndexOrThrow(BODY));
long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(NORMALIZED_DATE_SENT));
List<Attachment> attachments = new LinkedList<Attachment>(attachmentDatabase.getAttachmentsForMessage(messageId));
MmsAddresses addresses = addr.getAddressesForId(messageId);
List<String> destinations = new LinkedList<>();
String body = getDecryptedBody(masterSecret, messageText, outboxType);
destinations.addAll(addresses.getBcc());
destinations.addAll(addresses.getCc());
destinations.addAll(addresses.getTo());
Recipients recipients = RecipientFactory.getRecipientsFromStrings(context, destinations, false);
if (body != null && (Types.isGroupQuit(outboxType) || Types.isGroupUpdate(outboxType))) {
return new OutgoingGroupMediaMessage(recipients, body, attachments, timestamp);
}
OutgoingMediaMessage message = new OutgoingMediaMessage(recipients, body, attachments, timestamp,
!addresses.getBcc().isEmpty() ? ThreadDatabase.DistributionTypes.BROADCAST :
ThreadDatabase.DistributionTypes.DEFAULT);
if (Types.isSecureType(outboxType)) {
return new OutgoingSecureMediaMessage(message);
}
return message;
}
throw new NoSuchMessageException("No record found for id: " + messageId);
} catch (IOException e) {
throw new MmsException(e);
} finally {
if (cursor != null)
cursor.close();
}
}
public long copyMessageInbox(MasterSecret masterSecret, long messageId) throws MmsException {
try {
OutgoingMediaMessage request = getOutgoingMessage(masterSecret, messageId);
ContentValues contentValues = new ContentValues();
contentValues.put(ADDRESS, request.getRecipients().getPrimaryRecipient().getNumber());
contentValues.put(DATE_SENT, request.getSentTimeMillis());
contentValues.put(MESSAGE_BOX, Types.BASE_INBOX_TYPE | Types.SECURE_MESSAGE_BIT | Types.ENCRYPTION_SYMMETRIC_BIT);
contentValues.put(THREAD_ID, getThreadIdForMessage(messageId));
contentValues.put(READ, 1);
contentValues.put(DATE_RECEIVED, contentValues.getAsLong(DATE_SENT));
List<Attachment> attachments = new LinkedList<>();
for (Attachment attachment : request.getAttachments()) {
DatabaseAttachment databaseAttachment = (DatabaseAttachment)attachment;
attachments.add(new DatabaseAttachment(databaseAttachment.getAttachmentId(),
databaseAttachment.getMmsId(),
databaseAttachment.hasData(),
databaseAttachment.getContentType(),
AttachmentDatabase.TRANSFER_PROGRESS_DONE,
databaseAttachment.getSize(),
databaseAttachment.getLocation(),
databaseAttachment.getKey(),
databaseAttachment.getRelay()));
}
return insertMediaMessage(new MasterSecretUnion(masterSecret),
MmsAddresses.forTo(request.getRecipients().toNumberStringList(false)),
request.getBody(),
attachments,
contentValues);
} catch (NoSuchMessageException e) {
throw new MmsException(e);
}
}
private Pair<Long, Long> insertMessageInbox(MasterSecretUnion masterSecret,
IncomingMediaMessage retrieved,
String contentLocation,
long threadId, long mailbox)
throws MmsException
{
if (threadId == -1 || retrieved.isGroupMessage()) {
try {
threadId = getThreadIdFor(retrieved);
} catch (RecipientFormattingException e) {
Log.w("MmsDatabase", e);
if (threadId == -1)
throw new MmsException(e);
}
}
ContentValues contentValues = new ContentValues();
contentValues.put(DATE_SENT, retrieved.getSentTimeMillis());
contentValues.put(ADDRESS, retrieved.getAddresses().getFrom());
contentValues.put(MESSAGE_BOX, mailbox);
contentValues.put(MESSAGE_TYPE, PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF);
contentValues.put(THREAD_ID, threadId);
contentValues.put(CONTENT_LOCATION, contentLocation);
contentValues.put(STATUS, Status.DOWNLOAD_INITIALIZED);
contentValues.put(DATE_RECEIVED, generatePduCompatTimestamp());
contentValues.put(PART_COUNT, retrieved.getAttachments().size());
contentValues.put(READ, 0);
if (!contentValues.containsKey(DATE_SENT)) {
contentValues.put(DATE_SENT, contentValues.getAsLong(DATE_RECEIVED));
}
long messageId = insertMediaMessage(masterSecret, retrieved.getAddresses(),
retrieved.getBody(), retrieved.getAttachments(),
contentValues);
DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
jobManager.add(new TrimThreadJob(context, threadId));
return new Pair<>(messageId, threadId);
}
public Pair<Long, Long> insertMessageInbox(MasterSecretUnion masterSecret,
IncomingMediaMessage retrieved,
String contentLocation, long threadId)
throws MmsException
{
long type = Types.BASE_INBOX_TYPE;
if (masterSecret.getMasterSecret().isPresent()) {
type |= Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
type |= Types.ENCRYPTION_ASYMMETRIC_BIT;
}
if (retrieved.isPushMessage()) {
type |= Types.PUSH_MESSAGE_BIT;
}
return insertMessageInbox(masterSecret, retrieved, contentLocation, threadId, type);
}
public Pair<Long, Long> insertSecureDecryptedMessageInbox(MasterSecretUnion masterSecret,
IncomingMediaMessage retrieved,
long threadId)
throws MmsException
{
long type = Types.BASE_INBOX_TYPE | Types.SECURE_MESSAGE_BIT;
if (masterSecret.getMasterSecret().isPresent()) {
type |= Types.ENCRYPTION_SYMMETRIC_BIT;
} else {
type |= Types.ENCRYPTION_ASYMMETRIC_BIT;
}
if (retrieved.isPushMessage()) {
type |= Types.PUSH_MESSAGE_BIT;
}
return insertMessageInbox(masterSecret, retrieved, "", threadId, type);
}
public Pair<Long, Long> insertMessageInbox(@NonNull NotificationInd notification) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
MmsAddressDatabase addressDatabase = DatabaseFactory.getMmsAddressDatabase(context);
long threadId = getThreadIdFor(notification);
PduHeaders headers = notification.getPduHeaders();
ContentValues contentValues = new ContentValues();
ContentValuesBuilder contentBuilder = new ContentValuesBuilder(contentValues);
Log.w(TAG, "Message received type: " + headers.getOctet(PduHeaders.MESSAGE_TYPE));
contentBuilder.add(CONTENT_LOCATION, headers.getTextString(PduHeaders.CONTENT_LOCATION));
contentBuilder.add(DATE_SENT, headers.getLongInteger(PduHeaders.DATE) * 1000L);
contentBuilder.add(EXPIRY, headers.getLongInteger(PduHeaders.EXPIRY));
contentBuilder.add(MESSAGE_SIZE, headers.getLongInteger(PduHeaders.MESSAGE_SIZE));
contentBuilder.add(TRANSACTION_ID, headers.getTextString(PduHeaders.TRANSACTION_ID));
contentBuilder.add(MESSAGE_TYPE, headers.getOctet(PduHeaders.MESSAGE_TYPE));
if (headers.getEncodedStringValue(PduHeaders.FROM) != null) {
contentBuilder.add(ADDRESS, headers.getEncodedStringValue(PduHeaders.FROM).getTextString());
} else {
contentBuilder.add(ADDRESS, null);
}
contentValues.put(MESSAGE_BOX, Types.BASE_INBOX_TYPE);
contentValues.put(THREAD_ID, threadId);
contentValues.put(STATUS, Status.DOWNLOAD_INITIALIZED);
contentValues.put(DATE_RECEIVED, generatePduCompatTimestamp());
contentValues.put(READ, Util.isDefaultSmsProvider(context) ? 0 : 1);
if (!contentValues.containsKey(DATE_SENT))
contentValues.put(DATE_SENT, contentValues.getAsLong(DATE_RECEIVED));
long messageId = db.insert(TABLE_NAME, null, contentValues);
addressDatabase.insertAddressesForId(messageId, MmsAddresses.forFrom(Util.toIsoString(notification.getFrom().getTextString())));
return new Pair<>(messageId, threadId);
}
public void markIncomingNotificationReceived(long threadId) {
notifyConversationListeners(threadId);
DatabaseFactory.getThreadDatabase(context).update(threadId);
if (org.thoughtcrime.securesms.util.Util.isDefaultSmsProvider(context)) {
DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
}
jobManager.add(new TrimThreadJob(context, threadId));
}
public long insertMessageOutbox(@NonNull MasterSecretUnion masterSecret,
@NonNull OutgoingMediaMessage message,
long threadId, boolean forceSms)
throws MmsException
{
long type = Types.BASE_OUTBOX_TYPE;
if (masterSecret.getMasterSecret().isPresent()) type |= Types.ENCRYPTION_SYMMETRIC_BIT;
else type |= Types.ENCRYPTION_ASYMMETRIC_BIT;
if (message.isSecure()) type |= Types.SECURE_MESSAGE_BIT;
if (forceSms) type |= Types.MESSAGE_FORCE_SMS_BIT;
if (message.isGroup()) {
if (((OutgoingGroupMediaMessage)message).isGroupUpdate()) type |= Types.GROUP_UPDATE_BIT;
else if (((OutgoingGroupMediaMessage)message).isGroupQuit()) type |= Types.GROUP_QUIT_BIT;
}
List<String> recipientNumbers = message.getRecipients().toNumberStringList(true);
MmsAddresses addresses;
if (!message.getRecipients().isSingleRecipient() &&
message.getDistributionType() == ThreadDatabase.DistributionTypes.BROADCAST)
{
addresses = MmsAddresses.forBcc(recipientNumbers);
} else {
addresses = MmsAddresses.forTo(recipientNumbers);
}
ContentValues contentValues = new ContentValues();
contentValues.put(DATE_SENT, message.getSentTimeMillis());
contentValues.put(MESSAGE_TYPE, PduHeaders.MESSAGE_TYPE_SEND_REQ);
contentValues.put(MESSAGE_BOX, type);
contentValues.put(THREAD_ID, threadId);
contentValues.put(READ, 1);
contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
contentValues.remove(ADDRESS);
long messageId = insertMediaMessage(masterSecret, addresses, message.getBody(),
message.getAttachments(), contentValues);
jobManager.add(new TrimThreadJob(context, threadId));
return messageId;
}
private String getEncryptedBody(MasterSecretUnion masterSecret, String body) {
if (masterSecret.getMasterSecret().isPresent()) {
return new MasterCipher(masterSecret.getMasterSecret().get()).encryptBody(body);
} else {
return new AsymmetricMasterCipher(masterSecret.getAsymmetricMasterSecret().get()).encryptBody(body);
}
}
private @Nullable String getDecryptedBody(@NonNull MasterSecret masterSecret,
@Nullable String body, long outboxType)
{
try {
if (!TextUtils.isEmpty(body) && Types.isSymmetricEncryption(outboxType)) {
MasterCipher masterCipher = new MasterCipher(masterSecret);
return masterCipher.decryptBody(body);
} else {
return body;
}
} catch (InvalidMessageException e) {
Log.w(TAG, e);
}
return null;
}
private long insertMediaMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull MmsAddresses addresses,
@Nullable String body,
@NonNull List<Attachment> attachments,
@NonNull ContentValues contentValues)
throws MmsException
{
SQLiteDatabase db = databaseHelper.getWritableDatabase();
AttachmentDatabase partsDatabase = DatabaseFactory.getAttachmentDatabase(context);
MmsAddressDatabase addressDatabase = DatabaseFactory.getMmsAddressDatabase(context);
if (Types.isSymmetricEncryption(contentValues.getAsLong(MESSAGE_BOX)) ||
Types.isAsymmetricEncryption(contentValues.getAsLong(MESSAGE_BOX)))
{
if (!TextUtils.isEmpty(body)) {
contentValues.put(BODY, getEncryptedBody(masterSecret, body));
}
}
contentValues.put(PART_COUNT, attachments.size());
db.beginTransaction();
try {
long messageId = db.insert(TABLE_NAME, null, contentValues);
addressDatabase.insertAddressesForId(messageId, addresses);
partsDatabase.insertAttachmentsForMessage(masterSecret, messageId, attachments);
db.setTransactionSuccessful();
return messageId;
} finally {
db.endTransaction();
notifyConversationListeners(contentValues.getAsLong(THREAD_ID));
DatabaseFactory.getThreadDatabase(context).update(contentValues.getAsLong(THREAD_ID));
}
}
public boolean delete(long messageId) {
long threadId = getThreadIdForMessage(messageId);
MmsAddressDatabase addrDatabase = DatabaseFactory.getMmsAddressDatabase(context);
AttachmentDatabase attachmentDatabase = DatabaseFactory.getAttachmentDatabase(context);
attachmentDatabase.deleteAttachmentsForMessage(messageId);
addrDatabase.deleteAddressesForId(messageId);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, ID_WHERE, new String[] {messageId+""});
boolean threadDeleted = DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
return threadDeleted;
}
public void deleteThread(long threadId) {
Set<Long> singleThreadSet = new HashSet<>();
singleThreadSet.add(threadId);
deleteThreads(singleThreadSet);
}
/*package*/ void deleteThreads(Set<Long> threadIds) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String where = "";
Cursor cursor = null;
for (long threadId : threadIds) {
where += THREAD_ID + " = '" + threadId + "' OR ";
}
where = where.substring(0, where.length() - 4);
try {
cursor = db.query(TABLE_NAME, new String[] {ID}, where, null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
delete(cursor.getLong(0));
}
} finally {
if (cursor != null)
cursor.close();
}
}
/*package*/void deleteMessagesInThreadBeforeDate(long threadId, long date) {
Cursor cursor = null;
try {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String where = THREAD_ID + " = ? AND (CASE (" + MESSAGE_BOX + " & " + Types.BASE_TYPE_MASK + ") ";
for (long outgoingType : Types.OUTGOING_MESSAGE_TYPES) {
where += " WHEN " + outgoingType + " THEN " + DATE_SENT + " < " + date;
}
where += (" ELSE " + DATE_RECEIVED + " < " + date + " END)");
Log.w("MmsDatabase", "Executing trim query: " + where);
cursor = db.query(TABLE_NAME, new String[] {ID}, where, new String[] {threadId+""}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
Log.w("MmsDatabase", "Trimming: " + cursor.getLong(0));
delete(cursor.getLong(0));
}
} finally {
if (cursor != null)
cursor.close();
}
}
public void deleteAllThreads() {
DatabaseFactory.getAttachmentDatabase(context).deleteAllAttachments();
DatabaseFactory.getMmsAddressDatabase(context).deleteAllAddresses();
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.delete(TABLE_NAME, null, null);
}
public Cursor getCarrierMmsInformation(String apn) {
Uri uri = Uri.withAppendedPath(Uri.parse("content://telephony/carriers"), "current");
String selection = TextUtils.isEmpty(apn) ? null : "apn = ?";
String[] selectionArgs = TextUtils.isEmpty(apn) ? null : new String[] {apn.trim()};
try {
return context.getContentResolver().query(uri, null, selection, selectionArgs, null);
} catch (NullPointerException npe) {
// NOTE - This is dumb, but on some devices there's an NPE in the Android framework
// for the provider of this call, which gets rethrown back to here through a binder
// call.
throw new IllegalArgumentException(npe);
}
}
public Reader readerFor(MasterSecret masterSecret, Cursor cursor) {
return new Reader(masterSecret, cursor);
}
public static class Status {
public static final int DOWNLOAD_INITIALIZED = 1;
public static final int DOWNLOAD_NO_CONNECTIVITY = 2;
public static final int DOWNLOAD_CONNECTING = 3;
public static final int DOWNLOAD_SOFT_FAILURE = 4;
public static final int DOWNLOAD_HARD_FAILURE = 5;
public static final int DOWNLOAD_APN_UNAVAILABLE = 6;
public static boolean isDisplayDownloadButton(int status) {
return
status == DOWNLOAD_INITIALIZED ||
status == DOWNLOAD_NO_CONNECTIVITY ||
status == DOWNLOAD_SOFT_FAILURE;
}
public static String getLabelForStatus(Context context, int status) {
switch (status) {
case DOWNLOAD_CONNECTING: return context.getString(R.string.MmsDatabase_connecting_to_mms_server);
case DOWNLOAD_INITIALIZED: return context.getString(R.string.MmsDatabase_downloading_mms);
case DOWNLOAD_HARD_FAILURE: return context.getString(R.string.MmsDatabase_mms_download_failed);
case DOWNLOAD_APN_UNAVAILABLE: return context.getString(R.string.MmsDatabase_mms_pending_download);
}
return context.getString(R.string.MmsDatabase_downloading);
}
public static boolean isHardError(int status) {
return status == DOWNLOAD_HARD_FAILURE;
}
}
public class Reader {
private final Cursor cursor;
private final MasterSecret masterSecret;
private final MasterCipher masterCipher;
public Reader(MasterSecret masterSecret, Cursor cursor) {
this.cursor = cursor;
this.masterSecret = masterSecret;
if (masterSecret != null) masterCipher = new MasterCipher(masterSecret);
else masterCipher = null;
}
public MessageRecord getNext() {
if (cursor == null || !cursor.moveToNext())
return null;
return getCurrent();
}
public MessageRecord getCurrent() {
long mmsType = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_TYPE));
if (mmsType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) {
return getNotificationMmsMessageRecord(cursor);
} else {
return getMediaMmsMessageRecord(cursor);
}
}
private NotificationMmsMessageRecord getNotificationMmsMessageRecord(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.ID));
long dateSent = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.NORMALIZED_DATE_SENT));
long dateReceived = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.NORMALIZED_DATE_RECEIVED));
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.THREAD_ID));
long mailbox = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_BOX));
String address = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.ADDRESS));
int addressDeviceId = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.ADDRESS_DEVICE_ID));
Recipients recipients = getRecipientsFor(address);
String contentLocation = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.CONTENT_LOCATION));
String transactionId = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.TRANSACTION_ID));
long messageSize = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_SIZE));
long expiry = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.EXPIRY));
int status = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.STATUS));
int receiptCount = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.RECEIPT_COUNT));
byte[]contentLocationBytes = null;
byte[]transactionIdBytes = null;
if (!TextUtils.isEmpty(contentLocation))
contentLocationBytes = org.thoughtcrime.securesms.util.Util.toIsoBytes(contentLocation);
if (!TextUtils.isEmpty(transactionId))
transactionIdBytes = org.thoughtcrime.securesms.util.Util.toIsoBytes(transactionId);
return new NotificationMmsMessageRecord(context, id, recipients, recipients.getPrimaryRecipient(),
addressDeviceId, dateSent, dateReceived, receiptCount, threadId,
contentLocationBytes, messageSize, expiry, status,
transactionIdBytes, mailbox);
}
private MediaMmsMessageRecord getMediaMmsMessageRecord(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.ID));
long dateSent = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.NORMALIZED_DATE_SENT));
long dateReceived = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.NORMALIZED_DATE_RECEIVED));
long box = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_BOX));
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.THREAD_ID));
String address = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.ADDRESS));
int addressDeviceId = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.ADDRESS_DEVICE_ID));
int receiptCount = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.RECEIPT_COUNT));
DisplayRecord.Body body = getBody(cursor);
int partCount = cursor.getInt(cursor.getColumnIndexOrThrow(MmsDatabase.PART_COUNT));
String mismatchDocument = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.MISMATCHED_IDENTITIES));
String networkDocument = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.NETWORK_FAILURE));
Recipients recipients = getRecipientsFor(address);
List<IdentityKeyMismatch> mismatches = getMismatchedIdentities(mismatchDocument);
List<NetworkFailure> networkFailures = getFailures(networkDocument);
SlideDeck slideDeck = getSlideDeck(cursor);
return new MediaMmsMessageRecord(context, id, recipients, recipients.getPrimaryRecipient(),
addressDeviceId, dateSent, dateReceived, receiptCount,
threadId, body, slideDeck, partCount, box, mismatches, networkFailures);
}
private Recipients getRecipientsFor(String address) {
if (TextUtils.isEmpty(address) || address.equals("insert-address-token")) {
return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
}
Recipients recipients = RecipientFactory.getRecipientsFromString(context, address, true);
if (recipients == null || recipients.isEmpty()) {
return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
}
return recipients;
}
private List<IdentityKeyMismatch> getMismatchedIdentities(String document) {
if (!TextUtils.isEmpty(document)) {
try {
return JsonUtils.fromJson(document, IdentityKeyMismatchList.class).getList();
} catch (IOException e) {
Log.w(TAG, e);
}
}
return new LinkedList<>();
}
private List<NetworkFailure> getFailures(String document) {
if (!TextUtils.isEmpty(document)) {
try {
return JsonUtils.fromJson(document, NetworkFailureList.class).getList();
} catch (IOException ioe) {
Log.w(TAG, ioe);
}
}
return new LinkedList<>();
}
private DisplayRecord.Body getBody(Cursor cursor) {
try {
String body = cursor.getString(cursor.getColumnIndexOrThrow(MmsDatabase.BODY));
long box = cursor.getLong(cursor.getColumnIndexOrThrow(MmsDatabase.MESSAGE_BOX));
if (!TextUtils.isEmpty(body) && masterCipher != null && Types.isSymmetricEncryption(box)) {
return new DisplayRecord.Body(masterCipher.decryptBody(body), true);
} else if (!TextUtils.isEmpty(body) && masterCipher == null && Types.isSymmetricEncryption(box)) {
return new DisplayRecord.Body(body, false);
} else if (!TextUtils.isEmpty(body) && Types.isAsymmetricEncryption(box)) {
return new DisplayRecord.Body(body, false);
} else {
return new DisplayRecord.Body(body == null ? "" : body, true);
}
} catch (InvalidMessageException e) {
Log.w("MmsDatabase", e);
return new DisplayRecord.Body(context.getString(R.string.MmsDatabase_error_decrypting_message), true);
}
}
private SlideDeck getSlideDeck(@NonNull Cursor cursor) {
Attachment attachment = DatabaseFactory.getAttachmentDatabase(context).getAttachment(cursor);
return new SlideDeck(context, attachment);
}
public void close() {
cursor.close();
}
}
private long generatePduCompatTimestamp() {
final long time = System.currentTimeMillis();
return time - (time % 1000);
}
}
| 47,667 | 42.099458 | 171 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MmsSmsColumns.java | package org.thoughtcrime.securesms.database;
public interface MmsSmsColumns {
public static final String ID = "_id";
public static final String NORMALIZED_DATE_SENT = "date_sent";
public static final String NORMALIZED_DATE_RECEIVED = "date_received";
public static final String THREAD_ID = "thread_id";
public static final String READ = "read";
public static final String BODY = "body";
public static final String ADDRESS = "address";
public static final String ADDRESS_DEVICE_ID = "address_device_id";
public static final String RECEIPT_COUNT = "delivery_receipt_count";
public static final String MISMATCHED_IDENTITIES = "mismatched_identities";
public static class Types {
protected static final long TOTAL_MASK = 0xFFFFFFFF;
// Base Types
protected static final long BASE_TYPE_MASK = 0x1F;
protected static final long INCOMING_CALL_TYPE = 1;
protected static final long OUTGOING_CALL_TYPE = 2;
protected static final long MISSED_CALL_TYPE = 3;
protected static final long JOINED_TYPE = 4;
protected static final long BASE_INBOX_TYPE = 20;
protected static final long BASE_OUTBOX_TYPE = 21;
protected static final long BASE_SENDING_TYPE = 22;
protected static final long BASE_SENT_TYPE = 23;
protected static final long BASE_SENT_FAILED_TYPE = 24;
protected static final long BASE_PENDING_SECURE_SMS_FALLBACK = 25;
protected static final long BASE_PENDING_INSECURE_SMS_FALLBACK = 26;
public static final long BASE_DRAFT_TYPE = 27;
protected static final long[] OUTGOING_MESSAGE_TYPES = {BASE_OUTBOX_TYPE, BASE_SENT_TYPE,
BASE_SENDING_TYPE, BASE_SENT_FAILED_TYPE,
BASE_PENDING_SECURE_SMS_FALLBACK,
BASE_PENDING_INSECURE_SMS_FALLBACK};
// Message attributes
protected static final long MESSAGE_ATTRIBUTE_MASK = 0xE0;
protected static final long MESSAGE_FORCE_SMS_BIT = 0x40;
// Key Exchange Information
protected static final long KEY_EXCHANGE_MASK = 0xFF00;
protected static final long KEY_EXCHANGE_BIT = 0x8000;
protected static final long KEY_EXCHANGE_STALE_BIT = 0x4000;
protected static final long KEY_EXCHANGE_PROCESSED_BIT = 0x2000;
protected static final long KEY_EXCHANGE_CORRUPTED_BIT = 0x1000;
protected static final long KEY_EXCHANGE_INVALID_VERSION_BIT = 0x800;
protected static final long KEY_EXCHANGE_BUNDLE_BIT = 0x400;
protected static final long KEY_EXCHANGE_IDENTITY_UPDATE_BIT = 0x200;
// Secure Message Information
protected static final long SECURE_MESSAGE_BIT = 0x800000;
protected static final long END_SESSION_BIT = 0x400000;
protected static final long PUSH_MESSAGE_BIT = 0x200000;
// Group Message Information
protected static final long GROUP_UPDATE_BIT = 0x10000;
protected static final long GROUP_QUIT_BIT = 0x20000;
// Encrypted Storage Information
protected static final long ENCRYPTION_MASK = 0xFF000000;
protected static final long ENCRYPTION_SYMMETRIC_BIT = 0x80000000;
protected static final long ENCRYPTION_ASYMMETRIC_BIT = 0x40000000;
protected static final long ENCRYPTION_REMOTE_BIT = 0x20000000;
protected static final long ENCRYPTION_REMOTE_FAILED_BIT = 0x10000000;
protected static final long ENCRYPTION_REMOTE_NO_SESSION_BIT = 0x08000000;
protected static final long ENCRYPTION_REMOTE_DUPLICATE_BIT = 0x04000000;
protected static final long ENCRYPTION_REMOTE_LEGACY_BIT = 0x02000000;
public static boolean isDraftMessageType(long type) {
return (type & BASE_TYPE_MASK) == BASE_DRAFT_TYPE;
}
public static boolean isFailedMessageType(long type) {
return (type & BASE_TYPE_MASK) == BASE_SENT_FAILED_TYPE;
}
public static boolean isOutgoingMessageType(long type) {
for (long outgoingType : OUTGOING_MESSAGE_TYPES) {
if ((type & BASE_TYPE_MASK) == outgoingType)
return true;
}
return false;
}
public static boolean isForcedSms(long type) {
return (type & MESSAGE_FORCE_SMS_BIT) != 0;
}
public static boolean isPendingMessageType(long type) {
return
(type & BASE_TYPE_MASK) == BASE_OUTBOX_TYPE ||
(type & BASE_TYPE_MASK) == BASE_SENDING_TYPE;
}
public static boolean isPendingSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_INSECURE_SMS_FALLBACK ||
(type & BASE_TYPE_MASK) == BASE_PENDING_SECURE_SMS_FALLBACK;
}
public static boolean isPendingSecureSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_SECURE_SMS_FALLBACK;
}
public static boolean isPendingInsecureSmsFallbackType(long type) {
return (type & BASE_TYPE_MASK) == BASE_PENDING_INSECURE_SMS_FALLBACK;
}
public static boolean isInboxType(long type) {
return (type & BASE_TYPE_MASK) == BASE_INBOX_TYPE;
}
public static boolean isJoinedType(long type) {
return (type & BASE_TYPE_MASK) == JOINED_TYPE;
}
public static boolean isSecureType(long type) {
return (type & SECURE_MESSAGE_BIT) != 0;
}
public static boolean isPushType(long type) {
return (type & PUSH_MESSAGE_BIT) != 0;
}
public static boolean isEndSessionType(long type) {
return (type & END_SESSION_BIT) != 0;
}
public static boolean isKeyExchangeType(long type) {
return (type & KEY_EXCHANGE_BIT) != 0;
}
public static boolean isStaleKeyExchange(long type) {
return (type & KEY_EXCHANGE_STALE_BIT) != 0;
}
public static boolean isProcessedKeyExchange(long type) {
return (type & KEY_EXCHANGE_PROCESSED_BIT) != 0;
}
public static boolean isCorruptedKeyExchange(long type) {
return (type & KEY_EXCHANGE_CORRUPTED_BIT) != 0;
}
public static boolean isInvalidVersionKeyExchange(long type) {
return (type & KEY_EXCHANGE_INVALID_VERSION_BIT) != 0;
}
public static boolean isBundleKeyExchange(long type) {
return (type & KEY_EXCHANGE_BUNDLE_BIT) != 0;
}
public static boolean isIdentityUpdate(long type) {
return (type & KEY_EXCHANGE_IDENTITY_UPDATE_BIT) != 0;
}
public static boolean isCallLog(long type) {
return type == INCOMING_CALL_TYPE || type == OUTGOING_CALL_TYPE || type == MISSED_CALL_TYPE;
}
public static boolean isIncomingCall(long type) {
return type == INCOMING_CALL_TYPE;
}
public static boolean isOutgoingCall(long type) {
return type == OUTGOING_CALL_TYPE;
}
public static boolean isMissedCall(long type) {
return type == MISSED_CALL_TYPE;
}
public static boolean isGroupUpdate(long type) {
return (type & GROUP_UPDATE_BIT) != 0;
}
public static boolean isGroupQuit(long type) {
return (type & GROUP_QUIT_BIT) != 0;
}
public static boolean isSymmetricEncryption(long type) {
return (type & ENCRYPTION_SYMMETRIC_BIT) != 0;
}
public static boolean isAsymmetricEncryption(long type) {
return (type & ENCRYPTION_ASYMMETRIC_BIT) != 0;
}
public static boolean isFailedDecryptType(long type) {
return (type & ENCRYPTION_REMOTE_FAILED_BIT) != 0;
}
public static boolean isDuplicateMessageType(long type) {
return (type & ENCRYPTION_REMOTE_DUPLICATE_BIT) != 0;
}
public static boolean isDecryptInProgressType(long type) {
return (type & ENCRYPTION_ASYMMETRIC_BIT) != 0;
}
public static boolean isNoRemoteSessionType(long type) {
return (type & ENCRYPTION_REMOTE_NO_SESSION_BIT) != 0;
}
public static boolean isLegacyType(long type) {
return (type & ENCRYPTION_REMOTE_LEGACY_BIT) != 0 ||
(type & ENCRYPTION_REMOTE_BIT) != 0;
}
public static long translateFromSystemBaseType(long theirType) {
// public static final int NONE_TYPE = 0;
// public static final int INBOX_TYPE = 1;
// public static final int SENT_TYPE = 2;
// public static final int SENT_PENDING = 4;
// public static final int FAILED_TYPE = 5;
switch ((int)theirType) {
case 1: return BASE_INBOX_TYPE;
case 2: return BASE_SENT_TYPE;
case 3: return BASE_DRAFT_TYPE;
case 4: return BASE_OUTBOX_TYPE;
case 5: return BASE_SENT_FAILED_TYPE;
case 6: return BASE_OUTBOX_TYPE;
}
return BASE_INBOX_TYPE;
}
public static int translateToSystemBaseType(long type) {
if (isInboxType(type)) return 1;
else if (isOutgoingMessageType(type)) return 2;
else if (isFailedMessageType(type)) return 5;
return 1;
}
//
//
//
// public static final int NONE_TYPE = 0;
// public static final int INBOX_TYPE = 1;
// public static final int SENT_TYPE = 2;
// public static final int SENT_PENDING = 4;
// public static final int FAILED_TYPE = 5;
//
// public static final int OUTBOX_TYPE = 43; // Messages are stored local encrypted and need delivery.
//
//
// public static final int ENCRYPTING_TYPE = 42; // Messages are stored local encrypted and need async encryption and delivery.
// public static final int SECURE_SENT_TYPE = 44; // Messages were sent with async encryption.
// public static final int SECURE_RECEIVED_TYPE = 45; // Messages were received with async decryption.
// public static final int FAILED_DECRYPT_TYPE = 46; // Messages were received with async encryption and failed to decrypt.
// public static final int DECRYPTING_TYPE = 47; // Messages are in the process of being asymmetricaly decrypted.
// public static final int NO_SESSION_TYPE = 48; // Messages were received with async encryption but there is no session yet.
//
// public static final int OUTGOING_KEY_EXCHANGE_TYPE = 49;
// public static final int INCOMING_KEY_EXCHANGE_TYPE = 50;
// public static final int STALE_KEY_EXCHANGE_TYPE = 51;
// public static final int PROCESSED_KEY_EXCHANGE_TYPE = 52;
//
// public static final int[] OUTGOING_MESSAGE_TYPES = {SENT_TYPE, SENT_PENDING, ENCRYPTING_TYPE,
// OUTBOX_TYPE, SECURE_SENT_TYPE,
// FAILED_TYPE, OUTGOING_KEY_EXCHANGE_TYPE};
//
// public static boolean isFailedMessageType(long type) {
// return type == FAILED_TYPE;
// }
//
// public static boolean isOutgoingMessageType(long type) {
// for (int outgoingType : OUTGOING_MESSAGE_TYPES) {
// if (type == outgoingType)
// return true;
// }
//
// return false;
// }
//
// public static boolean isPendingMessageType(long type) {
// return type == SENT_PENDING || type == ENCRYPTING_TYPE || type == OUTBOX_TYPE;
// }
//
// public static boolean isSecureType(long type) {
// return
// type == SECURE_SENT_TYPE || type == ENCRYPTING_TYPE ||
// type == SECURE_RECEIVED_TYPE || type == DECRYPTING_TYPE;
// }
//
// public static boolean isKeyExchangeType(long type) {
// return type == OUTGOING_KEY_EXCHANGE_TYPE || type == INCOMING_KEY_EXCHANGE_TYPE;
// }
}
}
| 11,841 | 38.342193 | 136 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/MmsSmsDatabase.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.database;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.HashSet;
import java.util.Set;
public class MmsSmsDatabase extends Database {
private static final String TAG = MmsSmsDatabase.class.getSimpleName();
public static final String TRANSPORT = "transport_type";
public static final String MMS_TRANSPORT = "mms";
public static final String SMS_TRANSPORT = "sms";
private static final String[] PROJECTION = {MmsSmsColumns.ID, SmsDatabase.BODY, SmsDatabase.TYPE,
MmsSmsColumns.THREAD_ID,
SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT,
MmsSmsColumns.NORMALIZED_DATE_SENT,
MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsDatabase.MESSAGE_TYPE, MmsDatabase.MESSAGE_BOX,
SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY,
MmsDatabase.STATUS, MmsSmsColumns.RECEIPT_COUNT,
MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.ATTACHMENT_ID_ALIAS,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
public MmsSmsDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public Cursor getConversation(long threadId, long limit) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " DESC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId;
Cursor cursor = queryTables(PROJECTION, selection, order, limit > 0 ? String.valueOf(limit) : null);
setNotifyConverationListeners(cursor, threadId);
return cursor;
}
public Cursor getConversation(long threadId) {
return getConversation(threadId, 0);
}
public Cursor getIdentityConflictMessagesForThread(long threadId) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " ASC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId + " AND " + MmsSmsColumns.MISMATCHED_IDENTITIES + " IS NOT NULL";
Cursor cursor = queryTables(PROJECTION, selection, order, null);
setNotifyConverationListeners(cursor, threadId);
return cursor;
}
public Cursor getConversationSnippet(long threadId) {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " DESC";
String selection = MmsSmsColumns.THREAD_ID + " = " + threadId;
return queryTables(PROJECTION, selection, order, "1");
}
public Cursor getUnread() {
String order = MmsSmsColumns.NORMALIZED_DATE_RECEIVED + " ASC";
String selection = MmsSmsColumns.READ + " = 0";
return queryTables(PROJECTION, selection, order, null);
}
public int getConversationCount(long threadId) {
int count = DatabaseFactory.getSmsDatabase(context).getMessageCountForThread(threadId);
count += DatabaseFactory.getMmsDatabase(context).getMessageCountForThread(threadId);
return count;
}
public void incrementDeliveryReceiptCount(String address, long timestamp) {
DatabaseFactory.getSmsDatabase(context).incrementDeliveryReceiptCount(address, timestamp);
DatabaseFactory.getMmsDatabase(context).incrementDeliveryReceiptCount(address, timestamp);
}
private Cursor queryTables(String[] projection, String selection, String order, String limit) {
String[] mmsProjection = {MmsDatabase.DATE_SENT + " AS " + MmsSmsColumns.NORMALIZED_DATE_SENT,
MmsDatabase.DATE_RECEIVED + " AS " + MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " AS " + MmsSmsColumns.ID,
AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " AS " + AttachmentDatabase.ATTACHMENT_ID_ALIAS,
SmsDatabase.BODY, MmsSmsColumns.READ, MmsSmsColumns.THREAD_ID,
SmsDatabase.TYPE, SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT, MmsDatabase.MESSAGE_TYPE,
MmsDatabase.MESSAGE_BOX, SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY, MmsDatabase.STATUS,
MmsSmsColumns.RECEIPT_COUNT, MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
String[] smsProjection = {SmsDatabase.DATE_SENT + " AS " + MmsSmsColumns.NORMALIZED_DATE_SENT,
SmsDatabase.DATE_RECEIVED + " AS " + MmsSmsColumns.NORMALIZED_DATE_RECEIVED,
MmsSmsColumns.ID, "NULL AS " + AttachmentDatabase.ATTACHMENT_ID_ALIAS,
SmsDatabase.BODY, MmsSmsColumns.READ, MmsSmsColumns.THREAD_ID,
SmsDatabase.TYPE, SmsDatabase.ADDRESS, SmsDatabase.ADDRESS_DEVICE_ID, SmsDatabase.SUBJECT, MmsDatabase.MESSAGE_TYPE,
MmsDatabase.MESSAGE_BOX, SmsDatabase.STATUS, MmsDatabase.PART_COUNT,
MmsDatabase.CONTENT_LOCATION, MmsDatabase.TRANSACTION_ID,
MmsDatabase.MESSAGE_SIZE, MmsDatabase.EXPIRY, MmsDatabase.STATUS,
MmsSmsColumns.RECEIPT_COUNT, MmsSmsColumns.MISMATCHED_IDENTITIES,
MmsDatabase.NETWORK_FAILURE, TRANSPORT,
AttachmentDatabase.UNIQUE_ID,
AttachmentDatabase.MMS_ID,
AttachmentDatabase.SIZE,
AttachmentDatabase.DATA,
AttachmentDatabase.CONTENT_TYPE,
AttachmentDatabase.CONTENT_LOCATION,
AttachmentDatabase.CONTENT_DISPOSITION,
AttachmentDatabase.NAME,
AttachmentDatabase.TRANSFER_STATE};
SQLiteQueryBuilder mmsQueryBuilder = new SQLiteQueryBuilder();
SQLiteQueryBuilder smsQueryBuilder = new SQLiteQueryBuilder();
mmsQueryBuilder.setDistinct(true);
smsQueryBuilder.setDistinct(true);
smsQueryBuilder.setTables(SmsDatabase.TABLE_NAME);
mmsQueryBuilder.setTables(MmsDatabase.TABLE_NAME + " LEFT OUTER JOIN " +
AttachmentDatabase.TABLE_NAME +
" ON " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID + " = " +
" (SELECT " + AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.ROW_ID +
" FROM " + AttachmentDatabase.TABLE_NAME + " WHERE " +
AttachmentDatabase.TABLE_NAME + "." + AttachmentDatabase.MMS_ID + " = " +
MmsDatabase.TABLE_NAME + "." + MmsDatabase.ID + " LIMIT 1)");
Set<String> mmsColumnsPresent = new HashSet<>();
mmsColumnsPresent.add(MmsSmsColumns.ID);
mmsColumnsPresent.add(MmsSmsColumns.READ);
mmsColumnsPresent.add(MmsSmsColumns.THREAD_ID);
mmsColumnsPresent.add(MmsSmsColumns.BODY);
mmsColumnsPresent.add(MmsSmsColumns.ADDRESS);
mmsColumnsPresent.add(MmsSmsColumns.ADDRESS_DEVICE_ID);
mmsColumnsPresent.add(MmsSmsColumns.RECEIPT_COUNT);
mmsColumnsPresent.add(MmsSmsColumns.MISMATCHED_IDENTITIES);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_TYPE);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_BOX);
mmsColumnsPresent.add(MmsDatabase.DATE_SENT);
mmsColumnsPresent.add(MmsDatabase.DATE_RECEIVED);
mmsColumnsPresent.add(MmsDatabase.PART_COUNT);
mmsColumnsPresent.add(MmsDatabase.CONTENT_LOCATION);
mmsColumnsPresent.add(MmsDatabase.TRANSACTION_ID);
mmsColumnsPresent.add(MmsDatabase.MESSAGE_SIZE);
mmsColumnsPresent.add(MmsDatabase.EXPIRY);
mmsColumnsPresent.add(MmsDatabase.STATUS);
mmsColumnsPresent.add(MmsDatabase.NETWORK_FAILURE);
mmsColumnsPresent.add(AttachmentDatabase.ROW_ID);
mmsColumnsPresent.add(AttachmentDatabase.UNIQUE_ID);
mmsColumnsPresent.add(AttachmentDatabase.SIZE);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_TYPE);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_LOCATION);
mmsColumnsPresent.add(AttachmentDatabase.CONTENT_DISPOSITION);
mmsColumnsPresent.add(AttachmentDatabase.NAME);
mmsColumnsPresent.add(AttachmentDatabase.TRANSFER_STATE);
Set<String> smsColumnsPresent = new HashSet<>();
smsColumnsPresent.add(MmsSmsColumns.ID);
smsColumnsPresent.add(MmsSmsColumns.BODY);
smsColumnsPresent.add(MmsSmsColumns.ADDRESS);
smsColumnsPresent.add(MmsSmsColumns.ADDRESS_DEVICE_ID);
smsColumnsPresent.add(MmsSmsColumns.READ);
smsColumnsPresent.add(MmsSmsColumns.THREAD_ID);
smsColumnsPresent.add(MmsSmsColumns.RECEIPT_COUNT);
smsColumnsPresent.add(MmsSmsColumns.MISMATCHED_IDENTITIES);
smsColumnsPresent.add(SmsDatabase.TYPE);
smsColumnsPresent.add(SmsDatabase.SUBJECT);
smsColumnsPresent.add(SmsDatabase.DATE_SENT);
smsColumnsPresent.add(SmsDatabase.DATE_RECEIVED);
smsColumnsPresent.add(SmsDatabase.STATUS);
String mmsSubQuery = mmsQueryBuilder.buildUnionSubQuery(TRANSPORT, mmsProjection, mmsColumnsPresent, 3, MMS_TRANSPORT, selection, null, null, null);
String smsSubQuery = smsQueryBuilder.buildUnionSubQuery(TRANSPORT, smsProjection, smsColumnsPresent, 3, SMS_TRANSPORT, selection, null, null, null);
SQLiteQueryBuilder unionQueryBuilder = new SQLiteQueryBuilder();
String unionQuery = unionQueryBuilder.buildUnionQuery(new String[] {smsSubQuery, mmsSubQuery}, order, limit);
SQLiteQueryBuilder outerQueryBuilder = new SQLiteQueryBuilder();
outerQueryBuilder.setTables("(" + unionQuery + ")");
String query = outerQueryBuilder.buildQuery(projection, null, null, null, null, null, null);
Log.w("MmsSmsDatabase", "Executing query: " + query);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.rawQuery(query, null);
}
public Reader readerFor(@NonNull Cursor cursor, @Nullable MasterSecret masterSecret) {
return new Reader(cursor, masterSecret);
}
public Reader readerFor(@NonNull Cursor cursor) {
return new Reader(cursor);
}
public class Reader {
private final Cursor cursor;
private final Optional<MasterSecret> masterSecret;
private EncryptingSmsDatabase.Reader smsReader;
private MmsDatabase.Reader mmsReader;
public Reader(Cursor cursor, @Nullable MasterSecret masterSecret) {
this.cursor = cursor;
this.masterSecret = Optional.fromNullable(masterSecret);
}
public Reader(Cursor cursor) {
this(cursor, null);
}
private EncryptingSmsDatabase.Reader getSmsReader() {
if (smsReader == null) {
if (masterSecret.isPresent()) smsReader = DatabaseFactory.getEncryptingSmsDatabase(context).readerFor(masterSecret.get(), cursor);
else smsReader = DatabaseFactory.getSmsDatabase(context).readerFor(cursor);
}
return smsReader;
}
private MmsDatabase.Reader getMmsReader() {
if (mmsReader == null) {
mmsReader = DatabaseFactory.getMmsDatabase(context).readerFor(masterSecret.orNull(), cursor);
}
return mmsReader;
}
public MessageRecord getNext() {
if (cursor == null || !cursor.moveToNext())
return null;
return getCurrent();
}
public MessageRecord getCurrent() {
String type = cursor.getString(cursor.getColumnIndexOrThrow(TRANSPORT));
if (MmsSmsDatabase.MMS_TRANSPORT.equals(type)) return getMmsReader().getCurrent();
else if (MmsSmsDatabase.SMS_TRANSPORT.equals(type)) return getSmsReader().getCurrent();
else throw new AssertionError("Bad type: " + type);
}
public void close() {
cursor.close();
}
}
}
| 14,925 | 48.423841 | 152 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/NoExternalStorageException.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.database;
public class NoExternalStorageException extends Exception {
public NoExternalStorageException() {
// TODO Auto-generated constructor stub
}
public NoExternalStorageException(String detailMessage) {
super(detailMessage);
// TODO Auto-generated constructor stub
}
public NoExternalStorageException(Throwable throwable) {
super(throwable);
// TODO Auto-generated constructor stub
}
public NoExternalStorageException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
// TODO Auto-generated constructor stub
}
}
| 1,328 | 31.414634 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/NoSuchMessageException.java | package org.thoughtcrime.securesms.database;
public class NoSuchMessageException extends Exception {
public NoSuchMessageException(String s) {super(s);}
public NoSuchMessageException(Exception e) {super(e);}
}
| 215 | 29.857143 | 56 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/NotInDirectoryException.java | package org.thoughtcrime.securesms.database;
public class NotInDirectoryException extends Throwable {
}
| 105 | 20.2 | 56 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/PduHeadersBuilder.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.database;
import android.database.Cursor;
import android.util.Log;
import ws.com.google.android.mms.InvalidHeaderValueException;
import ws.com.google.android.mms.pdu.CharacterSets;
import ws.com.google.android.mms.pdu.EncodedStringValue;
import ws.com.google.android.mms.pdu.PduHeaders;
import java.io.UnsupportedEncodingException;
public class PduHeadersBuilder {
private final PduHeaders headers;
private final Cursor cursor;
public PduHeadersBuilder(PduHeaders headers, Cursor cursor) {
this.headers = headers;
this.cursor = cursor;
}
public PduHeaders getHeaders() {
return headers;
}
public void addLong(String key, int headersKey) {
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (!cursor.isNull(columnIndex))
headers.setLongInteger(cursor.getLong(columnIndex), headersKey);
}
public void addOctet(String key, int headersKey) throws InvalidHeaderValueException {
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (!cursor.isNull(columnIndex))
headers.setOctet(cursor.getInt(columnIndex), headersKey);
}
public void addText(String key, int headersKey) {
String value = cursor.getString(cursor.getColumnIndexOrThrow(key));
if (value != null && value.trim().length() > 0)
headers.setTextString(getBytes(value), headersKey);
}
public void add(String key, String charsetKey, int headersKey) {
String value = cursor.getString(cursor.getColumnIndexOrThrow(key));
if (value != null && value.trim().length() > 0) {
int charsetValue = cursor.getInt(cursor.getColumnIndexOrThrow(charsetKey));
EncodedStringValue encodedValue = new EncodedStringValue(charsetValue, getBytes(value));
headers.setEncodedStringValue(encodedValue, headersKey);
}
}
private byte[] getBytes(String data) {
try {
return data.getBytes(CharacterSets.MIMENAME_ISO_8859_1);
} catch (UnsupportedEncodingException e) {
Log.e("PduHeadersBuilder", "ISO_8859_1 must be supported!", e);
return new byte[0];
}
}
}
| 2,779 | 33.320988 | 94 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/PlaintextBackupExporter.java | package org.thoughtcrime.securesms.database;
import android.content.Context;
import android.os.Environment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import java.io.File;
import java.io.IOException;
public class PlaintextBackupExporter {
public static void exportPlaintextToSd(Context context, MasterSecret masterSecret)
throws NoExternalStorageException, IOException
{
verifyExternalStorageForPlaintextExport();
exportPlaintext(context, masterSecret);
}
private static void verifyExternalStorageForPlaintextExport() throws NoExternalStorageException {
if (!Environment.getExternalStorageDirectory().canWrite())
throw new NoExternalStorageException();
}
private static String getPlaintextExportDirectoryPath() {
File sdDirectory = Environment.getExternalStorageDirectory();
return sdDirectory.getAbsolutePath() + File.separator + "TextSecurePlaintextBackup.xml";
}
private static void exportPlaintext(Context context, MasterSecret masterSecret)
throws IOException
{
int count = DatabaseFactory.getSmsDatabase(context).getMessageCount();
XmlBackup.Writer writer = new XmlBackup.Writer(getPlaintextExportDirectoryPath(), count);
SmsMessageRecord record;
EncryptingSmsDatabase.Reader reader = null;
int skip = 0;
int ROW_LIMIT = 500;
do {
if (reader != null)
reader.close();
reader = DatabaseFactory.getEncryptingSmsDatabase(context).getMessages(masterSecret, skip, ROW_LIMIT);
while ((record = reader.getNext()) != null) {
XmlBackup.XmlBackupItem item =
new XmlBackup.XmlBackupItem(0, record.getIndividualRecipient().getNumber(),
record.getDateReceived(),
MmsSmsColumns.Types.translateToSystemBaseType(record.getType()),
null, record.getDisplayBody().toString(), null,
1, record.getDeliveryStatus());
writer.writeItem(item);
}
skip += ROW_LIMIT;
} while (reader.getCount() > 0);
writer.close();
}
}
| 2,277 | 33 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/PlaintextBackupImporter.java | package org.thoughtcrime.securesms.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Environment;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class PlaintextBackupImporter {
public static void importPlaintextFromSd(Context context, MasterSecret masterSecret)
throws NoExternalStorageException, IOException
{
Log.w("PlaintextBackupImporter", "Importing plaintext...");
verifyExternalStorageForPlaintextImport();
importPlaintext(context, masterSecret);
}
private static void verifyExternalStorageForPlaintextImport() throws NoExternalStorageException {
if (!Environment.getExternalStorageDirectory().canRead() ||
!(new File(getPlaintextExportDirectoryPath()).exists()))
throw new NoExternalStorageException();
}
private static String getPlaintextExportDirectoryPath() {
File sdDirectory = Environment.getExternalStorageDirectory();
return sdDirectory.getAbsolutePath() + File.separator + "TextSecurePlaintextBackup.xml";
}
private static void importPlaintext(Context context, MasterSecret masterSecret)
throws IOException
{
Log.w("PlaintextBackupImporter", "importPlaintext()");
SmsDatabase db = DatabaseFactory.getSmsDatabase(context);
SQLiteDatabase transaction = db.beginTransaction();
try {
ThreadDatabase threads = DatabaseFactory.getThreadDatabase(context);
XmlBackup backup = new XmlBackup(getPlaintextExportDirectoryPath());
MasterCipher masterCipher = new MasterCipher(masterSecret);
Set<Long> modifiedThreads = new HashSet<Long>();
XmlBackup.XmlBackupItem item;
while ((item = backup.getNext()) != null) {
Recipients recipients = RecipientFactory.getRecipientsFromString(context, item.getAddress(), false);
long threadId = threads.getThreadIdFor(recipients);
SQLiteStatement statement = db.createInsertStatement(transaction);
if (item.getAddress() == null || item.getAddress().equals("null"))
continue;
if (!isAppropriateTypeForImport(item.getType()))
continue;
addStringToStatement(statement, 1, item.getAddress());
addNullToStatement(statement, 2);
addLongToStatement(statement, 3, item.getDate());
addLongToStatement(statement, 4, item.getDate());
addLongToStatement(statement, 5, item.getProtocol());
addLongToStatement(statement, 6, item.getRead());
addLongToStatement(statement, 7, item.getStatus());
addTranslatedTypeToStatement(statement, 8, item.getType());
addNullToStatement(statement, 9);
addStringToStatement(statement, 10, item.getSubject());
addEncryptedStingToStatement(masterCipher, statement, 11, item.getBody());
addStringToStatement(statement, 12, item.getServiceCenter());
addLongToStatement(statement, 13, threadId);
modifiedThreads.add(threadId);
statement.execute();
}
for (long threadId : modifiedThreads) {
threads.update(threadId);
}
Log.w("PlaintextBackupImporter", "Exited loop");
} catch (XmlPullParserException e) {
Log.w("PlaintextBackupImporter", e);
throw new IOException("XML Parsing error!");
} finally {
db.endTransaction(transaction);
}
}
private static void addEncryptedStingToStatement(MasterCipher masterCipher, SQLiteStatement statement, int index, String value) {
if (value == null || value.equals("null")) {
statement.bindNull(index);
} else {
statement.bindString(index, masterCipher.encryptBody(value));
}
}
private static void addTranslatedTypeToStatement(SQLiteStatement statement, int index, int type) {
statement.bindLong(index, SmsDatabase.Types.translateFromSystemBaseType(type) | SmsDatabase.Types.ENCRYPTION_SYMMETRIC_BIT);
}
private static void addStringToStatement(SQLiteStatement statement, int index, String value) {
if (value == null || value.equals("null")) statement.bindNull(index);
else statement.bindString(index, value);
}
private static void addNullToStatement(SQLiteStatement statement, int index) {
statement.bindNull(index);
}
private static void addLongToStatement(SQLiteStatement statement, int index, long value) {
statement.bindLong(index, value);
}
private static boolean isAppropriateTypeForImport(long theirType) {
long ourType = SmsDatabase.Types.translateFromSystemBaseType(theirType);
return ourType == MmsSmsColumns.Types.BASE_INBOX_TYPE ||
ourType == MmsSmsColumns.Types.BASE_SENT_TYPE ||
ourType == MmsSmsColumns.Types.BASE_SENT_FAILED_TYPE;
}
}
| 5,265 | 38.593985 | 131 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/PushDatabase.java | package org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.util.Log;
import org.thoughtcrime.securesms.util.Base64;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.whispersystems.textsecure.internal.util.Util;
import java.io.IOException;
public class PushDatabase extends Database {
private static final String TAG = PushDatabase.class.getSimpleName();
private static final String TABLE_NAME = "push";
public static final String ID = "_id";
public static final String TYPE = "type";
public static final String SOURCE = "source";
public static final String DEVICE_ID = "device_id";
public static final String LEGACY_MSG = "body";
public static final String CONTENT = "content";
public static final String TIMESTAMP = "timestamp";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
TYPE + " INTEGER, " + SOURCE + " TEXT, " + DEVICE_ID + " INTEGER, " + LEGACY_MSG + " TEXT, " + CONTENT + " TEXT, " + TIMESTAMP + " INTEGER);";
public PushDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public long insert(@NonNull TextSecureEnvelope envelope) {
Optional<Long> messageId = find(envelope);
if (messageId.isPresent()) {
return messageId.get();
} else {
ContentValues values = new ContentValues();
values.put(TYPE, envelope.getType());
values.put(SOURCE, envelope.getSource());
values.put(DEVICE_ID, envelope.getSourceDevice());
values.put(LEGACY_MSG, envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "");
values.put(CONTENT, envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "");
values.put(TIMESTAMP, envelope.getTimestamp());
return databaseHelper.getWritableDatabase().insert(TABLE_NAME, null, values);
}
}
public TextSecureEnvelope get(long id) throws NoSuchMessageException {
Cursor cursor = null;
try {
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, null, ID_WHERE,
new String[] {String.valueOf(id)},
null, null, null);
if (cursor != null && cursor.moveToNext()) {
String legacyMessage = cursor.getString(cursor.getColumnIndexOrThrow(LEGACY_MSG));
String content = cursor.getString(cursor.getColumnIndexOrThrow(CONTENT));
return new TextSecureEnvelope(cursor.getInt(cursor.getColumnIndexOrThrow(TYPE)),
cursor.getString(cursor.getColumnIndexOrThrow(SOURCE)),
cursor.getInt(cursor.getColumnIndexOrThrow(DEVICE_ID)),
"",
cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP)),
Util.isEmpty(legacyMessage) ? null : Base64.decode(legacyMessage),
Util.isEmpty(content) ? null : Base64.decode(content));
}
} catch (IOException e) {
Log.w(TAG, e);
throw new NoSuchMessageException(e);
} finally {
if (cursor != null)
cursor.close();
}
throw new NoSuchMessageException("Not found");
}
public Cursor getPending() {
return databaseHelper.getReadableDatabase().query(TABLE_NAME, null, null, null, null, null, null);
}
public void delete(long id) {
databaseHelper.getWritableDatabase().delete(TABLE_NAME, ID_WHERE, new String[] {id+""});
}
public Reader readerFor(Cursor cursor) {
return new Reader(cursor);
}
private Optional<Long> find(TextSecureEnvelope envelope) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, null, TYPE + " = ? AND " + SOURCE + " = ? AND " +
DEVICE_ID + " = ? AND " + LEGACY_MSG + " = ? AND " +
CONTENT + " = ? AND " + TIMESTAMP + " = ?" ,
new String[] {String.valueOf(envelope.getType()),
envelope.getSource(),
String.valueOf(envelope.getSourceDevice()),
envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "",
envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "",
String.valueOf(envelope.getTimestamp())},
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return Optional.of(cursor.getLong(cursor.getColumnIndexOrThrow(ID)));
} else {
return Optional.absent();
}
} finally {
if (cursor != null) cursor.close();
}
}
public static class Reader {
private final Cursor cursor;
public Reader(Cursor cursor) {
this.cursor = cursor;
}
public TextSecureEnvelope getNext() {
try {
if (cursor == null || !cursor.moveToNext())
return null;
int type = cursor.getInt(cursor.getColumnIndexOrThrow(TYPE));
String source = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE));
int deviceId = cursor.getInt(cursor.getColumnIndexOrThrow(DEVICE_ID));
String legacyMessage = cursor.getString(cursor.getColumnIndexOrThrow(LEGACY_MSG));
String content = cursor.getString(cursor.getColumnIndexOrThrow(CONTENT));
long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP));
return new TextSecureEnvelope(type, source, deviceId, "", timestamp,
legacyMessage != null ? Base64.decode(legacyMessage) : null,
content != null ? Base64.decode(content) : null);
} catch (IOException e) {
throw new AssertionError(e);
}
}
public void close() {
this.cursor.close();
}
}
}
| 6,583 | 40.936306 | 148 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/RecipientPreferenceDatabase.java | package org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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.recipients.Recipients;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.Arrays;
public class RecipientPreferenceDatabase extends Database {
private static final String TAG = RecipientPreferenceDatabase.class.getSimpleName();
private static final String RECIPIENT_PREFERENCES_URI = "content://textsecure/recipients/";
private static final String TABLE_NAME = "recipient_preferences";
private static final String ID = "_id";
private static final String RECIPIENT_IDS = "recipient_ids";
private static final String BLOCK = "block";
private static final String NOTIFICATION = "notification";
private static final String VIBRATE = "vibrate";
private static final String MUTE_UNTIL = "mute_until";
private static final String COLOR = "color";
private static final String SEEN_INVITE_REMINDER = "seen_invite_reminder";
public enum VibrateState {
DEFAULT(0), ENABLED(1), DISABLED(2);
private final int id;
VibrateState(int id) {
this.id = id;
}
public int getId() {
return id;
}
public static VibrateState fromId(int id) {
return values()[id];
}
}
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME +
" (" + ID + " INTEGER PRIMARY KEY, " +
RECIPIENT_IDS + " TEXT UNIQUE, " +
BLOCK + " INTEGER DEFAULT 0," +
NOTIFICATION + " TEXT DEFAULT NULL, " +
VIBRATE + " INTEGER DEFAULT " + VibrateState.DEFAULT.getId() + ", " +
MUTE_UNTIL + " INTEGER DEFAULT 0, " +
COLOR + " TEXT DEFAULT NULL, " +
SEEN_INVITE_REMINDER + " INTEGER DEFAULT 0);";
public RecipientPreferenceDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
public Cursor getBlocked() {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = database.query(TABLE_NAME, new String[] {ID, RECIPIENT_IDS}, BLOCK + " = 1",
null, null, null, null, null);
cursor.setNotificationUri(context.getContentResolver(), Uri.parse(RECIPIENT_PREFERENCES_URI));
return cursor;
}
public Optional<RecipientsPreferences> getRecipientsPreferences(@NonNull long[] recipients) {
Arrays.sort(recipients);
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, null, RECIPIENT_IDS + " = ?",
new String[] {Util.join(recipients, " ")},
null, null, null);
if (cursor != null && cursor.moveToNext()) {
boolean blocked = cursor.getInt(cursor.getColumnIndexOrThrow(BLOCK)) == 1;
String notification = cursor.getString(cursor.getColumnIndexOrThrow(NOTIFICATION));
int vibrateState = cursor.getInt(cursor.getColumnIndexOrThrow(VIBRATE));
long muteUntil = cursor.getLong(cursor.getColumnIndexOrThrow(MUTE_UNTIL));
String serializedColor = cursor.getString(cursor.getColumnIndexOrThrow(COLOR));
Uri notificationUri = notification == null ? null : Uri.parse(notification);
boolean seenInviteReminder = cursor.getInt(cursor.getColumnIndexOrThrow(SEEN_INVITE_REMINDER)) == 1;
MaterialColor color;
try {
color = serializedColor == null ? null : MaterialColor.fromSerialized(serializedColor);
} catch (MaterialColor.UnknownColorException e) {
Log.w(TAG, e);
color = null;
}
Log.w(TAG, "Muted until: " + muteUntil);
return Optional.of(new RecipientsPreferences(blocked, muteUntil,
VibrateState.fromId(vibrateState),
notificationUri, color, seenInviteReminder));
}
return Optional.absent();
} finally {
if (cursor != null) cursor.close();
}
}
public void setColor(Recipients recipients, MaterialColor color) {
ContentValues values = new ContentValues();
values.put(COLOR, color.serialize());
updateOrInsert(recipients, values);
}
public void setBlocked(Recipients recipients, boolean blocked) {
ContentValues values = new ContentValues();
values.put(BLOCK, blocked ? 1 : 0);
updateOrInsert(recipients, values);
}
public void setRingtone(Recipients recipients, @Nullable Uri notification) {
ContentValues values = new ContentValues();
values.put(NOTIFICATION, notification == null ? null : notification.toString());
updateOrInsert(recipients, values);
}
public void setVibrate(Recipients recipients, @NonNull VibrateState enabled) {
ContentValues values = new ContentValues();
values.put(VIBRATE, enabled.getId());
updateOrInsert(recipients, values);
}
public void setMuted(Recipients recipients, long until) {
Log.w(TAG, "Setting muted until: " + until);
ContentValues values = new ContentValues();
values.put(MUTE_UNTIL, until);
updateOrInsert(recipients, values);
}
public void setSeenInviteReminder(Recipients recipients, boolean seen) {
ContentValues values = new ContentValues(1);
values.put(SEEN_INVITE_REMINDER, seen ? 1 : 0);
updateOrInsert(recipients, values);
}
private void updateOrInsert(Recipients recipients, ContentValues contentValues) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
int updated = database.update(TABLE_NAME, contentValues, RECIPIENT_IDS + " = ?",
new String[] {String.valueOf(recipients.getSortedIdsString())});
if (updated < 1) {
contentValues.put(RECIPIENT_IDS, recipients.getSortedIdsString());
database.insert(TABLE_NAME, null, contentValues);
}
database.setTransactionSuccessful();
database.endTransaction();
context.getContentResolver().notifyChange(Uri.parse(RECIPIENT_PREFERENCES_URI), null);
}
public static class RecipientsPreferences {
private final boolean blocked;
private final long muteUntil;
private final VibrateState vibrateState;
private final Uri notification;
private final MaterialColor color;
private final boolean seenInviteReminder;
public RecipientsPreferences(boolean blocked, long muteUntil,
@NonNull VibrateState vibrateState,
@Nullable Uri notification,
@Nullable MaterialColor color,
boolean seenInviteReminder)
{
this.blocked = blocked;
this.muteUntil = muteUntil;
this.vibrateState = vibrateState;
this.notification = notification;
this.color = color;
this.seenInviteReminder = seenInviteReminder;
}
public @Nullable MaterialColor getColor() {
return color;
}
public boolean isBlocked() {
return blocked;
}
public long getMuteUntil() {
return muteUntil;
}
public @NonNull VibrateState getVibrateState() {
return vibrateState;
}
public @Nullable Uri getRingtone() {
return notification;
}
public boolean hasSeenInviteReminder() {
return seenInviteReminder;
}
}
}
| 8,020 | 34.808036 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/SmsDatabase.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.NonNull;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatchList;
import org.thoughtcrime.securesms.database.model.DisplayRecord;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import org.thoughtcrime.securesms.jobs.TrimThreadJob;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.sms.IncomingGroupMessage;
import org.thoughtcrime.securesms.sms.IncomingTextMessage;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage;
import org.thoughtcrime.securesms.util.JsonUtils;
import org.whispersystems.jobqueue.JobManager;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import static org.thoughtcrime.securesms.util.Util.canonicalizeNumber;
/**
* Database for storage of SMS messages.
*
* @author Moxie Marlinspike
*/
public class SmsDatabase extends MessagingDatabase {
private static final String TAG = SmsDatabase.class.getSimpleName();
public static final String TABLE_NAME = "sms";
public static final String PERSON = "person";
static final String DATE_RECEIVED = "date";
static final String DATE_SENT = "date_sent";
public static final String PROTOCOL = "protocol";
public static final String STATUS = "status";
public static final String TYPE = "type";
public static final String REPLY_PATH_PRESENT = "reply_path_present";
public static final String SUBJECT = "subject";
public static final String SERVICE_CENTER = "service_center";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " integer PRIMARY KEY, " +
THREAD_ID + " INTEGER, " + ADDRESS + " TEXT, " + ADDRESS_DEVICE_ID + " INTEGER DEFAULT 1, " + PERSON + " INTEGER, " +
DATE_RECEIVED + " INTEGER, " + DATE_SENT + " INTEGER, " + PROTOCOL + " INTEGER, " + READ + " INTEGER DEFAULT 0, " +
STATUS + " INTEGER DEFAULT -1," + TYPE + " INTEGER, " + REPLY_PATH_PRESENT + " INTEGER, " +
RECEIPT_COUNT + " INTEGER DEFAULT 0," + SUBJECT + " TEXT, " + BODY + " TEXT, " +
MISMATCHED_IDENTITIES + " TEXT DEFAULT NULL, " + SERVICE_CENTER + " TEXT);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS sms_thread_id_index ON " + TABLE_NAME + " (" + THREAD_ID + ");",
"CREATE INDEX IF NOT EXISTS sms_read_index ON " + TABLE_NAME + " (" + READ + ");",
"CREATE INDEX IF NOT EXISTS sms_read_and_thread_id_index ON " + TABLE_NAME + "(" + READ + "," + THREAD_ID + ");",
"CREATE INDEX IF NOT EXISTS sms_type_index ON " + TABLE_NAME + " (" + TYPE + ");",
"CREATE INDEX IF NOT EXISTS sms_date_sent_index ON " + TABLE_NAME + " (" + DATE_SENT + ");",
"CREATE INDEX IF NOT EXISTS sms_thread_date_index ON " + TABLE_NAME + " (" + THREAD_ID + ", " + DATE_RECEIVED + ");"
};
private static final String[] MESSAGE_PROJECTION = new String[] {
ID, THREAD_ID, ADDRESS, ADDRESS_DEVICE_ID, PERSON,
DATE_RECEIVED + " AS " + NORMALIZED_DATE_RECEIVED,
DATE_SENT + " AS " + NORMALIZED_DATE_SENT,
PROTOCOL, READ, STATUS, TYPE,
REPLY_PATH_PRESENT, SUBJECT, BODY, SERVICE_CENTER, RECEIPT_COUNT,
MISMATCHED_IDENTITIES
};
private final JobManager jobManager;
public SmsDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
this.jobManager = ApplicationContext.getInstance(context).getJobManager();
}
protected String getTableName() {
return TABLE_NAME;
}
private void updateTypeBitmask(long id, long maskOff, long maskOn) {
Log.w("MessageDatabase", "Updating ID: " + id + " to base type: " + maskOn);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME +
" SET " + TYPE + " = (" + TYPE + " & " + (Types.TOTAL_MASK - maskOff) + " | " + maskOn + " )" +
" WHERE " + ID + " = ?", new String[] {id+""});
long threadId = getThreadIdForMessage(id);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
notifyConversationListListeners();
}
public long getThreadIdForMessage(long id) {
String sql = "SELECT " + THREAD_ID + " FROM " + TABLE_NAME + " WHERE " + ID + " = ?";
String[] sqlArgs = new String[] {id+""};
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, sqlArgs);
if (cursor != null && cursor.moveToFirst())
return cursor.getLong(0);
else
return -1;
} finally {
if (cursor != null)
cursor.close();
}
}
public int getMessageCount() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, new String[] {"COUNT(*)"}, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) return cursor.getInt(0);
else return 0;
} finally {
if (cursor != null)
cursor.close();
}
}
public int getMessageCountForThread(long threadId) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, new String[] {"COUNT(*)"}, THREAD_ID + " = ?",
new String[] {threadId+""}, null, null, null);
if (cursor != null && cursor.moveToFirst())
return cursor.getInt(0);
} finally {
if (cursor != null)
cursor.close();
}
return 0;
}
public void markAsEndSession(long id) {
updateTypeBitmask(id, Types.KEY_EXCHANGE_MASK, Types.END_SESSION_BIT);
}
public void markAsPreKeyBundle(long id) {
updateTypeBitmask(id, Types.KEY_EXCHANGE_MASK, Types.KEY_EXCHANGE_BIT | Types.KEY_EXCHANGE_BUNDLE_BIT);
}
public void markAsInvalidVersionKeyExchange(long id) {
updateTypeBitmask(id, 0, Types.KEY_EXCHANGE_INVALID_VERSION_BIT);
}
public void markAsSecure(long id) {
updateTypeBitmask(id, 0, Types.SECURE_MESSAGE_BIT);
}
public void markAsInsecure(long id) {
updateTypeBitmask(id, Types.SECURE_MESSAGE_BIT, 0);
}
public void markAsPush(long id) {
updateTypeBitmask(id, 0, Types.PUSH_MESSAGE_BIT);
}
public void markAsForcedSms(long id) {
updateTypeBitmask(id, Types.PUSH_MESSAGE_BIT, Types.MESSAGE_FORCE_SMS_BIT);
}
public void markAsDecryptFailed(long id) {
updateTypeBitmask(id, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_FAILED_BIT);
}
public void markAsDecryptDuplicate(long id) {
updateTypeBitmask(id, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_DUPLICATE_BIT);
}
public void markAsNoSession(long id) {
updateTypeBitmask(id, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_NO_SESSION_BIT);
}
public void markAsLegacyVersion(long id) {
updateTypeBitmask(id, Types.ENCRYPTION_MASK, Types.ENCRYPTION_REMOTE_LEGACY_BIT);
}
public void markAsOutbox(long id) {
updateTypeBitmask(id, Types.BASE_TYPE_MASK, Types.BASE_OUTBOX_TYPE);
}
public void markAsPendingInsecureSmsFallback(long id) {
updateTypeBitmask(id, Types.BASE_TYPE_MASK, Types.BASE_PENDING_INSECURE_SMS_FALLBACK);
}
public void markAsSending(long id) {
updateTypeBitmask(id, Types.BASE_TYPE_MASK, Types.BASE_SENDING_TYPE);
}
public void markAsSent(long id) {
updateTypeBitmask(id, Types.BASE_TYPE_MASK, Types.BASE_SENT_TYPE);
}
public void markStatus(long id, int status) {
Log.w("MessageDatabase", "Updating ID: " + id + " to status: " + status);
ContentValues contentValues = new ContentValues();
contentValues.put(STATUS, status);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {id+""});
notifyConversationListeners(getThreadIdForMessage(id));
}
public void markAsSentFailed(long id) {
updateTypeBitmask(id, Types.BASE_TYPE_MASK, Types.BASE_SENT_FAILED_TYPE);
}
public void incrementDeliveryReceiptCount(String address, long timestamp) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, new String[] {ID, THREAD_ID, ADDRESS, TYPE},
DATE_SENT + " = ?", new String[] {String.valueOf(timestamp)},
null, null, null, null);
while (cursor.moveToNext()) {
if (Types.isOutgoingMessageType(cursor.getLong(cursor.getColumnIndexOrThrow(TYPE)))) {
try {
String theirAddress = canonicalizeNumber(context, address);
String ourAddress = canonicalizeNumber(context, cursor.getString(cursor.getColumnIndexOrThrow(ADDRESS)));
if (ourAddress.equals(theirAddress)) {
database.execSQL("UPDATE " + TABLE_NAME +
" SET " + RECEIPT_COUNT + " = " + RECEIPT_COUNT + " + 1 WHERE " +
ID + " = ?",
new String[] {String.valueOf(cursor.getLong(cursor.getColumnIndexOrThrow(ID)))});
notifyConversationListeners(cursor.getLong(cursor.getColumnIndexOrThrow(THREAD_ID)));
}
} catch (InvalidNumberException e) {
Log.w("SmsDatabase", e);
}
}
}
} finally {
if (cursor != null)
cursor.close();
}
}
public void setMessagesRead(long threadId) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(READ, 1);
database.update(TABLE_NAME, contentValues,
THREAD_ID + " = ? AND " + READ + " = 0",
new String[] {threadId+""});
}
public void setAllMessagesRead() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(READ, 1);
database.update(TABLE_NAME, contentValues, null, null);
}
protected Pair<Long, Long> updateMessageBodyAndType(long messageId, String body, long maskOff, long maskOn) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.execSQL("UPDATE " + TABLE_NAME + " SET " + BODY + " = ?, " +
TYPE + " = (" + TYPE + " & " + (Types.TOTAL_MASK - maskOff) + " | " + maskOn + ") " +
"WHERE " + ID + " = ?",
new String[] {body, messageId + ""});
long threadId = getThreadIdForMessage(messageId);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
notifyConversationListListeners();
return new Pair<>(messageId, threadId);
}
public Pair<Long, Long> copyMessageInbox(long messageId) {
Reader reader = readerFor(getMessage(messageId));
SmsMessageRecord record = reader.getNext();
ContentValues contentValues = new ContentValues();
contentValues.put(TYPE, (record.getType() & ~Types.BASE_TYPE_MASK) | Types.BASE_INBOX_TYPE);
contentValues.put(ADDRESS, record.getIndividualRecipient().getNumber());
contentValues.put(ADDRESS_DEVICE_ID, record.getRecipientDeviceId());
contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
contentValues.put(DATE_SENT, record.getDateSent());
contentValues.put(PROTOCOL, 31337);
contentValues.put(READ, 0);
contentValues.put(BODY, record.getBody().getBody());
contentValues.put(THREAD_ID, record.getThreadId());
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long newMessageId = db.insert(TABLE_NAME, null, contentValues);
DatabaseFactory.getThreadDatabase(context).update(record.getThreadId());
notifyConversationListeners(record.getThreadId());
jobManager.add(new TrimThreadJob(context, record.getThreadId()));
reader.close();
return new Pair<>(newMessageId, record.getThreadId());
}
public @NonNull Pair<Long, Long> insertReceivedCall(@NonNull String number) {
return insertCallLog(number, Types.INCOMING_CALL_TYPE, false);
}
public @NonNull Pair<Long, Long> insertOutgoingCall(@NonNull String number) {
return insertCallLog(number, Types.OUTGOING_CALL_TYPE, false);
}
public @NonNull Pair<Long, Long> insertMissedCall(@NonNull String number) {
return insertCallLog(number, Types.MISSED_CALL_TYPE, true);
}
private @NonNull Pair<Long, Long> insertCallLog(@NonNull String number, long type, boolean unread) {
Recipients recipients = RecipientFactory.getRecipientsFromString(context, number, true);
long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
ContentValues values = new ContentValues(6);
values.put(ADDRESS, number);
values.put(ADDRESS_DEVICE_ID, 1);
values.put(DATE_RECEIVED, System.currentTimeMillis());
values.put(DATE_SENT, System.currentTimeMillis());
values.put(READ, unread ? 0 : 1);
values.put(TYPE, type);
values.put(THREAD_ID, threadId);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long messageId = db.insert(TABLE_NAME, null, values);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
jobManager.add(new TrimThreadJob(context, threadId));
if (unread) {
DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
}
return new Pair<>(messageId, threadId);
}
protected Pair<Long, Long> insertMessageInbox(IncomingTextMessage message, long type) {
if (message.isJoined()) {
type = (type & (Types.TOTAL_MASK - Types.BASE_TYPE_MASK)) | Types.JOINED_TYPE;
} else if (message.isPreKeyBundle()) {
type |= Types.KEY_EXCHANGE_BIT | Types.KEY_EXCHANGE_BUNDLE_BIT;
} else if (message.isSecureMessage()) {
type |= Types.SECURE_MESSAGE_BIT;
} else if (message.isGroup()) {
type |= Types.SECURE_MESSAGE_BIT;
if (((IncomingGroupMessage)message).isUpdate()) type |= Types.GROUP_UPDATE_BIT;
else if (((IncomingGroupMessage)message).isQuit()) type |= Types.GROUP_QUIT_BIT;
} else if (message.isEndSession()) {
type |= Types.SECURE_MESSAGE_BIT;
type |= Types.END_SESSION_BIT;
}
if (message.isPush()) type |= Types.PUSH_MESSAGE_BIT;
Recipients recipients;
if (message.getSender() != null) {
recipients = RecipientFactory.getRecipientsFromString(context, message.getSender(), true);
} else {
Log.w(TAG, "Sender is null, returning unknown recipient");
recipients = RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), false);
}
Recipients groupRecipients;
if (message.getGroupId() == null) {
groupRecipients = null;
} else {
groupRecipients = RecipientFactory.getRecipientsFromString(context, message.getGroupId(), true);
}
boolean unread = org.thoughtcrime.securesms.util.Util.isDefaultSmsProvider(context) ||
message.isSecureMessage() || message.isPreKeyBundle();
long threadId;
if (groupRecipients == null) threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
else threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(groupRecipients);
ContentValues values = new ContentValues(6);
values.put(ADDRESS, message.getSender());
values.put(ADDRESS_DEVICE_ID, message.getSenderDeviceId());
values.put(DATE_RECEIVED, System.currentTimeMillis());
values.put(DATE_SENT, message.getSentTimestampMillis());
values.put(PROTOCOL, message.getProtocol());
values.put(READ, unread ? 0 : 1);
if (!TextUtils.isEmpty(message.getPseudoSubject()))
values.put(SUBJECT, message.getPseudoSubject());
values.put(REPLY_PATH_PRESENT, message.isReplyPathPresent());
values.put(SERVICE_CENTER, message.getServiceCenterAddress());
values.put(BODY, message.getMessageBody());
values.put(TYPE, type);
values.put(THREAD_ID, threadId);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long messageId = db.insert(TABLE_NAME, null, values);
if (unread) {
DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
}
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
jobManager.add(new TrimThreadJob(context, threadId));
return new Pair<>(messageId, threadId);
}
public Pair<Long, Long> insertMessageInbox(IncomingTextMessage message) {
return insertMessageInbox(message, Types.BASE_INBOX_TYPE);
}
protected long insertMessageOutbox(long threadId, OutgoingTextMessage message,
long type, boolean forceSms, long date)
{
if (message.isKeyExchange()) type |= Types.KEY_EXCHANGE_BIT;
else if (message.isSecureMessage()) type |= Types.SECURE_MESSAGE_BIT;
else if (message.isEndSession()) type |= Types.END_SESSION_BIT;
if (forceSms) type |= Types.MESSAGE_FORCE_SMS_BIT;
ContentValues contentValues = new ContentValues(6);
contentValues.put(ADDRESS, PhoneNumberUtils.formatNumber(message.getRecipients().getPrimaryRecipient().getNumber()));
contentValues.put(THREAD_ID, threadId);
contentValues.put(BODY, message.getMessageBody());
contentValues.put(DATE_RECEIVED, System.currentTimeMillis());
contentValues.put(DATE_SENT, date);
contentValues.put(READ, 1);
contentValues.put(TYPE, type);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long messageId = db.insert(TABLE_NAME, ADDRESS, contentValues);
DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
jobManager.add(new TrimThreadJob(context, threadId));
return messageId;
}
Cursor getMessages(int skip, int limit) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.query(TABLE_NAME, MESSAGE_PROJECTION, null, null, null, null, ID, skip + "," + limit);
}
Cursor getOutgoingMessages() {
String outgoingSelection = TYPE + " & " + Types.BASE_TYPE_MASK + " = " + Types.BASE_OUTBOX_TYPE;
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.query(TABLE_NAME, MESSAGE_PROJECTION, outgoingSelection, null, null, null, null);
}
public Cursor getDecryptInProgressMessages() {
String where = TYPE + " & " + (Types.ENCRYPTION_ASYMMETRIC_BIT) + " != 0";
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.query(TABLE_NAME, MESSAGE_PROJECTION, where, null, null, null, null);
}
public Cursor getEncryptedRogueMessages(Recipient recipient) {
String selection = TYPE + " & " + Types.ENCRYPTION_REMOTE_NO_SESSION_BIT + " != 0" +
" AND PHONE_NUMBERS_EQUAL(" + ADDRESS + ", ?)";
String[] args = {recipient.getNumber()};
SQLiteDatabase db = databaseHelper.getReadableDatabase();
return db.query(TABLE_NAME, MESSAGE_PROJECTION, selection, args, null, null, null);
}
public Cursor getMessage(long messageId) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, MESSAGE_PROJECTION, ID_WHERE, new String[]{messageId + ""},
null, null, null);
setNotifyConverationListeners(cursor, getThreadIdForMessage(messageId));
return cursor;
}
public boolean deleteMessage(long messageId) {
Log.w("MessageDatabase", "Deleting: " + messageId);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
long threadId = getThreadIdForMessage(messageId);
db.delete(TABLE_NAME, ID_WHERE, new String[] {messageId+""});
boolean threadDeleted = DatabaseFactory.getThreadDatabase(context).update(threadId);
notifyConversationListeners(threadId);
return threadDeleted;
}
/*package */void deleteThread(long threadId) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, THREAD_ID + " = ?", new String[] {threadId+""});
}
/*package*/void deleteMessagesInThreadBeforeDate(long threadId, long date) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String where = THREAD_ID + " = ? AND (CASE " + TYPE;
for (long outgoingType : Types.OUTGOING_MESSAGE_TYPES) {
where += " WHEN " + outgoingType + " THEN " + DATE_SENT + " < " + date;
}
where += (" ELSE " + DATE_RECEIVED + " < " + date + " END)");
db.delete(TABLE_NAME, where, new String[] {threadId + ""});
}
/*package*/ void deleteThreads(Set<Long> threadIds) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String where = "";
for (long threadId : threadIds) {
where += THREAD_ID + " = '" + threadId + "' OR ";
}
where = where.substring(0, where.length() - 4);
db.delete(TABLE_NAME, where, null);
}
/*package */ void deleteAllThreads() {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
/*package*/ SQLiteDatabase beginTransaction() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
return database;
}
/*package*/ void endTransaction(SQLiteDatabase database) {
database.setTransactionSuccessful();
database.endTransaction();
}
/*package*/ SQLiteStatement createInsertStatement(SQLiteDatabase database) {
return database.compileStatement("INSERT INTO " + TABLE_NAME + " (" + ADDRESS + ", " +
PERSON + ", " +
DATE_SENT + ", " +
DATE_RECEIVED + ", " +
PROTOCOL + ", " +
READ + ", " +
STATUS + ", " +
TYPE + ", " +
REPLY_PATH_PRESENT + ", " +
SUBJECT + ", " +
BODY + ", " +
SERVICE_CENTER +
", " + THREAD_ID + ") " +
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
}
public static class Status {
public static final int STATUS_NONE = -1;
public static final int STATUS_COMPLETE = 0;
public static final int STATUS_PENDING = 0x20;
public static final int STATUS_FAILED = 0x40;
}
public Reader readerFor(Cursor cursor) {
return new Reader(cursor);
}
public class Reader {
private final Cursor cursor;
public Reader(Cursor cursor) {
this.cursor = cursor;
}
public SmsMessageRecord getNext() {
if (cursor == null || !cursor.moveToNext())
return null;
return getCurrent();
}
public int getCount() {
if (cursor == null) return 0;
else return cursor.getCount();
}
public SmsMessageRecord getCurrent() {
long messageId = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.ID));
String address = cursor.getString(cursor.getColumnIndexOrThrow(SmsDatabase.ADDRESS));
int addressDeviceId = cursor.getInt(cursor.getColumnIndexOrThrow(SmsDatabase.ADDRESS_DEVICE_ID));
long type = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.TYPE));
long dateReceived = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.NORMALIZED_DATE_RECEIVED));
long dateSent = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.NORMALIZED_DATE_SENT));
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.THREAD_ID));
int status = cursor.getInt(cursor.getColumnIndexOrThrow(SmsDatabase.STATUS));
int receiptCount = cursor.getInt(cursor.getColumnIndexOrThrow(SmsDatabase.RECEIPT_COUNT));
String mismatchDocument = cursor.getString(cursor.getColumnIndexOrThrow(SmsDatabase.MISMATCHED_IDENTITIES));
List<IdentityKeyMismatch> mismatches = getMismatches(mismatchDocument);
Recipients recipients = getRecipientsFor(address);
DisplayRecord.Body body = getBody(cursor);
return new SmsMessageRecord(context, messageId, body, recipients,
recipients.getPrimaryRecipient(),
addressDeviceId,
dateSent, dateReceived, receiptCount, type,
threadId, status, mismatches);
}
private Recipients getRecipientsFor(String address) {
if (address != null) {
Recipients recipients = RecipientFactory.getRecipientsFromString(context, address, true);
if (recipients == null || recipients.isEmpty()) {
return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
}
return recipients;
} else {
Log.w(TAG, "getRecipientsFor() address is null");
return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
}
}
private List<IdentityKeyMismatch> getMismatches(String document) {
try {
if (!TextUtils.isEmpty(document)) {
return JsonUtils.fromJson(document, IdentityKeyMismatchList.class).getList();
}
} catch (IOException e) {
Log.w(TAG, e);
}
return new LinkedList<>();
}
protected DisplayRecord.Body getBody(Cursor cursor) {
long type = cursor.getLong(cursor.getColumnIndexOrThrow(SmsDatabase.TYPE));
String body = cursor.getString(cursor.getColumnIndexOrThrow(SmsDatabase.BODY));
if (Types.isSymmetricEncryption(type)) {
return new DisplayRecord.Body(body, false);
} else {
return new DisplayRecord.Body(body, true);
}
}
public void close() {
cursor.close();
}
}
}
| 28,096 | 39.427338 | 128 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/SmsMigrator.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.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.util.StringTokenizer;
public class SmsMigrator {
private static final String TAG = SmsMigrator.class.getSimpleName();
private static void addEncryptedStringToStatement(Context context, SQLiteStatement statement,
Cursor cursor, MasterSecret masterSecret,
int index, String key)
{
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (cursor.isNull(columnIndex)) {
statement.bindNull(index);
} else {
statement.bindString(index, encrypt(masterSecret, cursor.getString(columnIndex)));
}
}
private static void addStringToStatement(SQLiteStatement statement, Cursor cursor,
int index, String key)
{
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (cursor.isNull(columnIndex)) {
statement.bindNull(index);
} else {
statement.bindString(index, cursor.getString(columnIndex));
}
}
private static void addIntToStatement(SQLiteStatement statement, Cursor cursor,
int index, String key)
{
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (cursor.isNull(columnIndex)) {
statement.bindNull(index);
} else {
statement.bindLong(index, cursor.getLong(columnIndex));
}
}
private static void addTranslatedTypeToStatement(SQLiteStatement statement, Cursor cursor,
int index, String key)
{
int columnIndex = cursor.getColumnIndexOrThrow(key);
if (cursor.isNull(columnIndex)) {
statement.bindLong(index, SmsDatabase.Types.BASE_INBOX_TYPE | SmsDatabase.Types.ENCRYPTION_SYMMETRIC_BIT);
} else {
long theirType = cursor.getLong(columnIndex);
statement.bindLong(index, SmsDatabase.Types.translateFromSystemBaseType(theirType) | SmsDatabase.Types.ENCRYPTION_SYMMETRIC_BIT);
}
}
private static boolean isAppropriateTypeForMigration(Cursor cursor, int columnIndex) {
long systemType = cursor.getLong(columnIndex);
long ourType = SmsDatabase.Types.translateFromSystemBaseType(systemType);
return ourType == MmsSmsColumns.Types.BASE_INBOX_TYPE ||
ourType == MmsSmsColumns.Types.BASE_SENT_TYPE ||
ourType == MmsSmsColumns.Types.BASE_SENT_FAILED_TYPE;
}
private static void getContentValuesForRow(Context context, MasterSecret masterSecret,
Cursor cursor, long threadId,
SQLiteStatement statement)
{
addStringToStatement(statement, cursor, 1, SmsDatabase.ADDRESS);
addIntToStatement(statement, cursor, 2, SmsDatabase.PERSON);
addIntToStatement(statement, cursor, 3, SmsDatabase.DATE_RECEIVED);
addIntToStatement(statement, cursor, 4, SmsDatabase.DATE_RECEIVED);
addIntToStatement(statement, cursor, 5, SmsDatabase.PROTOCOL);
addIntToStatement(statement, cursor, 6, SmsDatabase.READ);
addIntToStatement(statement, cursor, 7, SmsDatabase.STATUS);
addTranslatedTypeToStatement(statement, cursor, 8, SmsDatabase.TYPE);
addIntToStatement(statement, cursor, 9, SmsDatabase.REPLY_PATH_PRESENT);
addStringToStatement(statement, cursor, 10, SmsDatabase.SUBJECT);
addEncryptedStringToStatement(context, statement, cursor, masterSecret, 11, SmsDatabase.BODY);
addStringToStatement(statement, cursor, 12, SmsDatabase.SERVICE_CENTER);
statement.bindLong(13, threadId);
}
private static String getTheirCanonicalAddress(Context context, String theirRecipientId) {
Uri uri = Uri.parse("content://mms-sms/canonical-address/" + theirRecipientId);
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return cursor.getString(0);
} else {
return null;
}
} catch (IllegalStateException iae) {
Log.w("SmsMigrator", iae);
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
private static Recipients getOurRecipients(Context context, String theirRecipients) {
StringTokenizer tokenizer = new StringTokenizer(theirRecipients.trim(), " ");
StringBuilder sb = new StringBuilder();
while (tokenizer.hasMoreTokens()) {
String theirRecipientId = tokenizer.nextToken();
String address = getTheirCanonicalAddress(context, theirRecipientId);
if (address == null)
continue;
if (sb.length() != 0)
sb.append(',');
sb.append(address);
}
if (sb.length() == 0) return null;
else return RecipientFactory.getRecipientsFromString(context, sb.toString(), true);
}
private static String encrypt(MasterSecret masterSecret, String body)
{
MasterCipher masterCipher = new MasterCipher(masterSecret);
return masterCipher.encryptBody(body);
}
private static void migrateConversation(Context context, MasterSecret masterSecret,
SmsMigrationProgressListener listener,
ProgressDescription progress,
long theirThreadId, long ourThreadId)
{
SmsDatabase ourSmsDatabase = DatabaseFactory.getSmsDatabase(context);
Cursor cursor = null;
try {
Uri uri = Uri.parse("content://sms/conversations/" + theirThreadId);
try {
cursor = context.getContentResolver().query(uri, null, null, null, null);
} catch (SQLiteException e) {
/// Work around for weird sony-specific (?) bug: #4309
Log.w(TAG, e);
return;
}
SQLiteDatabase transaction = ourSmsDatabase.beginTransaction();
SQLiteStatement statement = ourSmsDatabase.createInsertStatement(transaction);
while (cursor != null && cursor.moveToNext()) {
int typeColumn = cursor.getColumnIndex(SmsDatabase.TYPE);
if (cursor.isNull(typeColumn) || isAppropriateTypeForMigration(cursor, typeColumn)) {
getContentValuesForRow(context, masterSecret, cursor, ourThreadId, statement);
statement.execute();
}
listener.progressUpdate(new ProgressDescription(progress, cursor.getCount(), cursor.getPosition()));
}
ourSmsDatabase.endTransaction(transaction);
DatabaseFactory.getThreadDatabase(context).update(ourThreadId);
DatabaseFactory.getThreadDatabase(context).notifyConversationListeners(ourThreadId);
} finally {
if (cursor != null)
cursor.close();
}
}
public static void migrateDatabase(Context context,
MasterSecret masterSecret,
SmsMigrationProgressListener listener)
{
// if (context.getSharedPreferences("SecureSMS", Context.MODE_PRIVATE).getBoolean("migrated", false))
// return;
ThreadDatabase threadDatabase = DatabaseFactory.getThreadDatabase(context);
Cursor cursor = null;
try {
Uri threadListUri = Uri.parse("content://mms-sms/conversations?simple=true");
cursor = context.getContentResolver().query(threadListUri, null, null, null, "date ASC");
while (cursor != null && cursor.moveToNext()) {
long theirThreadId = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
String theirRecipients = cursor.getString(cursor.getColumnIndexOrThrow("recipient_ids"));
Recipients ourRecipients = getOurRecipients(context, theirRecipients);
ProgressDescription progress = new ProgressDescription(cursor.getCount(), cursor.getPosition(), 100, 0);
if (ourRecipients != null) {
long ourThreadId = threadDatabase.getThreadIdFor(ourRecipients);
migrateConversation(context, masterSecret,
listener, progress,
theirThreadId, ourThreadId);
}
progress.incrementPrimaryComplete();
listener.progressUpdate(progress);
}
} finally {
if (cursor != null)
cursor.close();
}
context.getSharedPreferences("SecureSMS", Context.MODE_PRIVATE).edit()
.putBoolean("migrated", true).apply();
}
public interface SmsMigrationProgressListener {
public void progressUpdate(ProgressDescription description);
}
public static class ProgressDescription {
public final int primaryTotal;
public int primaryComplete;
public final int secondaryTotal;
public final int secondaryComplete;
public ProgressDescription(int primaryTotal, int primaryComplete,
int secondaryTotal, int secondaryComplete)
{
this.primaryTotal = primaryTotal;
this.primaryComplete = primaryComplete;
this.secondaryTotal = secondaryTotal;
this.secondaryComplete = secondaryComplete;
}
public ProgressDescription(ProgressDescription that, int secondaryTotal, int secondaryComplete) {
this.primaryComplete = that.primaryComplete;
this.primaryTotal = that.primaryTotal;
this.secondaryComplete = secondaryComplete;
this.secondaryTotal = secondaryTotal;
}
public void incrementPrimaryComplete() {
primaryComplete += 1;
}
}
}
| 10,727 | 37.314286 | 135 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/TextSecureDirectory.java | package org.thoughtcrime.securesms.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.text.TextUtils;
import android.util.Log;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TextSecureDirectory {
private static final int INTRODUCED_CHANGE_FROM_TOKEN_TO_E164_NUMBER = 2;
private static final int INTRODUCED_VOICE_COLUMN = 4;
private static final String DATABASE_NAME = "whisper_directory.db";
private static final int DATABASE_VERSION = 4;
private static final String TABLE_NAME = "directory";
private static final String ID = "_id";
private static final String NUMBER = "number";
private static final String REGISTERED = "registered";
private static final String RELAY = "relay";
private static final String TIMESTAMP = "timestamp";
private static final String VOICE = "voice";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY, " +
NUMBER + " TEXT UNIQUE, " +
REGISTERED + " INTEGER, " +
RELAY + " TEXT, " +
TIMESTAMP + " INTEGER, " +
VOICE + " INTEGER);";
private static final Object instanceLock = new Object();
private static volatile TextSecureDirectory instance;
public static TextSecureDirectory getInstance(Context context) {
if (instance == null) {
synchronized (instanceLock) {
if (instance == null) {
instance = new TextSecureDirectory(context.getApplicationContext());
}
}
}
return instance;
}
private final DatabaseHelper databaseHelper;
private final Context context;
private TextSecureDirectory(Context context) {
this.context = context;
this.databaseHelper = new DatabaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public boolean isSecureTextSupported(String e164number) throws NotInDirectoryException {
if (e164number == null || e164number.length() == 0) {
return false;
}
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME,
new String[]{REGISTERED}, NUMBER + " = ?",
new String[] {e164number}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return cursor.getInt(0) == 1;
} else {
throw new NotInDirectoryException();
}
} finally {
if (cursor != null)
cursor.close();
}
}
public boolean isSecureVoiceSupported(String e164number) throws NotInDirectoryException {
if (TextUtils.isEmpty(e164number)) {
return false;
}
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME,
new String[]{VOICE}, NUMBER + " = ?",
new String[] {e164number}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return cursor.getInt(0) == 1;
} else {
throw new NotInDirectoryException();
}
} finally {
if (cursor != null)
cursor.close();
}
}
public String getRelay(String e164number) {
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.query(TABLE_NAME, null, NUMBER + " = ?", new String[]{e164number}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndexOrThrow(RELAY));
}
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
public void setNumber(ContactTokenDetails token, boolean active) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NUMBER, token.getNumber());
values.put(RELAY, token.getRelay());
values.put(REGISTERED, active ? 1 : 0);
values.put(TIMESTAMP, System.currentTimeMillis());
db.replace(TABLE_NAME, null, values);
}
public void setNumbers(List<ContactTokenDetails> activeTokens, Collection<String> inactiveTokens) {
long timestamp = System.currentTimeMillis();
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.beginTransaction();
try {
for (ContactTokenDetails token : activeTokens) {
Log.w("Directory", "Adding active token: " + token.getNumber() + ", " + token.getToken());
ContentValues values = new ContentValues();
values.put(NUMBER, token.getNumber());
values.put(REGISTERED, 1);
values.put(TIMESTAMP, timestamp);
values.put(RELAY, token.getRelay());
values.put(VOICE, token.isVoice());
db.replace(TABLE_NAME, null, values);
}
for (String token : inactiveTokens) {
ContentValues values = new ContentValues();
values.put(NUMBER, token);
values.put(REGISTERED, 0);
values.put(TIMESTAMP, timestamp);
db.replace(TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
public Set<String> getPushEligibleContactNumbers(String localNumber) {
final Uri uri = Phone.CONTENT_URI;
final Set<String> results = new HashSet<>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[] {Phone.NUMBER}, null, null, null);
while (cursor != null && cursor.moveToNext()) {
final String rawNumber = cursor.getString(0);
if (rawNumber != null) {
try {
final String e164Number = PhoneNumberFormatter.formatNumber(rawNumber, localNumber);
results.add(e164Number);
} catch (InvalidNumberException e) {
Log.w("Directory", "Invalid number: " + rawNumber);
}
}
}
if (cursor != null)
cursor.close();
final SQLiteDatabase readableDb = databaseHelper.getReadableDatabase();
if (readableDb != null) {
cursor = readableDb.query(TABLE_NAME, new String[]{NUMBER},
null, null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
results.add(cursor.getString(0));
}
}
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
public List<String> getActiveNumbers() {
final List<String> results = new ArrayList<>();
Cursor cursor = null;
try {
cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[]{NUMBER},
REGISTERED + " = 1", null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
results.add(cursor.getString(0));
}
return results;
} finally {
if (cursor != null)
cursor.close();
}
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory,
int version)
{
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < INTRODUCED_CHANGE_FROM_TOKEN_TO_E164_NUMBER) {
db.execSQL("DROP TABLE directory;");
db.execSQL("CREATE TABLE directory ( _id INTEGER PRIMARY KEY, " +
"number TEXT UNIQUE, " +
"registered INTEGER, " +
"relay TEXT, " +
"supports_sms INTEGER, " +
"timestamp INTEGER);");
}
if (oldVersion < INTRODUCED_VOICE_COLUMN) {
db.execSQL("ALTER TABLE directory ADD COLUMN voice INTEGER;");
}
}
}
}
| 8,608 | 31.123134 | 113 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/ThreadDatabase.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.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.MergeCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.crypto.MasterCipher;
import org.thoughtcrime.securesms.database.model.DisplayRecord;
import org.thoughtcrime.securesms.database.model.MediaMmsMessageRecord;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.thoughtcrime.securesms.database.model.ThreadRecord;
import org.thoughtcrime.securesms.mms.Slide;
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.util.Util;
import org.whispersystems.libaxolotl.InvalidMessageException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class ThreadDatabase extends Database {
private static final String TAG = ThreadDatabase.class.getSimpleName();
static final String TABLE_NAME = "thread";
public static final String ID = "_id";
public static final String DATE = "date";
public static final String MESSAGE_COUNT = "message_count";
public static final String RECIPIENT_IDS = "recipient_ids";
public static final String SNIPPET = "snippet";
private static final String SNIPPET_CHARSET = "snippet_cs";
public static final String READ = "read";
private static final String TYPE = "type";
private static final String ERROR = "error";
public static final String SNIPPET_TYPE = "snippet_type";
private static final String SNIPPET_URI = "snippet_uri";
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY, " +
DATE + " INTEGER DEFAULT 0, " + MESSAGE_COUNT + " INTEGER DEFAULT 0, " +
RECIPIENT_IDS + " TEXT, " + SNIPPET + " TEXT, " + SNIPPET_CHARSET + " INTEGER DEFAULT 0, " +
READ + " INTEGER DEFAULT 1, " + TYPE + " INTEGER DEFAULT 0, " + ERROR + " INTEGER DEFAULT 0, " +
SNIPPET_TYPE + " INTEGER DEFAULT 0, " + SNIPPET_URI + " TEXT DEFAULT NULL);";
public static final String[] CREATE_INDEXS = {
"CREATE INDEX IF NOT EXISTS thread_recipient_ids_index ON " + TABLE_NAME + " (" + RECIPIENT_IDS + ");",
};
public ThreadDatabase(Context context, SQLiteOpenHelper databaseHelper) {
super(context, databaseHelper);
}
private long[] getRecipientIds(Recipients recipients) {
Set<Long> recipientSet = new HashSet<>();
List<Recipient> recipientList = recipients.getRecipientsList();
for (Recipient recipient : recipientList) {
recipientSet.add(recipient.getRecipientId());
}
long[] recipientArray = new long[recipientSet.size()];
int i = 0;
for (Long recipientId : recipientSet) {
recipientArray[i++] = recipientId;
}
Arrays.sort(recipientArray);
return recipientArray;
}
private String getRecipientsAsString(long[] recipientIds) {
StringBuilder sb = new StringBuilder();
for (int i=0;i<recipientIds.length;i++) {
if (i != 0) sb.append(' ');
sb.append(recipientIds[i]);
}
return sb.toString();
}
private long createThreadForRecipients(String recipients, int recipientCount, int distributionType) {
ContentValues contentValues = new ContentValues(4);
long date = System.currentTimeMillis();
contentValues.put(DATE, date - date % 1000);
contentValues.put(RECIPIENT_IDS, recipients);
if (recipientCount > 1)
contentValues.put(TYPE, distributionType);
contentValues.put(MESSAGE_COUNT, 0);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
return db.insert(TABLE_NAME, null, contentValues);
}
private void updateThread(long threadId, long count, String body, @Nullable Uri attachment, long date, long type)
{
ContentValues contentValues = new ContentValues(4);
contentValues.put(DATE, date - date % 1000);
contentValues.put(MESSAGE_COUNT, count);
contentValues.put(SNIPPET, body);
contentValues.put(SNIPPET_URI, attachment == null ? null : attachment.toString());
contentValues.put(SNIPPET_TYPE, type);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID + " = ?", new String[] {threadId + ""});
notifyConversationListListeners();
}
public void updateSnippet(long threadId, String snippet, @Nullable Uri attachment, long date, long type) {
ContentValues contentValues = new ContentValues(3);
contentValues.put(DATE, date - date % 1000);
contentValues.put(SNIPPET, snippet);
contentValues.put(SNIPPET_TYPE, type);
contentValues.put(SNIPPET_URI, attachment == null ? null : attachment.toString());
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID + " = ?", new String[] {threadId + ""});
notifyConversationListListeners();
}
private void deleteThread(long threadId) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, ID_WHERE, new String[] {threadId + ""});
notifyConversationListListeners();
}
private void deleteThreads(Set<Long> threadIds) {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
String where = "";
for (long threadId : threadIds) {
where += ID + " = '" + threadId + "' OR ";
}
where = where.substring(0, where.length() - 4);
db.delete(TABLE_NAME, where, null);
notifyConversationListListeners();
}
private void deleteAllThreads() {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
notifyConversationListListeners();
}
public void trimAllThreads(int length, ProgressListener listener) {
Cursor cursor = null;
int threadCount = 0;
int complete = 0;
try {
cursor = this.getConversationList();
if (cursor != null)
threadCount = cursor.getCount();
while (cursor != null && cursor.moveToNext()) {
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(ID));
trimThread(threadId, length);
listener.onProgress(++complete, threadCount);
}
} finally {
if (cursor != null)
cursor.close();
}
}
public void trimThread(long threadId, int length) {
Log.w("ThreadDatabase", "Trimming thread: " + threadId + " to: " + length);
Cursor cursor = null;
try {
cursor = DatabaseFactory.getMmsSmsDatabase(context).getConversation(threadId);
if (cursor != null && length > 0 && cursor.getCount() > length) {
Log.w("ThreadDatabase", "Cursor count is greater than length!");
cursor.moveToPosition(length - 1);
long lastTweetDate = cursor.getLong(cursor.getColumnIndexOrThrow(MmsSmsColumns.NORMALIZED_DATE_RECEIVED));
Log.w("ThreadDatabase", "Cut off tweet date: " + lastTweetDate);
DatabaseFactory.getSmsDatabase(context).deleteMessagesInThreadBeforeDate(threadId, lastTweetDate);
DatabaseFactory.getMmsDatabase(context).deleteMessagesInThreadBeforeDate(threadId, lastTweetDate);
update(threadId);
notifyConversationListeners(threadId);
}
} finally {
if (cursor != null)
cursor.close();
}
}
public void setAllThreadsRead() {
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues(1);
contentValues.put(READ, 1);
db.update(TABLE_NAME, contentValues, null, null);
DatabaseFactory.getSmsDatabase(context).setAllMessagesRead();
DatabaseFactory.getMmsDatabase(context).setAllMessagesRead();
notifyConversationListListeners();
}
public void setRead(long threadId) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(READ, 1);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {threadId+""});
DatabaseFactory.getSmsDatabase(context).setMessagesRead(threadId);
DatabaseFactory.getMmsDatabase(context).setMessagesRead(threadId);
notifyConversationListListeners();
}
public void setUnread(long threadId) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(READ, 0);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {threadId + ""});
notifyConversationListListeners();
}
public void setDistributionType(long threadId, int distributionType) {
ContentValues contentValues = new ContentValues(1);
contentValues.put(TYPE, distributionType);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {threadId + ""});
notifyConversationListListeners();
}
public Cursor getFilteredConversationList(List<String> filter) {
if (filter == null || filter.size() == 0)
return null;
List<Long> rawRecipientIds = DatabaseFactory.getAddressDatabase(context).getCanonicalAddressIds(filter);
if (rawRecipientIds == null || rawRecipientIds.size() == 0)
return null;
SQLiteDatabase db = databaseHelper.getReadableDatabase();
List<List<Long>> partitionedRecipientIds = Util.partition(rawRecipientIds, 900);
List<Cursor> cursors = new LinkedList<>();
for (List<Long> recipientIds : partitionedRecipientIds) {
String selection = RECIPIENT_IDS + " = ?";
String[] selectionArgs = new String[recipientIds.size()];
for (int i=0;i<recipientIds.size()-1;i++)
selection += (" OR " + RECIPIENT_IDS + " = ?");
int i= 0;
for (long id : recipientIds) {
selectionArgs[i++] = String.valueOf(id);
}
cursors.add(db.query(TABLE_NAME, null, selection, selectionArgs, null, null, DATE + " DESC"));
}
Cursor cursor = cursors.size() > 1 ? new MergeCursor(cursors.toArray(new Cursor[cursors.size()])) : cursors.get(0);
setNotifyConverationListListeners(cursor);
return cursor;
}
public Cursor getConversationList() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, DATE + " DESC");
setNotifyConverationListListeners(cursor);
return cursor;
}
public void deleteConversation(long threadId) {
DatabaseFactory.getSmsDatabase(context).deleteThread(threadId);
DatabaseFactory.getMmsDatabase(context).deleteThread(threadId);
DatabaseFactory.getDraftDatabase(context).clearDrafts(threadId);
deleteThread(threadId);
notifyConversationListeners(threadId);
notifyConversationListListeners();
}
public void deleteConversations(Set<Long> selectedConversations) {
DatabaseFactory.getSmsDatabase(context).deleteThreads(selectedConversations);
DatabaseFactory.getMmsDatabase(context).deleteThreads(selectedConversations);
DatabaseFactory.getDraftDatabase(context).clearDrafts(selectedConversations);
deleteThreads(selectedConversations);
notifyConversationListeners(selectedConversations);
notifyConversationListListeners();
}
public void deleteAllConversations() {
DatabaseFactory.getSmsDatabase(context).deleteAllThreads();
DatabaseFactory.getMmsDatabase(context).deleteAllThreads();
DatabaseFactory.getDraftDatabase(context).clearAllDrafts();
deleteAllThreads();
}
public long getThreadIdIfExistsFor(Recipients recipients) {
long[] recipientIds = getRecipientIds(recipients);
String recipientsList = getRecipientsAsString(recipientIds);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String where = RECIPIENT_IDS + " = ?";
String[] recipientsArg = new String[] {recipientsList};
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, new String[]{ID}, where, recipientsArg, null, null, null);
if (cursor != null && cursor.moveToFirst())
return cursor.getLong(cursor.getColumnIndexOrThrow(ID));
else
return -1L;
} finally {
if (cursor != null)
cursor.close();
}
}
public long getThreadIdFor(Recipients recipients) {
return getThreadIdFor(recipients, DistributionTypes.DEFAULT);
}
public long getThreadIdFor(Recipients recipients, int distributionType) {
long[] recipientIds = getRecipientIds(recipients);
String recipientsList = getRecipientsAsString(recipientIds);
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String where = RECIPIENT_IDS + " = ?";
String[] recipientsArg = new String[] {recipientsList};
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, new String[]{ID}, where, recipientsArg, null, null, null);
if (cursor != null && cursor.moveToFirst())
return cursor.getLong(cursor.getColumnIndexOrThrow(ID));
else
return createThreadForRecipients(recipientsList, recipientIds.length, distributionType);
} finally {
if (cursor != null)
cursor.close();
}
}
public @Nullable Recipients getRecipientsForThreadId(long threadId) {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, null, ID + " = ?", new String[] {threadId+""}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String recipientIds = cursor.getString(cursor.getColumnIndexOrThrow(RECIPIENT_IDS));
return RecipientFactory.getRecipientsForIds(context, recipientIds, false);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public boolean update(long threadId) {
MmsSmsDatabase mmsSmsDatabase = DatabaseFactory.getMmsSmsDatabase(context);
long count = mmsSmsDatabase.getConversationCount(threadId);
if (count == 0) {
deleteThread(threadId);
notifyConversationListListeners();
return true;
}
MmsSmsDatabase.Reader reader = null;
try {
reader = mmsSmsDatabase.readerFor(mmsSmsDatabase.getConversationSnippet(threadId));
MessageRecord record;
if (reader != null && (record = reader.getNext()) != null) {
final long timestamp;
if (record.isPush()) timestamp = record.getDateSent();
else timestamp = record.getDateReceived();
updateThread(threadId, count, record.getBody().getBody(), getAttachmentUriFor(record), timestamp, record.getType());
notifyConversationListListeners();
return false;
} else {
deleteThread(threadId);
notifyConversationListListeners();
return true;
}
} finally {
if (reader != null)
reader.close();
}
}
private @Nullable Uri getAttachmentUriFor(MessageRecord record) {
if (!record.isMms() || record.isMmsNotification() || record.isGroupAction()) return null;
SlideDeck slideDeck = ((MediaMmsMessageRecord)record).getSlideDeck();
Slide thumbnail = slideDeck.getThumbnailSlide();
return thumbnail != null ? thumbnail.getThumbnailUri() : null;
}
public static interface ProgressListener {
public void onProgress(int complete, int total);
}
public Reader readerFor(Cursor cursor, MasterCipher masterCipher) {
return new Reader(cursor, masterCipher);
}
public static class DistributionTypes {
public static final int DEFAULT = 2;
public static final int BROADCAST = 1;
public static final int CONVERSATION = 2;
}
public class Reader {
private final Cursor cursor;
private final MasterCipher masterCipher;
public Reader(Cursor cursor, MasterCipher masterCipher) {
this.cursor = cursor;
this.masterCipher = masterCipher;
}
public ThreadRecord getNext() {
if (cursor == null || !cursor.moveToNext())
return null;
return getCurrent();
}
public ThreadRecord getCurrent() {
long threadId = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.ID));
String recipientId = cursor.getString(cursor.getColumnIndexOrThrow(ThreadDatabase.RECIPIENT_IDS));
Recipients recipients = RecipientFactory.getRecipientsForIds(context, recipientId, true);
DisplayRecord.Body body = getPlaintextBody(cursor);
long date = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.DATE));
long count = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.MESSAGE_COUNT));
long read = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.READ));
long type = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.SNIPPET_TYPE));
int distributionType = cursor.getInt(cursor.getColumnIndexOrThrow(ThreadDatabase.TYPE));
Uri snippetUri = getSnippetUri(cursor);
return new ThreadRecord(context, body, snippetUri, recipients, date, count,
read == 1, threadId, type, distributionType);
}
private DisplayRecord.Body getPlaintextBody(Cursor cursor) {
try {
long type = cursor.getLong(cursor.getColumnIndexOrThrow(ThreadDatabase.SNIPPET_TYPE));
String body = cursor.getString(cursor.getColumnIndexOrThrow(SNIPPET));
if (!TextUtils.isEmpty(body) && masterCipher != null && MmsSmsColumns.Types.isSymmetricEncryption(type)) {
return new DisplayRecord.Body(masterCipher.decryptBody(body), true);
} else if (!TextUtils.isEmpty(body) && masterCipher == null && MmsSmsColumns.Types.isSymmetricEncryption(type)) {
return new DisplayRecord.Body(body, false);
} else {
return new DisplayRecord.Body(body, true);
}
} catch (InvalidMessageException e) {
Log.w("ThreadDatabase", e);
return new DisplayRecord.Body(context.getString(R.string.ThreadDatabase_error_decrypting_message), true);
}
}
private @Nullable Uri getSnippetUri(Cursor cursor) {
if (cursor.isNull(cursor.getColumnIndexOrThrow(ThreadDatabase.SNIPPET_URI))) {
return null;
}
try {
return Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(ThreadDatabase.SNIPPET_URI)));
} catch (IllegalArgumentException e) {
Log.w(TAG, e);
return null;
}
}
public void close() {
cursor.close();
}
}
}
| 19,783 | 36.258004 | 141 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/XmlBackup.java | package org.thoughtcrime.securesms.database;
import android.text.TextUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XmlBackup {
private static final String PROTOCOL = "protocol";
private static final String ADDRESS = "address";
private static final String DATE = "date";
private static final String TYPE = "type";
private static final String SUBJECT = "subject";
private static final String BODY = "body";
private static final String SERVICE_CENTER = "service_center";
private static final String READ = "read";
private static final String STATUS = "status";
private static final String TOA = "toa";
private static final String SC_TOA = "sc_toa";
private static final String LOCKED = "locked";
private final XmlPullParser parser;
public XmlBackup(String path) throws XmlPullParserException, FileNotFoundException {
this.parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(new FileInputStream(path), null);
}
public XmlBackupItem getNext() throws IOException, XmlPullParserException {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (!name.equalsIgnoreCase("sms")) {
continue;
}
int attributeCount = parser.getAttributeCount();
if (attributeCount <= 0) {
continue;
}
XmlBackupItem item = new XmlBackupItem();
for (int i=0;i<attributeCount;i++) {
String attributeName = parser.getAttributeName(i);
if (attributeName.equals(PROTOCOL )) item.protocol = Integer.parseInt(parser.getAttributeValue(i));
else if (attributeName.equals(ADDRESS )) item.address = parser.getAttributeValue(i);
else if (attributeName.equals(DATE )) item.date = Long.parseLong(parser.getAttributeValue(i));
else if (attributeName.equals(TYPE )) item.type = Integer.parseInt(parser.getAttributeValue(i));
else if (attributeName.equals(SUBJECT )) item.subject = parser.getAttributeValue(i);
else if (attributeName.equals(BODY )) item.body = parser.getAttributeValue(i);
else if (attributeName.equals(SERVICE_CENTER)) item.serviceCenter = parser.getAttributeValue(i);
else if (attributeName.equals(READ )) item.read = Integer.parseInt(parser.getAttributeValue(i));
else if (attributeName.equals(STATUS )) item.status = Integer.parseInt(parser.getAttributeValue(i));
}
return item;
}
return null;
}
public static class XmlBackupItem {
private int protocol;
private String address;
private long date;
private int type;
private String subject;
private String body;
private String serviceCenter;
private int read;
private int status;
public XmlBackupItem() {}
public XmlBackupItem(int protocol, String address, long date, int type, String subject,
String body, String serviceCenter, int read, int status)
{
this.protocol = protocol;
this.address = address;
this.date = date;
this.type = type;
this.subject = subject;
this.body = body;
this.serviceCenter = serviceCenter;
this.read = read;
this.status = status;
}
public int getProtocol() {
return protocol;
}
public String getAddress() {
return address;
}
public long getDate() {
return date;
}
public int getType() {
return type;
}
public String getSubject() {
return subject;
}
public String getBody() {
return body;
}
public String getServiceCenter() {
return serviceCenter;
}
public int getRead() {
return read;
}
public int getStatus() {
return status;
}
}
public static class Writer {
private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>";
private static final String CREATED_BY = "<!-- File Created By TextSecure -->";
private static final String OPEN_TAG_SMSES = "<smses count=\"%d\">";
private static final String CLOSE_TAG_SMSES = "</smses>";
private static final String OPEN_TAG_SMS = " <sms ";
private static final String CLOSE_EMPTYTAG = "/>";
private static final String OPEN_ATTRIBUTE = "=\"";
private static final String CLOSE_ATTRIBUTE = "\" ";
private static final Pattern PATTERN = Pattern.compile("[^\u0020-\uD7FF]");
private final BufferedWriter bufferedWriter;
public Writer(String path, int count) throws IOException {
bufferedWriter = new BufferedWriter(new FileWriter(path, false));
bufferedWriter.write(XML_HEADER);
bufferedWriter.newLine();
bufferedWriter.write(CREATED_BY);
bufferedWriter.newLine();
bufferedWriter.write(String.format(OPEN_TAG_SMSES, count));
}
public void writeItem(XmlBackupItem item) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(OPEN_TAG_SMS);
appendAttribute(stringBuilder, PROTOCOL, item.getProtocol());
appendAttribute(stringBuilder, ADDRESS, escapeXML(item.getAddress()));
appendAttribute(stringBuilder, DATE, item.getDate());
appendAttribute(stringBuilder, TYPE, item.getType());
appendAttribute(stringBuilder, SUBJECT, escapeXML(item.getSubject()));
appendAttribute(stringBuilder, BODY, escapeXML(item.getBody()));
appendAttribute(stringBuilder, TOA, "null");
appendAttribute(stringBuilder, SC_TOA, "null");
appendAttribute(stringBuilder, SERVICE_CENTER, item.getServiceCenter());
appendAttribute(stringBuilder, READ, item.getRead());
appendAttribute(stringBuilder, STATUS, item.getStatus());
appendAttribute(stringBuilder, LOCKED, 0);
stringBuilder.append(CLOSE_EMPTYTAG);
bufferedWriter.newLine();
bufferedWriter.write(stringBuilder.toString());
}
private <T> void appendAttribute(StringBuilder stringBuilder, String name, T value) {
stringBuilder.append(name).append(OPEN_ATTRIBUTE).append(value).append(CLOSE_ATTRIBUTE);
}
public void close() throws IOException {
bufferedWriter.newLine();
bufferedWriter.write(CLOSE_TAG_SMSES);
bufferedWriter.close();
}
private String escapeXML(String s) {
if (TextUtils.isEmpty(s)) return s;
Matcher matcher = PATTERN.matcher( s.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\"", """)
.replace("'", "'"));
StringBuffer st = new StringBuffer();
while (matcher.find()) {
String escaped="";
for (char ch: matcher.group(0).toCharArray()) {
escaped += ("&#" + ((int) ch) + ";");
}
matcher.appendReplacement(st, escaped);
}
matcher.appendTail(st);
return st.toString();
}
}
}
| 7,805 | 33.848214 | 122 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/documents/Document.java | package org.thoughtcrime.securesms.database.documents;
import java.util.List;
public interface Document<T> {
public int size();
public List<T> getList();
}
| 164 | 14 | 54 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/documents/IdentityKeyMismatch.java | package org.thoughtcrime.securesms.database.documents;
import android.util.Log;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.thoughtcrime.securesms.util.Base64;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.InvalidKeyException;
import java.io.IOException;
public class IdentityKeyMismatch {
private static final String TAG = IdentityKeyMismatch.class.getSimpleName();
@JsonProperty(value = "r")
private long recipientId;
@JsonProperty(value = "k")
@JsonSerialize(using = IdentityKeySerializer.class)
@JsonDeserialize(using = IdentityKeyDeserializer.class)
private IdentityKey identityKey;
public IdentityKeyMismatch() {}
public IdentityKeyMismatch(long recipientId, IdentityKey identityKey) {
this.recipientId = recipientId;
this.identityKey = identityKey;
}
public long getRecipientId() {
return recipientId;
}
public IdentityKey getIdentityKey() {
return identityKey;
}
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof IdentityKeyMismatch)) {
return false;
}
IdentityKeyMismatch that = (IdentityKeyMismatch)other;
return that.recipientId == this.recipientId && that.identityKey.equals(this.identityKey);
}
@Override
public int hashCode() {
return (int)recipientId ^ identityKey.hashCode();
}
private static class IdentityKeySerializer extends JsonSerializer<IdentityKey> {
@Override
public void serialize(IdentityKey value, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException
{
jsonGenerator.writeString(Base64.encodeBytes(value.serialize()));
}
}
private static class IdentityKeyDeserializer extends JsonDeserializer<IdentityKey> {
@Override
public IdentityKey deserialize(JsonParser jsonParser, DeserializationContext ctxt)
throws IOException
{
try {
return new IdentityKey(Base64.decode(jsonParser.getValueAsString()), 0);
} catch (InvalidKeyException e) {
Log.w(TAG, e);
throw new IOException(e);
}
}
}
}
| 2,597 | 29.209302 | 105 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/documents/IdentityKeyMismatchList.java | package org.thoughtcrime.securesms.database.documents;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.LinkedList;
import java.util.List;
public class IdentityKeyMismatchList implements Document<IdentityKeyMismatch> {
@JsonProperty(value = "m")
private List<IdentityKeyMismatch> mismatches;
public IdentityKeyMismatchList() {
this.mismatches = new LinkedList<>();
}
public IdentityKeyMismatchList(List<IdentityKeyMismatch> mismatches) {
this.mismatches = mismatches;
}
@Override
public int size() {
if (mismatches == null) return 0;
else return mismatches.size();
}
@Override
public List<IdentityKeyMismatch> getList() {
return mismatches;
}
}
| 738 | 22.09375 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/documents/NetworkFailure.java | package org.thoughtcrime.securesms.database.documents;
import com.fasterxml.jackson.annotation.JsonProperty;
public class NetworkFailure {
@JsonProperty(value = "r")
private long recipientId;
public NetworkFailure(long recipientId) {
this.recipientId = recipientId;
}
public NetworkFailure() {}
public long getRecipientId() {
return recipientId;
}
@Override
public boolean equals(Object other) {
if (other == null || !(other instanceof NetworkFailure)) return false;
NetworkFailure that = (NetworkFailure)other;
return this.recipientId == that.recipientId;
}
@Override
public int hashCode() {
return (int)recipientId;
}
}
| 681 | 19.666667 | 74 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/documents/NetworkFailureList.java | package org.thoughtcrime.securesms.database.documents;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.LinkedList;
import java.util.List;
public class NetworkFailureList implements Document<NetworkFailure> {
@JsonProperty(value = "l")
private List<NetworkFailure> failures;
public NetworkFailureList() {
this.failures = new LinkedList<>();
}
public NetworkFailureList(List<NetworkFailure> failures) {
this.failures = failures;
}
@Override
public int size() {
if (failures == null) return 0;
else return failures.size();
}
@Override
@JsonIgnore
public List<NetworkFailure> getList() {
return failures;
}
}
| 751 | 21.117647 | 69 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/BlockedContactsLoader.java | package org.thoughtcrime.securesms.database.loaders;
import android.content.Context;
import android.database.Cursor;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.util.AbstractCursorLoader;
public class BlockedContactsLoader extends AbstractCursorLoader {
public BlockedContactsLoader(Context context) {
super(context);
}
@Override
public Cursor getCursor() {
return DatabaseFactory.getRecipientPreferenceDatabase(getContext())
.getBlocked();
}
}
| 545 | 23.818182 | 71 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/ConversationListLoader.java | package org.thoughtcrime.securesms.database.loaders;
import android.content.Context;
import android.database.Cursor;
import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.util.AbstractCursorLoader;
import java.util.List;
public class ConversationListLoader extends AbstractCursorLoader {
private final String filter;
public ConversationListLoader(Context context, String filter) {
super(context);
this.filter = filter;
}
@Override
public Cursor getCursor() {
if (filter != null && filter.trim().length() != 0) {
List<String> numbers = ContactAccessor.getInstance().getNumbersForThreadSearchFilter(context, filter);
return DatabaseFactory.getThreadDatabase(context).getFilteredConversationList(numbers);
} else {
return DatabaseFactory.getThreadDatabase(context).getConversationList();
}
}
}
| 949 | 28.6875 | 108 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/ConversationLoader.java | package org.thoughtcrime.securesms.database.loaders;
import android.content.Context;
import android.database.Cursor;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.util.AbstractCursorLoader;
public class ConversationLoader extends AbstractCursorLoader {
private final long threadId;
private long limit;
public ConversationLoader(Context context, long threadId, long limit) {
super(context);
this.threadId = threadId;
this.limit = limit;
}
public boolean hasLimit() {
return limit > 0;
}
@Override
public Cursor getCursor() {
return DatabaseFactory.getMmsSmsDatabase(context).getConversation(threadId, limit);
}
}
| 711 | 24.428571 | 87 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/CountryListLoader.java | package org.thoughtcrime.securesms.database.loaders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
public class CountryListLoader extends AsyncTaskLoader<ArrayList<Map<String, String>>> {
public CountryListLoader(Context context) {
super(context);
}
@Override
public ArrayList<Map<String, String>> loadInBackground() {
Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
for (String region : regions) {
Map<String, String> data = new HashMap<String, String>(2);
data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
data.put("country_code", "+" +PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
results.add(data);
}
Collections.sort(results, new RegionComparator());
return results;
}
private static class RegionComparator implements Comparator<Map<String, String>> {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
return lhs.get("country_name").compareTo(rhs.get("country_name"));
}
}
}
| 1,506 | 30.395833 | 99 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/DeviceListLoader.java | package org.thoughtcrime.securesms.database.loaders;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.messages.multidevice.DeviceInfo;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class DeviceListLoader extends AsyncTaskLoader<List<DeviceInfo>> {
private static final String TAG = DeviceListLoader.class.getSimpleName();
private final TextSecureAccountManager accountManager;
public DeviceListLoader(Context context, TextSecureAccountManager accountManager) {
super(context);
this.accountManager = accountManager;
}
@Override
public List<DeviceInfo> loadInBackground() {
try {
List<DeviceInfo> devices = accountManager.getDevices();
Iterator<DeviceInfo> iterator = devices.iterator();
while (iterator.hasNext()) {
if ((iterator.next().getId() == TextSecureAddress.DEFAULT_DEVICE_ID)) {
iterator.remove();
}
}
Collections.sort(devices, new DeviceInfoComparator());
return devices;
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
}
private static class DeviceInfoComparator implements Comparator<DeviceInfo> {
@Override
public int compare(DeviceInfo lhs, DeviceInfo rhs) {
if (lhs.getCreated() < rhs.getCreated()) return -1;
else if (lhs.getCreated() != rhs.getCreated()) return 1;
else return 0;
}
}
}
| 1,748 | 28.644068 | 85 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/IdentityLoader.java | package org.thoughtcrime.securesms.database.loaders;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.CursorLoader;
import org.thoughtcrime.securesms.database.DatabaseFactory;
public class IdentityLoader extends CursorLoader {
private final Context context;
public IdentityLoader(Context context) {
super(context);
this.context = context.getApplicationContext();
}
@Override
public Cursor loadInBackground() {
return DatabaseFactory.getIdentityDatabase(context).getIdentities();
}
}
| 568 | 22.708333 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/loaders/MessageDetailsLoader.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.database.loaders;
import android.content.Context;
import android.database.Cursor;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsSmsDatabase;
import org.thoughtcrime.securesms.util.AbstractCursorLoader;
public class MessageDetailsLoader extends AbstractCursorLoader {
private final String type;
private final long messageId;
public MessageDetailsLoader(Context context, String type, long messageId) {
super(context);
this.type = type;
this.messageId = messageId;
}
@Override
public Cursor getCursor() {
switch (type) {
case MmsSmsDatabase.SMS_TRANSPORT:
return DatabaseFactory.getEncryptingSmsDatabase(context).getMessage(messageId);
case MmsSmsDatabase.MMS_TRANSPORT:
return DatabaseFactory.getMmsDatabase(context).getMessage(messageId);
default:
throw new AssertionError("no valid message type specified");
}
}
}
| 1,697 | 34.375 | 87 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/DisplayRecord.java | /**
* Copyright (C) 2012 Moxie Marlinspike
*
* 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.database.model;
import android.content.Context;
import android.text.SpannableString;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.recipients.Recipients;
/**
* The base class for all message record models. Encapsulates basic data
* shared between ThreadRecord and MessageRecord.
*
* @author Moxie Marlinspike
*
*/
public abstract class DisplayRecord {
protected final Context context;
protected final long type;
private final Recipients recipients;
private final long dateSent;
private final long dateReceived;
private final long threadId;
private final Body body;
public DisplayRecord(Context context, Body body, Recipients recipients, long dateSent,
long dateReceived, long threadId, long type)
{
this.context = context.getApplicationContext();
this.threadId = threadId;
this.recipients = recipients;
this.dateSent = dateSent;
this.dateReceived = dateReceived;
this.type = type;
this.body = body;
}
public Body getBody() {
return body;
}
public abstract SpannableString getDisplayBody();
public Recipients getRecipients() {
return recipients;
}
public long getDateSent() {
return dateSent;
}
public long getDateReceived() {
return dateReceived;
}
public long getThreadId() {
return threadId;
}
public boolean isKeyExchange() {
return SmsDatabase.Types.isKeyExchangeType(type);
}
public boolean isEndSession() {
return SmsDatabase.Types.isEndSessionType(type);
}
public boolean isGroupUpdate() {
return SmsDatabase.Types.isGroupUpdate(type);
}
public boolean isGroupQuit() {
return SmsDatabase.Types.isGroupQuit(type);
}
public boolean isGroupAction() {
return isGroupUpdate() || isGroupQuit();
}
public boolean isCallLog() {
return SmsDatabase.Types.isCallLog(type);
}
public boolean isJoined() {
return SmsDatabase.Types.isJoinedType(type);
}
public boolean isIncomingCall() {
return SmsDatabase.Types.isIncomingCall(type);
}
public boolean isOutgoingCall() {
return SmsDatabase.Types.isOutgoingCall(type);
}
public boolean isMissedCall() {
return SmsDatabase.Types.isMissedCall(type);
}
public static class Body {
private final String body;
private final boolean plaintext;
public Body(String body, boolean plaintext) {
this.body = body;
this.plaintext = plaintext;
}
public boolean isPlaintext() {
return plaintext;
}
public String getBody() {
return body == null ? "" : body;
}
}
}
| 3,467 | 24.5 | 88 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/MediaMmsMessageRecord.java | /**
* Copyright (C) 2012 Moxie Marlinspike
*
* 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.database.model;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.mms.SlideDeck;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.util.List;
/**
* Represents the message record model for MMS messages that contain
* media (ie: they've been downloaded).
*
* @author Moxie Marlinspike
*
*/
public class MediaMmsMessageRecord extends MessageRecord {
private final static String TAG = MediaMmsMessageRecord.class.getSimpleName();
private final Context context;
private final int partCount;
private final @NonNull SlideDeck slideDeck;
public MediaMmsMessageRecord(Context context, long id, Recipients recipients,
Recipient individualRecipient, int recipientDeviceId,
long dateSent, long dateReceived, int deliveredCount,
long threadId, Body body,
@NonNull SlideDeck slideDeck,
int partCount, long mailbox,
List<IdentityKeyMismatch> mismatches,
List<NetworkFailure> failures)
{
super(context, id, body, recipients, individualRecipient, recipientDeviceId,
dateSent, dateReceived, threadId, DELIVERY_STATUS_NONE, deliveredCount, mailbox,
mismatches, failures);
this.context = context.getApplicationContext();
this.partCount = partCount;
this.slideDeck = slideDeck;
}
public @NonNull SlideDeck getSlideDeck() {
return slideDeck;
}
public boolean containsMediaSlide() {
return slideDeck.containsMediaSlide();
}
public int getPartCount() {
return partCount;
}
@Override
public boolean isMms() {
return true;
}
@Override
public boolean isMmsNotification() {
return false;
}
@Override
public SpannableString getDisplayBody() {
if (MmsDatabase.Types.isDecryptInProgressType(type)) {
return emphasisAdded(context.getString(R.string.MmsMessageRecord_decrypting_mms_please_wait));
} else if (MmsDatabase.Types.isFailedDecryptType(type)) {
return emphasisAdded(context.getString(R.string.MmsMessageRecord_bad_encrypted_mms_message));
} else if (MmsDatabase.Types.isDuplicateMessageType(type)) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_duplicate_message));
} else if (MmsDatabase.Types.isNoRemoteSessionType(type)) {
return emphasisAdded(context.getString(R.string.MmsMessageRecord_mms_message_encrypted_for_non_existing_session));
} else if (isLegacyMessage()) {
return emphasisAdded(context.getString(R.string.MessageRecord_message_encrypted_with_a_legacy_protocol_version_that_is_no_longer_supported));
} else if (!getBody().isPlaintext()) {
return emphasisAdded(context.getString(R.string.MessageNotifier_locked_message));
}
return super.getDisplayBody();
}
}
| 4,017 | 36.551402 | 147 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/MessageRecord.java | /**
* Copyright (C) 2012 Moxie Marlinpsike
*
* 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.database.model;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.MmsSmsColumns;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.GroupUtil;
import java.util.List;
/**
* The base class for message record models that are displayed in
* conversations, as opposed to models that are displayed in a thread list.
* Encapsulates the shared data between both SMS and MMS messages.
*
* @author Moxie Marlinspike
*
*/
public abstract class MessageRecord extends DisplayRecord {
public static final int DELIVERY_STATUS_NONE = 0;
public static final int DELIVERY_STATUS_RECEIVED = 1;
public static final int DELIVERY_STATUS_PENDING = 2;
public static final int DELIVERY_STATUS_FAILED = 3;
private static final int MAX_DISPLAY_LENGTH = 2000;
private final Recipient individualRecipient;
private final int recipientDeviceId;
private final long id;
private final int deliveryStatus;
private final int receiptCount;
private final List<IdentityKeyMismatch> mismatches;
private final List<NetworkFailure> networkFailures;
MessageRecord(Context context, long id, Body body, Recipients recipients,
Recipient individualRecipient, int recipientDeviceId,
long dateSent, long dateReceived, long threadId,
int deliveryStatus, int receiptCount, long type,
List<IdentityKeyMismatch> mismatches,
List<NetworkFailure> networkFailures)
{
super(context, body, recipients, dateSent, dateReceived, threadId, type);
this.id = id;
this.individualRecipient = individualRecipient;
this.recipientDeviceId = recipientDeviceId;
this.deliveryStatus = deliveryStatus;
this.receiptCount = receiptCount;
this.mismatches = mismatches;
this.networkFailures = networkFailures;
}
public abstract boolean isMms();
public abstract boolean isMmsNotification();
public boolean isFailed() {
return
MmsSmsColumns.Types.isFailedMessageType(type) ||
MmsSmsColumns.Types.isPendingSecureSmsFallbackType(type) ||
getDeliveryStatus() == DELIVERY_STATUS_FAILED;
}
public boolean isOutgoing() {
return MmsSmsColumns.Types.isOutgoingMessageType(type);
}
public boolean isPending() {
return MmsSmsColumns.Types.isPendingMessageType(type);
}
public boolean isSecure() {
return MmsSmsColumns.Types.isSecureType(type);
}
public boolean isLegacyMessage() {
return MmsSmsColumns.Types.isLegacyType(type);
}
public boolean isAsymmetricEncryption() {
return MmsSmsColumns.Types.isAsymmetricEncryption(type);
}
@Override
public SpannableString getDisplayBody() {
if (isGroupUpdate() && isOutgoing()) {
return emphasisAdded(context.getString(R.string.MessageRecord_updated_group));
} else if (isGroupUpdate()) {
return emphasisAdded(GroupUtil.getDescription(context, getBody().getBody()).toString());
} else if (isGroupQuit() && isOutgoing()) {
return emphasisAdded(context.getString(R.string.MessageRecord_left_group));
} else if (isGroupQuit()) {
return emphasisAdded(context.getString(R.string.ConversationItem_group_action_left, getIndividualRecipient().toShortString()));
} else if (isIncomingCall()) {
return emphasisAdded(context.getString(R.string.MessageRecord_s_called_you, getIndividualRecipient().toShortString()));
} else if (isOutgoingCall()) {
return emphasisAdded(context.getString(R.string.MessageRecord_called_s, getIndividualRecipient().toShortString()));
} else if (isMissedCall()) {
return emphasisAdded(context.getString(R.string.MessageRecord_missed_call_from, getIndividualRecipient().toShortString()));
} else if (isJoined()) {
return emphasisAdded(context.getString(R.string.MessageRecord_s_is_on_signal_say_hey, getIndividualRecipient().toShortString()));
} else if (getBody().getBody().length() > MAX_DISPLAY_LENGTH) {
return new SpannableString(getBody().getBody().substring(0, MAX_DISPLAY_LENGTH));
}
return new SpannableString(getBody().getBody());
}
public long getId() {
return id;
}
public int getDeliveryStatus() {
return deliveryStatus;
}
public boolean isDelivered() {
return getDeliveryStatus() == DELIVERY_STATUS_RECEIVED || receiptCount > 0;
}
public boolean isPush() {
return SmsDatabase.Types.isPushType(type) && !SmsDatabase.Types.isForcedSms(type);
}
public boolean isForcedSms() {
return SmsDatabase.Types.isForcedSms(type);
}
public boolean isStaleKeyExchange() {
return SmsDatabase.Types.isStaleKeyExchange(type);
}
public boolean isProcessedKeyExchange() {
return SmsDatabase.Types.isProcessedKeyExchange(type);
}
public boolean isPendingInsecureSmsFallback() {
return SmsDatabase.Types.isPendingInsecureSmsFallbackType(type);
}
public boolean isIdentityMismatchFailure() {
return mismatches != null && !mismatches.isEmpty();
}
public boolean isBundleKeyExchange() {
return SmsDatabase.Types.isBundleKeyExchange(type);
}
public boolean isIdentityUpdate() {
return SmsDatabase.Types.isIdentityUpdate(type);
}
public boolean isCorruptedKeyExchange() {
return SmsDatabase.Types.isCorruptedKeyExchange(type);
}
public boolean isInvalidVersionKeyExchange() {
return SmsDatabase.Types.isInvalidVersionKeyExchange(type);
}
public Recipient getIndividualRecipient() {
return individualRecipient;
}
public int getRecipientDeviceId() {
return recipientDeviceId;
}
public long getType() {
return type;
}
public List<IdentityKeyMismatch> getIdentityKeyMismatches() {
return mismatches;
}
public List<NetworkFailure> getNetworkFailures() {
return networkFailures;
}
public boolean hasNetworkFailures() {
return networkFailures != null && !networkFailures.isEmpty();
}
protected SpannableString emphasisAdded(String sequence) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new RelativeSizeSpan(0.9f), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, sequence.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
public boolean equals(Object other) {
return other != null &&
other instanceof MessageRecord &&
((MessageRecord) other).getId() == getId() &&
((MessageRecord) other).isMms() == isMms();
}
public int hashCode() {
return (int)getId();
}
}
| 7,984 | 33.868996 | 135 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/NotificationMmsMessageRecord.java | /**
* Copyright (C) 2012 Moxie Marlinspike
*
* 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.database.model;
import android.content.Context;
import android.text.SpannableString;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.util.LinkedList;
/**
* Represents the message record model for MMS messages that are
* notifications (ie: they're pointers to undownloaded media).
*
* @author Moxie Marlinspike
*
*/
public class NotificationMmsMessageRecord extends MessageRecord {
private final byte[] contentLocation;
private final long messageSize;
private final long expiry;
private final int status;
private final byte[] transactionId;
public NotificationMmsMessageRecord(Context context, long id, Recipients recipients,
Recipient individualRecipient, int recipientDeviceId,
long dateSent, long dateReceived, int receiptCount,
long threadId, byte[] contentLocation, long messageSize,
long expiry, int status, byte[] transactionId, long mailbox)
{
super(context, id, new Body("", true), recipients, individualRecipient, recipientDeviceId,
dateSent, dateReceived, threadId, DELIVERY_STATUS_NONE, receiptCount, mailbox,
new LinkedList<IdentityKeyMismatch>(), new LinkedList<NetworkFailure>());
this.contentLocation = contentLocation;
this.messageSize = messageSize;
this.expiry = expiry;
this.status = status;
this.transactionId = transactionId;
}
public byte[] getTransactionId() {
return transactionId;
}
public int getStatus() {
return this.status;
}
public byte[] getContentLocation() {
return contentLocation;
}
public long getMessageSize() {
return (messageSize + 1023) / 1024;
}
public long getExpiration() {
return expiry * 1000;
}
@Override
public boolean isOutgoing() {
return false;
}
@Override
public boolean isFailed() {
return MmsDatabase.Status.isHardError(status);
}
@Override
public boolean isSecure() {
return false;
}
@Override
public boolean isPending() {
return false;
}
@Override
public boolean isMms() {
return true;
}
@Override
public boolean isMmsNotification() {
return true;
}
@Override
public SpannableString getDisplayBody() {
return emphasisAdded(context.getString(R.string.NotificationMmsMessageRecord_multimedia_message));
}
}
| 3,477 | 28.226891 | 102 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/SmsMessageRecord.java | /**
* Copyright (C) 2012 Moxie Marlinspike
*
* 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.database.model;
import android.content.Context;
import android.text.SpannableString;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.MmsSmsColumns;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import java.util.LinkedList;
import java.util.List;
/**
* The message record model which represents standard SMS messages.
*
* @author Moxie Marlinspike
*
*/
public class SmsMessageRecord extends MessageRecord {
public SmsMessageRecord(Context context, long id,
Body body, Recipients recipients,
Recipient individualRecipient,
int recipientDeviceId,
long dateSent, long dateReceived,
int receiptCount,
long type, long threadId,
int status, List<IdentityKeyMismatch> mismatches)
{
super(context, id, body, recipients, individualRecipient, recipientDeviceId,
dateSent, dateReceived, threadId, getGenericDeliveryStatus(status), receiptCount, type,
mismatches, new LinkedList<NetworkFailure>());
}
public long getType() {
return type;
}
@Override
public SpannableString getDisplayBody() {
if (SmsDatabase.Types.isFailedDecryptType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_bad_encrypted_message));
} else if (isProcessedKeyExchange()) {
return new SpannableString("");
} else if (isStaleKeyExchange()) {
return emphasisAdded(context.getString(R.string.ConversationItem_error_received_stale_key_exchange_message));
} else if (isCorruptedKeyExchange()) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_received_corrupted_key_exchange_message));
} else if (isInvalidVersionKeyExchange()) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_received_key_exchange_message_for_invalid_protocol_version));
} else if (MmsSmsColumns.Types.isLegacyType(type)) {
return emphasisAdded(context.getString(R.string.MessageRecord_message_encrypted_with_a_legacy_protocol_version_that_is_no_longer_supported));
} else if (isBundleKeyExchange()) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_received_message_with_unknown_identity_key_click_to_process));
} else if (isIdentityUpdate()) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_received_updated_but_unknown_identity_information));
} else if (isKeyExchange() && isOutgoing()) {
return new SpannableString("");
} else if (isKeyExchange() && !isOutgoing()) {
return emphasisAdded(context.getString(R.string.ConversationItem_received_key_exchange_message_click_to_process));
} else if (SmsDatabase.Types.isDuplicateMessageType(type)) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_duplicate_message));
} else if (SmsDatabase.Types.isDecryptInProgressType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_decrypting_please_wait));
} else if (SmsDatabase.Types.isNoRemoteSessionType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_message_encrypted_for_non_existing_session));
} else if (!getBody().isPlaintext()) {
return emphasisAdded(context.getString(R.string.MessageNotifier_locked_message));
} else if (SmsDatabase.Types.isEndSessionType(type)) {
return emphasisAdded(context.getString(R.string.SmsMessageRecord_secure_session_reset));
} else {
return super.getDisplayBody();
}
}
@Override
public boolean isMms() {
return false;
}
@Override
public boolean isMmsNotification() {
return false;
}
private static int getGenericDeliveryStatus(int status) {
if (status == SmsDatabase.Status.STATUS_NONE) {
return MessageRecord.DELIVERY_STATUS_NONE;
} else if (status >= SmsDatabase.Status.STATUS_FAILED) {
return MessageRecord.DELIVERY_STATUS_FAILED;
} else if (status >= SmsDatabase.Status.STATUS_PENDING) {
return MessageRecord.DELIVERY_STATUS_PENDING;
} else {
return MessageRecord.DELIVERY_STATUS_RECEIVED;
}
}
}
| 5,232 | 42.608333 | 147 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/database/model/ThreadRecord.java | /**
* Copyright (C) 2012 Moxie Marlinspike
*
* 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.database.model;
import android.content.Context;
import android.net.Uri;
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 org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.database.MmsSmsColumns;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.GroupUtil;
/**
* The message record model which represents thread heading messages.
*
* @author Moxie Marlinspike
*
*/
public class ThreadRecord extends DisplayRecord {
private @NonNull final Context context;
private @Nullable final Uri snippetUri;
private final long count;
private final boolean read;
private final int distributionType;
public ThreadRecord(@NonNull Context context, @NonNull Body body, @Nullable Uri snippetUri,
@NonNull Recipients recipients, long date, long count, boolean read,
long threadId, long snippetType, int distributionType)
{
super(context, body, recipients, date, date, threadId, snippetType);
this.context = context.getApplicationContext();
this.snippetUri = snippetUri;
this.count = count;
this.read = read;
this.distributionType = distributionType;
}
public @Nullable Uri getSnippetUri() {
return snippetUri;
}
@Override
public SpannableString getDisplayBody() {
if (SmsDatabase.Types.isDecryptInProgressType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_decrypting_please_wait));
} else if (isGroupUpdate()) {
return emphasisAdded(GroupUtil.getDescription(context, getBody().getBody()).toString());
} else if (isGroupQuit()) {
return emphasisAdded(context.getString(R.string.ThreadRecord_left_the_group));
} else if (isKeyExchange()) {
return emphasisAdded(context.getString(R.string.ConversationListItem_key_exchange_message));
} else if (SmsDatabase.Types.isFailedDecryptType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_bad_encrypted_message));
} else if (SmsDatabase.Types.isNoRemoteSessionType(type)) {
return emphasisAdded(context.getString(R.string.MessageDisplayHelper_message_encrypted_for_non_existing_session));
} else if (!getBody().isPlaintext()) {
return emphasisAdded(context.getString(R.string.MessageNotifier_locked_message));
} else if (SmsDatabase.Types.isEndSessionType(type)) {
return emphasisAdded(context.getString(R.string.ThreadRecord_secure_session_reset));
} else if (MmsSmsColumns.Types.isLegacyType(type)) {
return emphasisAdded(context.getString(R.string.MessageRecord_message_encrypted_with_a_legacy_protocol_version_that_is_no_longer_supported));
} else if (MmsSmsColumns.Types.isDraftMessageType(type)) {
String draftText = context.getString(R.string.ThreadRecord_draft);
return emphasisAdded(draftText + " " + getBody().getBody(), 0, draftText.length());
} else if (SmsDatabase.Types.isOutgoingCall(type)) {
return emphasisAdded(context.getString(org.thoughtcrime.securesms.R.string.ThreadRecord_called));
} else if (SmsDatabase.Types.isIncomingCall(type)) {
return emphasisAdded(context.getString(org.thoughtcrime.securesms.R.string.ThreadRecord_called_you));
} else if (SmsDatabase.Types.isMissedCall(type)) {
return emphasisAdded(context.getString(org.thoughtcrime.securesms.R.string.ThreadRecord_missed_call));
} else if (SmsDatabase.Types.isJoinedType(type)) {
return emphasisAdded(context.getString(R.string.ThreadRecord_s_is_on_signal_say_hey, getRecipients().getPrimaryRecipient().toShortString()));
} else {
if (TextUtils.isEmpty(getBody().getBody())) {
return new SpannableString(emphasisAdded(context.getString(R.string.ThreadRecord_media_message)));
} else {
return new SpannableString(getBody().getBody());
}
}
}
private SpannableString emphasisAdded(String sequence) {
return emphasisAdded(sequence, 0, sequence.length());
}
private SpannableString emphasisAdded(String sequence, int start, int end) {
SpannableString spannable = new SpannableString(sequence);
spannable.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
public long getCount() {
return count;
}
public boolean isRead() {
return read;
}
public long getDate() {
return getDateReceived();
}
public int getDistributionType() {
return distributionType;
}
}
| 5,580 | 41.603053 | 147 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dependencies/AxolotlStorageModule.java | package org.thoughtcrime.securesms.dependencies;
import android.content.Context;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.storage.TextSecureAxolotlStore;
import org.thoughtcrime.securesms.jobs.CleanPreKeysJob;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import dagger.Module;
import dagger.Provides;
@Module (complete = false, injects = {CleanPreKeysJob.class})
public class AxolotlStorageModule {
private final Context context;
public AxolotlStorageModule(Context context) {
this.context = context;
}
@Provides SignedPreKeyStoreFactory provideSignedPreKeyStoreFactory() {
return new SignedPreKeyStoreFactory() {
@Override
public SignedPreKeyStore create() {
return new TextSecureAxolotlStore(context);
}
};
}
public static interface SignedPreKeyStoreFactory {
public SignedPreKeyStore create();
}
}
| 937 | 25.8 | 72 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dependencies/InjectableType.java | package org.thoughtcrime.securesms.dependencies;
public interface InjectableType {
}
| 86 | 16.4 | 48 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dependencies/RedPhoneCommunicationModule.java | package org.thoughtcrime.securesms.dependencies;
import android.content.Context;
import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager;
import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore;
import org.thoughtcrime.securesms.BuildConfig;
import org.thoughtcrime.securesms.jobs.GcmRefreshJob;
import org.thoughtcrime.securesms.jobs.RefreshAttributesJob;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import dagger.Module;
import dagger.Provides;
@Module(complete = false, injects = {GcmRefreshJob.class,
RefreshAttributesJob.class})
public class RedPhoneCommunicationModule {
private final Context context;
public RedPhoneCommunicationModule(Context context) {
this.context = context;
}
@Provides RedPhoneAccountManager provideRedPhoneAccountManager() {
return new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL,
new RedPhoneTrustStore(context),
TextSecurePreferences.getLocalNumber(context),
TextSecurePreferences.getPushServerPassword(context));
}
}
| 1,172 | 34.545455 | 92 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dependencies/TextSecureCommunicationModule.java | package org.thoughtcrime.securesms.dependencies;
import android.content.Context;
import org.thoughtcrime.securesms.BuildConfig;
import org.thoughtcrime.securesms.DeviceListActivity;
import org.thoughtcrime.securesms.crypto.storage.TextSecureAxolotlStore;
import org.thoughtcrime.securesms.jobs.AttachmentDownloadJob;
import org.thoughtcrime.securesms.jobs.CleanPreKeysJob;
import org.thoughtcrime.securesms.jobs.CreateSignedPreKeyJob;
import org.thoughtcrime.securesms.jobs.DeliveryReceiptJob;
import org.thoughtcrime.securesms.jobs.GcmRefreshJob;
import org.thoughtcrime.securesms.jobs.MultiDeviceContactUpdateJob;
import org.thoughtcrime.securesms.jobs.MultiDeviceGroupUpdateJob;
import org.thoughtcrime.securesms.jobs.PushGroupSendJob;
import org.thoughtcrime.securesms.jobs.PushMediaSendJob;
import org.thoughtcrime.securesms.jobs.PushNotificationReceiveJob;
import org.thoughtcrime.securesms.jobs.PushTextSendJob;
import org.thoughtcrime.securesms.jobs.RefreshAttributesJob;
import org.thoughtcrime.securesms.jobs.RefreshPreKeysJob;
import org.thoughtcrime.securesms.push.SecurityEventListener;
import org.thoughtcrime.securesms.push.TextSecurePushTrustStore;
import org.thoughtcrime.securesms.service.MessageRetrievalService;
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 org.whispersystems.textsecure.api.util.CredentialsProvider;
import dagger.Module;
import dagger.Provides;
@Module(complete = false, injects = {CleanPreKeysJob.class,
CreateSignedPreKeyJob.class,
DeliveryReceiptJob.class,
PushGroupSendJob.class,
PushTextSendJob.class,
PushMediaSendJob.class,
AttachmentDownloadJob.class,
RefreshPreKeysJob.class,
MessageRetrievalService.class,
PushNotificationReceiveJob.class,
MultiDeviceContactUpdateJob.class,
MultiDeviceGroupUpdateJob.class,
DeviceListActivity.DeviceListFragment.class,
RefreshAttributesJob.class,
GcmRefreshJob.class})
public class TextSecureCommunicationModule {
private final Context context;
public TextSecureCommunicationModule(Context context) {
this.context = context;
}
@Provides TextSecureAccountManager provideTextSecureAccountManager() {
return new TextSecureAccountManager(BuildConfig.TEXTSECURE_URL,
new TextSecurePushTrustStore(context),
TextSecurePreferences.getLocalNumber(context),
TextSecurePreferences.getPushServerPassword(context),
BuildConfig.USER_AGENT);
}
@Provides TextSecureMessageSenderFactory provideTextSecureMessageSenderFactory() {
return new TextSecureMessageSenderFactory() {
@Override
public TextSecureMessageSender create() {
return new TextSecureMessageSender(BuildConfig.TEXTSECURE_URL,
new TextSecurePushTrustStore(context),
TextSecurePreferences.getLocalNumber(context),
TextSecurePreferences.getPushServerPassword(context),
new TextSecureAxolotlStore(context),
BuildConfig.USER_AGENT,
Optional.<TextSecureMessageSender.EventListener>of(new SecurityEventListener(context)));
}
};
}
@Provides TextSecureMessageReceiver provideTextSecureMessageReceiver() {
return new TextSecureMessageReceiver(BuildConfig.TEXTSECURE_URL,
new TextSecurePushTrustStore(context),
new DynamicCredentialsProvider(context),
BuildConfig.USER_AGENT);
}
public static interface TextSecureMessageSenderFactory {
public TextSecureMessageSender create();
}
private static class DynamicCredentialsProvider implements CredentialsProvider {
private final Context context;
private DynamicCredentialsProvider(Context context) {
this.context = context.getApplicationContext();
}
@Override
public String getUser() {
return TextSecurePreferences.getLocalNumber(context);
}
@Override
public String getPassword() {
return TextSecurePreferences.getPushServerPassword(context);
}
@Override
public String getSignalingKey() {
return TextSecurePreferences.getSignalingKey(context);
}
}
}
| 5,220 | 44.008621 | 131 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/AttrImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.TypeInfo;
public class AttrImpl extends NodeImpl implements Attr {
private String mName;
private String mValue;
/*
* Internal methods
*/
protected AttrImpl(DocumentImpl owner, String name) {
super(owner);
mName = name;
}
/*
* Attr Interface Methods
*/
public String getName() {
return mName;
}
public Element getOwnerElement() {
// TODO Auto-generated method stub
return null;
}
public boolean getSpecified() {
return mValue != null;
}
public String getValue() {
return mValue;
}
// Instead of setting a <code>Text></code> with the content of the
// String value as defined in the specs, we directly set here the
// internal mValue member.
public void setValue(String value) throws DOMException {
mValue = value;
}
/*
* Node Interface Methods
*/
@Override
public String getNodeName() {
return mName;
}
@Override
public short getNodeType() {
return Node.ATTRIBUTE_NODE;
}
@Override
public Node getParentNode() {
return null;
}
@Override
public Node getPreviousSibling() {
return null;
}
@Override
public Node getNextSibling() {
return null;
}
@Override
public void setNodeValue(String nodeValue) throws DOMException {
setValue(nodeValue);
}
public TypeInfo getSchemaTypeInfo() {
return null;
}
public boolean isId() {
return false;
}
}
| 2,239 | 19.550459 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/DocumentImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
public abstract class DocumentImpl extends NodeImpl implements Document {
/*
* Internal methods
*/
public DocumentImpl() {
super(null);
}
/*
* Document Interface Methods
*/
public Attr createAttribute(String name) throws DOMException {
return new AttrImpl(this, name);
}
public Attr createAttributeNS(String namespaceURI, String qualifiedName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public CDATASection createCDATASection(String data) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Comment createComment(String data) {
// TODO Auto-generated method stub
return null;
}
public DocumentFragment createDocumentFragment() {
// TODO Auto-generated method stub
return null;
}
public abstract Element createElement(String tagName) throws DOMException;
public Element createElementNS(String namespaceURI, String qualifiedName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public EntityReference createEntityReference(String name) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public ProcessingInstruction createProcessingInstruction(String target, String data)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Text createTextNode(String data) {
// TODO Auto-generated method stub
return null;
}
public DocumentType getDoctype() {
// TODO Auto-generated method stub
return null;
}
public abstract Element getDocumentElement();
public Element getElementById(String elementId) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagName(String tagname) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public DOMImplementation getImplementation() {
// TODO Auto-generated method stub
return null;
}
public Node importNode(Node importedNode, boolean deep) throws DOMException {
// TODO Auto-generated method stub
return null;
}
/*
* Node Interface methods
*/
@Override
public short getNodeType() {
return Node.DOCUMENT_NODE;
}
@Override
public String getNodeName() {
// The value of nodeName is "#document" when Node is a Document
return "#document";
}
public String getInputEncoding() {
return null;
}
public String getXmlEncoding() {
return null;
}
public boolean getXmlStandalone() {
return false;
}
public void setXmlStandalone(boolean xmlStandalone) throws DOMException {}
public String getXmlVersion() {
return null;
}
public void setXmlVersion(String xmlVersion) throws DOMException {}
public boolean getStrictErrorChecking() {
return true;
}
public void setStrictErrorChecking(boolean strictErrorChecking) {}
public String getDocumentURI() {
return null;
}
public void setDocumentURI(String documentURI) {}
public Node adoptNode(Node source) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public DOMConfiguration getDomConfig() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void normalizeDocument() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Node renameNode(Node n, String namespaceURI, String qualifiedName)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
}
| 5,202 | 25.682051 | 88 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/ElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
public class ElementImpl extends NodeImpl implements Element {
private String mTagName;
private NamedNodeMap mAttributes = new NamedNodeMapImpl();
/*
* Internal methods
*/
protected ElementImpl(DocumentImpl owner, String tagName) {
super(owner);
mTagName = tagName;
}
/*
* Element Interface methods
*/
public String getAttribute(String name) {
Attr attrNode = getAttributeNode(name);
String attrValue = "";
if (attrNode != null) {
attrValue = attrNode.getValue();
}
return attrValue;
}
public String getAttributeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public Attr getAttributeNode(String name) {
return (Attr)mAttributes.getNamedItem(name);
}
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public NodeList getElementsByTagName(String name) {
return new NodeListImpl(this, name, true);
}
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public String getTagName() {
return mTagName;
}
public boolean hasAttribute(String name) {
return (getAttributeNode(name) != null);
}
public boolean hasAttributeNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return false;
}
public void removeAttribute(String name) throws DOMException {
// TODO Auto-generated method stub
}
public void removeAttributeNS(String namespaceURI, String localName)
throws DOMException {
// TODO Auto-generated method stub
}
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public void setAttribute(String name, String value) throws DOMException {
Attr attribute = getAttributeNode(name);
if (attribute == null) {
attribute = mOwnerDocument.createAttribute(name);
}
attribute.setNodeValue(value);
mAttributes.setNamedItem(attribute);
}
public void setAttributeNS(String namespaceURI, String qualifiedName,
String value) throws DOMException {
// TODO Auto-generated method stub
}
public Attr setAttributeNode(Attr newAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException {
// TODO Auto-generated method stub
return null;
}
/*
* Node Interface methods
*/
@Override
public short getNodeType() {
return ELEMENT_NODE;
}
@Override
public String getNodeName() {
// The value of nodeName is tagName when Node is an Element
return mTagName;
}
@Override
public NamedNodeMap getAttributes() {
return mAttributes;
}
@Override
public boolean hasAttributes() {
return (mAttributes.getLength() > 0);
}
public TypeInfo getSchemaTypeInfo() {
return null;
}
public void setIdAttribute(String name, boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setIdAttributeNS(String namespaceURI, String localName,
boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setIdAttributeNode(Attr idAttr, boolean isId)
throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
}
| 4,738 | 26.393064 | 83 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/NamedNodeMapImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import java.util.Vector;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public class NamedNodeMapImpl implements NamedNodeMap {
private Vector<Node> mNodes = new Vector<Node>();
public int getLength() {
return mNodes.size();
}
public Node getNamedItem(String name) {
Node node = null;
for (int i = 0; i < mNodes.size(); i++) {
if (name.equals(mNodes.elementAt(i).getNodeName())) {
node = mNodes.elementAt(i);
break;
}
}
return node;
}
public Node getNamedItemNS(String namespaceURI, String localName) {
// TODO Auto-generated method stub
return null;
}
public Node item(int index) {
if (index < mNodes.size()) {
return mNodes.elementAt(index);
}
return null;
}
public Node removeNamedItem(String name) throws DOMException {
Node node = getNamedItem(name);
if (node == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Not found");
} else {
mNodes.remove(node);
}
return node;
}
public Node removeNamedItemNS(String namespaceURI, String localName)
throws DOMException {
// TODO Auto-generated method stub
return null;
}
public Node setNamedItem(Node arg) throws DOMException {
Node existing = getNamedItem(arg.getNodeName());
if (existing != null) {
mNodes.remove(existing);
}
mNodes.add(arg);
return existing;
}
public Node setNamedItemNS(Node arg) throws DOMException {
// TODO Auto-generated method stub
return null;
}
}
| 2,462 | 26.988636 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/NodeImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import java.util.NoSuchElementException;
import java.util.Vector;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.thoughtcrime.securesms.dom.events.EventTargetImpl;
public abstract class NodeImpl implements Node, EventTarget {
private Node mParentNode;
private final Vector<Node> mChildNodes = new Vector<Node>();
DocumentImpl mOwnerDocument;
private final EventTarget mEventTarget = new EventTargetImpl(this);
/*
* Internal methods
*/
protected NodeImpl(DocumentImpl owner) {
mOwnerDocument = owner;
}
/*
* Node Interface Methods
*/
public Node appendChild(Node newChild) throws DOMException {
((NodeImpl)newChild).setParentNode(this);
mChildNodes.remove(newChild);
mChildNodes.add(newChild);
return newChild;
}
public Node cloneNode(boolean deep) {
// TODO Auto-generated method stub
return null;
}
public NamedNodeMap getAttributes() {
// Default. Override in Element.
return null;
}
public NodeList getChildNodes() {
return new NodeListImpl(this, null, false);
}
public Node getFirstChild() {
Node firstChild = null;
try {
firstChild = mChildNodes.firstElement();
}
catch (NoSuchElementException e) {
// Ignore and return null
}
return firstChild;
}
public Node getLastChild() {
Node lastChild = null;
try {
lastChild = mChildNodes.lastElement();
}
catch (NoSuchElementException e) {
// Ignore and return null
}
return lastChild;
}
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
public String getNamespaceURI() {
// TODO Auto-generated method stub
return null;
}
public Node getNextSibling() {
if ((mParentNode != null) && (this != mParentNode.getLastChild())) {
Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes;
int indexOfThis = siblings.indexOf(this);
return siblings.elementAt(indexOfThis + 1);
}
return null;
}
public abstract String getNodeName();
public abstract short getNodeType();
public String getNodeValue() throws DOMException {
// Default behaviour. Override if required.
return null;
}
public Document getOwnerDocument() {
return mOwnerDocument;
}
public Node getParentNode() {
return mParentNode;
}
public String getPrefix() {
// TODO Auto-generated method stub
return null;
}
public Node getPreviousSibling() {
if ((mParentNode != null) && (this != mParentNode.getFirstChild())) {
Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes;
int indexOfThis = siblings.indexOf(this);
return siblings.elementAt(indexOfThis - 1);
}
return null;
}
public boolean hasAttributes() {
// Default. Override in Element.
return false;
}
public boolean hasChildNodes() {
return !(mChildNodes.isEmpty());
}
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
// TODO Auto-generated method stub
return null;
}
public boolean isSupported(String feature, String version) {
// TODO Auto-generated method stub
return false;
}
public void normalize() {
// TODO Auto-generated method stub
}
public Node removeChild(Node oldChild) throws DOMException {
if (mChildNodes.contains(oldChild)) {
mChildNodes.remove(oldChild);
((NodeImpl)oldChild).setParentNode(null);
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Child does not exist");
}
return null;
}
public Node replaceChild(Node newChild, Node oldChild) throws DOMException {
if (mChildNodes.contains(oldChild)) {
// Try to remove the new child if available
try {
mChildNodes.remove(newChild);
} catch (DOMException e) {
// Ignore exception
}
mChildNodes.setElementAt(newChild, mChildNodes.indexOf(oldChild));
((NodeImpl)newChild).setParentNode(this);
((NodeImpl)oldChild).setParentNode(null);
} else {
throw new DOMException(DOMException.NOT_FOUND_ERR, "Old child does not exist");
}
return oldChild;
}
public void setNodeValue(String nodeValue) throws DOMException {
// Default behaviour. Override if required.
}
public void setPrefix(String prefix) throws DOMException {
// TODO Auto-generated method stub
}
private void setParentNode(Node parentNode) {
mParentNode = parentNode;
}
/*
* EventTarget Interface
*/
public void addEventListener(String type, EventListener listener, boolean useCapture) {
mEventTarget.addEventListener(type, listener, useCapture);
}
public void removeEventListener(String type, EventListener listener, boolean useCapture) {
mEventTarget.removeEventListener(type, listener, useCapture);
}
public boolean dispatchEvent(Event evt) throws EventException {
return mEventTarget.dispatchEvent(evt);
}
public String getBaseURI() {
return null;
}
public short compareDocumentPosition(Node other) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String getTextContent() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public void setTextContent(String textContent) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public boolean isSameNode(Node other) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String lookupPrefix(String namespaceURI) {
return null;
}
public boolean isDefaultNamespace(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public String lookupNamespaceURI(String prefix) {
return null;
}
public boolean isEqualNode(Node arg) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Object getFeature(String feature, String version) {
return null;
}
public Object setUserData(String key, Object data,
UserDataHandler handler) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null);
}
public Object getUserData(String key) {
return null;
}
}
| 7,828 | 27.572993 | 94 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/NodeListImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom;
import java.util.ArrayList;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NodeListImpl implements NodeList {
private ArrayList<Node> mSearchNodes;
private ArrayList<Node> mStaticNodes;
private Node mRootNode;
private String mTagName;
private boolean mDeepSearch;
/*
* Internal Interface
*/
/**
* Constructs a NodeList by searching for all descendants or the direct
* children of a root node with a given tag name.
* @param rootNode The root <code>Node</code> of the search.
* @param tagName The tag name to be searched for. If null, all descendants
* will be returned.
* @param deep Limit the search to the direct children of rootNode if false,
* to all descendants otherwise.
*/
public NodeListImpl(Node rootNode, String tagName, boolean deepSearch) {
mRootNode = rootNode;
mTagName = tagName;
mDeepSearch = deepSearch;
}
/**
* Constructs a NodeList for a given static node list.
* @param nodes The static node list.
*/
public NodeListImpl(ArrayList<Node> nodes) {
mStaticNodes = nodes;
}
/*
* NodeListImpl Interface
*/
public int getLength() {
if (mStaticNodes == null) {
fillList(mRootNode);
return mSearchNodes.size();
} else {
return mStaticNodes.size();
}
}
public Node item(int index) {
Node node = null;
if (mStaticNodes == null) {
fillList(mRootNode);
try {
node = mSearchNodes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
} else {
try {
node = mStaticNodes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
}
return node;
}
/**
* A preorder traversal is done in the following order:
* <ul>
* <li> Visit root.
* <li> Traverse children from left to right in preorder.
* </ul>
* This method fills the live node list.
* @param The root of preorder traversal
* @return The next match
*/
private void fillList(Node node) {
// (Re)-initialize the container if this is the start of the search.
// Visit the root of this iteration otherwise.
if (node == mRootNode) {
mSearchNodes = new ArrayList<Node>();
} else {
if ((mTagName == null) || node.getNodeName().equals(mTagName)) {
mSearchNodes.add(node);
}
}
// Descend one generation...
node = node.getFirstChild();
// ...and visit in preorder the children if we are in deep search
// or directly add the children to the list otherwise.
while (node != null) {
if (mDeepSearch) {
fillList(node);
} else {
if ((mTagName == null) || node.getNodeName().equals(mTagName)) {
mSearchNodes.add(node);
}
}
node = node.getNextSibling();
}
}
}
| 3,952 | 29.643411 | 80 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/events/EventImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.events;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
public class EventImpl implements Event {
// Event type informations
private String mEventType;
private boolean mCanBubble;
private boolean mCancelable;
// Flags whether the event type information was set
// FIXME: Can we use mEventType for this purpose?
private boolean mInitialized;
// Target of this event
private EventTarget mTarget;
// Event status variables
private short mEventPhase;
private boolean mStopPropagation;
private boolean mPreventDefault;
private EventTarget mCurrentTarget;
private int mSeekTo;
private final long mTimeStamp = System.currentTimeMillis();
public boolean getBubbles() {
return mCanBubble;
}
public boolean getCancelable() {
return mCancelable;
}
public EventTarget getCurrentTarget() {
return mCurrentTarget;
}
public short getEventPhase() {
return mEventPhase;
}
public EventTarget getTarget() {
return mTarget;
}
public long getTimeStamp() {
return mTimeStamp;
}
public String getType() {
return mEventType;
}
public void initEvent(String eventTypeArg, boolean canBubbleArg,
boolean cancelableArg) {
mEventType = eventTypeArg;
mCanBubble = canBubbleArg;
mCancelable = cancelableArg;
mInitialized = true;
}
public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg,
int seekTo) {
mSeekTo = seekTo;
initEvent(eventTypeArg, canBubbleArg, cancelableArg);
}
public void preventDefault() {
mPreventDefault = true;
}
public void stopPropagation() {
mStopPropagation = true;
}
/*
* Internal Interface
*/
boolean isInitialized() {
return mInitialized;
}
boolean isPreventDefault() {
return mPreventDefault;
}
boolean isPropogationStopped() {
return mStopPropagation;
}
void setTarget(EventTarget target) {
mTarget = target;
}
void setEventPhase(short eventPhase) {
mEventPhase = eventPhase;
}
void setCurrentTarget(EventTarget currentTarget) {
mCurrentTarget = currentTarget;
}
public int getSeekTo() {
return mSeekTo;
}
}
| 3,103 | 23.25 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/events/EventTargetImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.events;
import java.util.ArrayList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventException;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import android.util.Log;
public class EventTargetImpl implements EventTarget {
private static final String TAG = "EventTargetImpl";
private ArrayList<EventListenerEntry> mListenerEntries;
private EventTarget mNodeTarget;
static class EventListenerEntry
{
final String mType;
final EventListener mListener;
final boolean mUseCapture;
EventListenerEntry(String type, EventListener listener, boolean useCapture)
{
mType = type;
mListener = listener;
mUseCapture = useCapture;
}
}
public EventTargetImpl(EventTarget target) {
mNodeTarget = target;
}
public void addEventListener(String type, EventListener listener, boolean useCapture) {
if ((type == null) || type.equals("") || (listener == null)) {
return;
}
// Make sure we have only one entry
removeEventListener(type, listener, useCapture);
if (mListenerEntries == null) {
mListenerEntries = new ArrayList<EventListenerEntry>();
}
mListenerEntries.add(new EventListenerEntry(type, listener, useCapture));
}
public boolean dispatchEvent(Event evt) throws EventException {
// We need to use the internal APIs to modify and access the event status
EventImpl eventImpl = (EventImpl)evt;
if (!eventImpl.isInitialized()) {
throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
"Event not initialized");
} else if ((eventImpl.getType() == null) || eventImpl.getType().equals("")) {
throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR,
"Unspecified even type");
}
// Initialize event status
eventImpl.setTarget(mNodeTarget);
// TODO: At this point, to support event capturing and bubbling, we should
// establish the chain of EventTargets from the top of the tree to this
// event's target.
// TODO: CAPTURING_PHASE skipped
// Handle AT_TARGET
// Invoke handleEvent of non-capturing listeners on this EventTarget.
eventImpl.setEventPhase(Event.AT_TARGET);
eventImpl.setCurrentTarget(mNodeTarget);
if (!eventImpl.isPropogationStopped() && (mListenerEntries != null)) {
for (int i = 0; i < mListenerEntries.size(); i++) {
EventListenerEntry listenerEntry = mListenerEntries.get(i);
if (!listenerEntry.mUseCapture
&& listenerEntry.mType.equals(eventImpl.getType())) {
try {
listenerEntry.mListener.handleEvent(eventImpl);
}
catch (Exception e) {
// Any exceptions thrown inside an EventListener will
// not stop propagation of the event
Log.w(TAG, "Catched EventListener exception", e);
}
}
}
}
if (eventImpl.getBubbles()) {
// TODO: BUBBLING_PHASE skipped
}
return eventImpl.isPreventDefault();
}
public void removeEventListener(String type, EventListener listener,
boolean useCapture) {
if (null == mListenerEntries) {
return;
}
for (int i = 0; i < mListenerEntries.size(); i ++) {
EventListenerEntry listenerEntry = mListenerEntries.get(i);
if ((listenerEntry.mUseCapture == useCapture)
&& (listenerEntry.mListener == listener)
&& listenerEntry.mType.equals(type)) {
mListenerEntries.remove(i);
break;
}
}
}
}
| 4,688 | 34.522727 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/ElementParallelTimeContainerImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import org.thoughtcrime.securesms.dom.NodeListImpl;
public abstract class ElementParallelTimeContainerImpl extends ElementTimeContainerImpl
implements ElementParallelTimeContainer {
private final static String ENDSYNC_ATTRIBUTE_NAME = "endsync";
private final static String ENDSYNC_FIRST = "first";
private final static String ENDSYNC_LAST = "last";
private final static String ENDSYNC_ALL = "all";
private final static String ENDSYNC_MEDIA = "media";
/*
* Internal Interface
*/
ElementParallelTimeContainerImpl(SMILElement element) {
super(element);
}
public String getEndSync() {
String endsync = mSmilElement.getAttribute(ENDSYNC_ATTRIBUTE_NAME);
if ((endsync == null) || (endsync.length() == 0)) {
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
if (ENDSYNC_FIRST.equals(endsync) || ENDSYNC_LAST.equals(endsync) ||
ENDSYNC_ALL.equals(endsync) || ENDSYNC_MEDIA.equals(endsync)) {
return endsync;
}
// FIXME add the checking for ID-Value and smil1.0-Id-value.
setEndSync(ENDSYNC_LAST);
return ENDSYNC_LAST;
}
public void setEndSync(String endSync) throws DOMException {
if (ENDSYNC_FIRST.equals(endSync) || ENDSYNC_LAST.equals(endSync) ||
ENDSYNC_ALL.equals(endSync) || ENDSYNC_MEDIA.equals(endSync)) {
mSmilElement.setAttribute(ENDSYNC_ATTRIBUTE_NAME, endSync);
} else { // FIXME add the support for ID-Value and smil1.0-Id-value.
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Unsupported endsync value" + endSync);
}
}
@Override
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
dur = getImplicitDuration();
}
return dur;
}
public float getImplicitDuration() {
float dur = -1.0F;
if (ENDSYNC_LAST.equals(getEndSync())) {
NodeList children = getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
TimeList endTimeList = child.getEnd();
for (int j = 0; j < endTimeList.getLength(); ++j) {
Time endTime = endTimeList.item(j);
if (endTime.getTimeType() == Time.SMIL_TIME_INDEFINITE) {
// Return "indefinite" here.
return -1.0F;
}
if (endTime.getResolved()) {
float end = (float)endTime.getResolvedOffset();
dur = (end > dur) ? end : dur;
}
}
}
} // Other endsync types are not supported now.
return dur;
}
public NodeList getActiveChildrenAt(float instant) {
/*
* Find the closest Time of ElementTime before instant.
* Add ElementTime to list of active elements if the Time belongs to the begin-list,
* do not add it otherwise.
*/
ArrayList<Node> activeChildren = new ArrayList<Node>();
NodeList children = getTimeChildren();
int childrenLen = children.getLength();
for (int i = 0; i < childrenLen; ++i) {
double maxOffset = 0.0;
boolean active = false;
ElementTime child = (ElementTime) children.item(i);
TimeList beginList = child.getBegin();
int len = beginList.getLength();
for (int j = 0; j < len; ++j) {
Time begin = beginList.item(j);
if (begin.getResolved()) {
double resolvedOffset = begin.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = true;
}
}
}
TimeList endList = child.getEnd();
len = endList.getLength();
for (int j = 0; j < len; ++j) {
Time end = endList.item(j);
if (end.getResolved()) {
double resolvedOffset = end.getResolvedOffset() * 1000.0;
if ((resolvedOffset <= instant) && (resolvedOffset >= maxOffset)) {
maxOffset = resolvedOffset;
active = false;
}
}
}
if (active) {
activeChildren.add((Node) child);
}
}
return new NodeListImpl(activeChildren);
}
}
| 5,748 | 35.852564 | 92 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/ElementSequentialTimeContainerImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.thoughtcrime.securesms.dom.NodeListImpl;
public abstract class ElementSequentialTimeContainerImpl extends
ElementTimeContainerImpl implements ElementSequentialTimeContainer {
/*
* Internal Interface
*/
ElementSequentialTimeContainerImpl(SMILElement element) {
super(element);
}
/*
* ElementSequentialTimeContainer Interface
*/
public NodeList getActiveChildrenAt(float instant) {
NodeList allChildren = this.getTimeChildren();
ArrayList<Node> nodes = new ArrayList<Node>();
for (int i = 0; i < allChildren.getLength(); i++) {
instant -= ((ElementTime) allChildren.item(i)).getDur();
if (instant < 0) {
nodes.add(allChildren.item(i));
return new NodeListImpl(nodes);
}
}
return new NodeListImpl(nodes);
}
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
NodeList children = getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
if (child.getDur() < 0) {
// Return "indefinite" since containing a child whose duration is indefinite.
return -1.0F;
}
dur += child.getDur();
}
}
return dur;
}
}
| 2,356 | 30.851351 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/ElementTimeContainerImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.smil.ElementTimeContainer;
import org.w3c.dom.smil.SMILElement;
public abstract class ElementTimeContainerImpl extends ElementTimeImpl implements
ElementTimeContainer {
/*
* Internal Interface
*/
ElementTimeContainerImpl(SMILElement element) {
super(element);
}
}
| 1,026 | 29.205882 | 81 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/ElementTimeImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import android.util.Log;
public abstract class ElementTimeImpl implements ElementTime {
private static final String TAG = "ElementTimeImpl";
private static final String FILL_REMOVE_ATTRIBUTE = "remove";
private static final String FILL_FREEZE_ATTRIBUTE = "freeze";
private static final String FILL_HOLD_ATTRIBUTE = "hold";
private static final String FILL_TRANSITION_ATTRIBUTE = "transition";
private static final String FILL_AUTO_ATTRIBUTE = "auto";
private static final String FILL_ATTRIBUTE_NAME = "fill";
private static final String FILLDEFAULT_ATTRIBUTE_NAME = "fillDefault";
final SMILElement mSmilElement;
/*
* Internal Interface
*/
ElementTimeImpl(SMILElement element) {
mSmilElement = element;
}
// Default implementation. Override if required.
int getBeginConstraints() {
return TimeImpl.ALLOW_ALL;
}
// Default implementation. Override if required
int getEndConstraints() {
return TimeImpl.ALLOW_ALL;
}
/**
* To get the parent node on the ElementTime tree. It is in opposition to getTimeChildren.
* @return the parent ElementTime. Returns <code>null</code> if there is no parent.
*/
abstract ElementTime getParentElementTime();
/*
* ElementTime Interface
*/
public TimeList getBegin() {
String[] beginTimeStringList = mSmilElement.getAttribute("begin").split(";");
// TODO: Check other constraints on parsed values, e.g., "single, non-negative offset values
ArrayList<Time> beginTimeList = new ArrayList<Time>();
// Initialize Time instances and add them to Vector
for (int i = 0; i < beginTimeStringList.length; i++) {
try {
beginTimeList.add(new TimeImpl(beginTimeStringList[i], getBeginConstraints()));
} catch (IllegalArgumentException e) {
// Ignore badly formatted times
}
}
if (beginTimeList.size() == 0) {
/*
* What is the right default value?
*
* In MMS SMIL, this method may be called either on an instance of:
*
* 1 - ElementSequentialTimeContainer (The SMILDocument)
* 2 - ElementParallelTimeContainer (A Time-Child of the SMILDocument, which is a seq)
* 3 - ElementTime (A SMILMediaElement).
*
* 1 - In the first case, the default start time is obviously 0.
* 2 - In the second case, the specifications mentions that
* "For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value. The default begin value is 0."
* 3 - In the third case, the specification mentions that
* "The default value of begin for children of a par is 0."
*
* In short, if no value is specified, the default is always 0.
*/
beginTimeList.add(new TimeImpl("0", TimeImpl.ALLOW_ALL));
}
return new TimeListImpl(beginTimeList);
}
public float getDur() {
float dur = 0;
try {
String durString = mSmilElement.getAttribute("dur");
if (durString != null) {
dur = TimeImpl.parseClockValue(durString) / 1000f;
}
} catch (IllegalArgumentException e) {
// Do nothing and return the minimum value
}
return dur;
}
public TimeList getEnd() {
ArrayList<Time> endTimeList = new ArrayList<Time>();
String[] endTimeStringList = mSmilElement.getAttribute("end").split(";");
int len = endTimeStringList.length;
if (!((len == 1) && (endTimeStringList[0].length() == 0))) { // Ensure the end field is set.
// Initialize Time instances and add them to Vector
for (int i = 0; i < len; i++) {
try {
endTimeList.add(new TimeImpl(endTimeStringList[i],
getEndConstraints()));
} catch (IllegalArgumentException e) {
// Ignore badly formatted times
Log.e(TAG, "Malformed time value.", e);
}
}
}
// "end" time is not specified
if (endTimeList.size() == 0) {
// Get duration
float duration = getDur();
if (duration < 0) {
endTimeList.add(new TimeImpl("indefinite", getEndConstraints()));
} else {
// Get begin
TimeList begin = getBegin();
for (int i = 0; i < begin.getLength(); i++) {
endTimeList.add(new TimeImpl(
// end = begin + dur
begin.item(i).getResolvedOffset() + duration + "s",
getEndConstraints()));
}
}
}
return new TimeListImpl(endTimeList);
}
private boolean beginAndEndAreZero() {
TimeList begin = getBegin();
TimeList end = getEnd();
if (begin.getLength() == 1 && end.getLength() == 1) {
Time beginTime = begin.item(0);
Time endTime = end.item(0);
return beginTime.getOffset() == 0. && endTime.getOffset() == 0.;
}
return false;
}
public short getFill() {
String fill = mSmilElement.getAttribute(FILL_ATTRIBUTE_NAME);
if (fill.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) {
return FILL_FREEZE;
} else if (fill.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) {
return FILL_REMOVE;
} else if (fill.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (fill.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (!fill.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) {
/*
* fill = default
* The fill behavior for the element is determined by the value of the fillDefault
* attribute. This is the default value.
*/
short fillDefault = getFillDefault();
if (fillDefault != FILL_AUTO) {
return fillDefault;
}
}
/*
* fill = auto
* The fill behavior for this element depends on whether the element specifies any of
* the attributes that define the simple or active duration:
* - If none of the attributes dur, end, repeatCount or repeatDur are specified on
* the element, then the element will have a fill behavior identical to that if it were
* specified as "freeze".
* - Otherwise, the element will have a fill behavior identical to that if it were
* specified as "remove".
*/
if (((mSmilElement.getAttribute("dur").length() == 0) &&
(mSmilElement.getAttribute("end").length() == 0) &&
(mSmilElement.getAttribute("repeatCount").length() == 0) &&
(mSmilElement.getAttribute("repeatDur").length() == 0)) ||
beginAndEndAreZero()) {
return FILL_FREEZE;
} else {
return FILL_REMOVE;
}
}
public short getFillDefault() {
String fillDefault = mSmilElement.getAttribute(FILLDEFAULT_ATTRIBUTE_NAME);
if (fillDefault.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) {
return FILL_REMOVE;
} else if (fillDefault.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) {
return FILL_FREEZE;
} else if (fillDefault.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) {
return FILL_AUTO;
} else if (fillDefault.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else if (fillDefault.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) {
// FIXME handle it as freeze for now
return FILL_FREEZE;
} else {
/*
* fillDefault = inherit
* Specifies that the value of this attribute (and of the fill behavior) are
* inherited from the fillDefault value of the parent element.
* This is the default value.
*/
ElementTime parent = getParentElementTime();
if (parent == null) {
/*
* fillDefault = auto
* If there is no parent element, the value is "auto".
*/
return FILL_AUTO;
} else {
return ((ElementTimeImpl) parent).getFillDefault();
}
}
}
public float getRepeatCount() {
String repeatCount = mSmilElement.getAttribute("repeatCount");
try {
float value = Float.parseFloat(repeatCount);
if (value > 0) {
return value;
} else {
return 0; // default
}
} catch (NumberFormatException e) {
return 0; // default
}
}
public float getRepeatDur() {
try {
float repeatDur =
TimeImpl.parseClockValue(mSmilElement.getAttribute("repeatDur"));
if (repeatDur > 0) {
return repeatDur;
} else {
return 0; // default
}
} catch (IllegalArgumentException e) {
return 0; // default
}
}
public short getRestart() {
String restart = mSmilElement.getAttribute("restart");
if (restart.equalsIgnoreCase("never")) {
return RESTART_NEVER;
} else if (restart.equalsIgnoreCase("whenNotActive")) {
return RESTART_WHEN_NOT_ACTIVE;
} else {
return RESTART_ALWAYS; // default
}
}
public void setBegin(TimeList begin) throws DOMException {
// TODO Implement this
mSmilElement.setAttribute("begin", "indefinite");
}
public void setDur(float dur) throws DOMException {
// In SMIL 3.0, the dur could be a timecount-value which may contain fractions.
// However, in MMS 1.3, the dur SHALL be expressed in integer milliseconds.
mSmilElement.setAttribute("dur", Integer.toString((int)(dur * 1000)) + "ms");
}
public void setEnd(TimeList end) throws DOMException {
// TODO Implement this
mSmilElement.setAttribute("end", "indefinite");
}
public void setFill(short fill) throws DOMException {
if (fill == FILL_FREEZE) {
mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE);
} else {
mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE); // default
}
}
public void setFillDefault(short fillDefault) throws DOMException {
if (fillDefault == FILL_FREEZE) {
mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE);
} else {
mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE);
}
}
public void setRepeatCount(float repeatCount) throws DOMException {
String repeatCountString = "indefinite";
if (repeatCount > 0) {
repeatCountString = Float.toString(repeatCount);
}
mSmilElement.setAttribute("repeatCount", repeatCountString);
}
public void setRepeatDur(float repeatDur) throws DOMException {
String repeatDurString = "indefinite";
if (repeatDur > 0) {
repeatDurString = Float.toString(repeatDur) + "ms";
}
mSmilElement.setAttribute("repeatDur", repeatDurString);
}
public void setRestart(short restart) throws DOMException {
if (restart == RESTART_NEVER) {
mSmilElement.setAttribute("restart", "never");
} else if (restart == RESTART_WHEN_NOT_ACTIVE) {
mSmilElement.setAttribute("restart", "whenNotActive");
} else {
mSmilElement.setAttribute("restart", "always");
}
}
}
| 13,165 | 36.724928 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilDocumentImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.TimeList;
import org.thoughtcrime.securesms.dom.DocumentImpl;
import org.thoughtcrime.securesms.dom.events.EventImpl;
public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent {
/*
* The sequential time container cannot be initialized here because the real container
* is body, which hasn't been created yet. It will be initialized when the body has
* already been created. Please see getBody().
*/
ElementSequentialTimeContainer mSeqTimeContainer;
public final static String SMIL_DOCUMENT_START_EVENT = "SmilDocumentStart";
public final static String SMIL_DOCUMENT_END_EVENT = "SimlDocumentEnd";
/*
* Internal methods
*/
public SmilDocumentImpl() {
super();
}
/*
* ElementSequentialTimeContainer stuff
*/
public NodeList getActiveChildrenAt(float instant) {
return mSeqTimeContainer.getActiveChildrenAt(instant);
}
public NodeList getTimeChildren() {
return mSeqTimeContainer.getTimeChildren();
}
public boolean beginElement() {
return mSeqTimeContainer.beginElement();
}
public boolean endElement() {
return mSeqTimeContainer.endElement();
}
public TimeList getBegin() {
return mSeqTimeContainer.getBegin();
}
public float getDur() {
return mSeqTimeContainer.getDur();
}
public TimeList getEnd() {
return mSeqTimeContainer.getEnd();
}
public short getFill() {
return mSeqTimeContainer.getFill();
}
public short getFillDefault() {
return mSeqTimeContainer.getFillDefault();
}
public float getRepeatCount() {
return mSeqTimeContainer.getRepeatCount();
}
public float getRepeatDur() {
return mSeqTimeContainer.getRepeatDur();
}
public short getRestart() {
return mSeqTimeContainer.getRestart();
}
public void pauseElement() {
mSeqTimeContainer.pauseElement();
}
public void resumeElement() {
mSeqTimeContainer.resumeElement();
}
public void seekElement(float seekTo) {
mSeqTimeContainer.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mSeqTimeContainer.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mSeqTimeContainer.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mSeqTimeContainer.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mSeqTimeContainer.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mSeqTimeContainer.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mSeqTimeContainer.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mSeqTimeContainer.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mSeqTimeContainer.setRestart(restart);
}
/*
* Document Interface
*/
@Override
public Element createElement(String tagName) throws DOMException {
// Find the appropriate class for this element
tagName = tagName.toLowerCase();
if (tagName.equals("text") ||
tagName.equals("img") ||
tagName.equals("video")) {
return new SmilRegionMediaElementImpl(this, tagName);
} else if (tagName.equals("audio")) {
return new SmilMediaElementImpl(this, tagName);
} else if (tagName.equals("layout")) {
return new SmilLayoutElementImpl(this, tagName);
} else if (tagName.equals("root-layout")) {
return new SmilRootLayoutElementImpl(this, tagName);
} else if (tagName.equals("region")) {
return new SmilRegionElementImpl(this, tagName);
} else if (tagName.equals("ref")) {
return new SmilRefElementImpl(this, tagName);
} else if (tagName.equals("par")) {
return new SmilParElementImpl(this, tagName);
} else {
// This includes also the structural nodes SMIL,
// HEAD, BODY, for which no specific types are defined.
return new SmilElementImpl(this, tagName);
}
}
@Override
public SMILElement getDocumentElement() {
Node rootElement = getFirstChild();
if (rootElement == null || !(rootElement instanceof SMILElement)) {
// The root doesn't exist. Create a new one.
rootElement = createElement("smil");
appendChild(rootElement);
}
return (SMILElement) rootElement;
}
/*
* SMILElement Interface
*/
public SMILElement getHead() {
Node rootElement = getDocumentElement();
Node headElement = rootElement.getFirstChild();
if (headElement == null || !(headElement instanceof SMILElement)) {
// The head doesn't exist. Create a new one.
headElement = createElement("head");
rootElement.appendChild(headElement);
}
return (SMILElement) headElement;
}
public SMILElement getBody() {
Node rootElement = getDocumentElement();
Node headElement = getHead();
Node bodyElement = headElement.getNextSibling();
if (bodyElement == null || !(bodyElement instanceof SMILElement)) {
// The body doesn't exist. Create a new one.
bodyElement = createElement("body");
rootElement.appendChild(bodyElement);
}
// Initialize the real sequential time container, which is body.
mSeqTimeContainer = new ElementSequentialTimeContainerImpl((SMILElement) bodyElement) {
public NodeList getTimeChildren() {
return getBody().getElementsByTagName("par");
}
public boolean beginElement() {
Event startEvent = createEvent("Event");
startEvent.initEvent(SMIL_DOCUMENT_START_EVENT, false, false);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
Event endEvent = createEvent("Event");
endEvent.initEvent(SMIL_DOCUMENT_END_EVENT, false, false);
dispatchEvent(endEvent);
return true;
}
public void pauseElement() {
// TODO Auto-generated method stub
}
public void resumeElement() {
// TODO Auto-generated method stub
}
public void seekElement(float seekTo) {
// TODO Auto-generated method stub
}
ElementTime getParentElementTime() {
return null;
}
};
return (SMILElement) bodyElement;
}
public SMILLayoutElement getLayout() {
Node headElement = getHead();
Node layoutElement = null;
// Find the layout element under <code>HEAD</code>
layoutElement = headElement.getFirstChild();
while ((layoutElement != null) && !(layoutElement instanceof SMILLayoutElement)) {
layoutElement = layoutElement.getNextSibling();
}
if (layoutElement == null) {
// The layout doesn't exist. Create a default one.
layoutElement = new SmilLayoutElementImpl(this, "layout");
headElement.appendChild(layoutElement);
}
return (SMILLayoutElement) layoutElement;
}
/*
* DocumentEvent Interface
*/
public Event createEvent(String eventType) throws DOMException {
if ("Event".equals(eventType)) {
return new EventImpl();
} else {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR,
"Not supported interface");
}
}
}
| 9,134 | 30.284247 | 95 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILElement;
import org.thoughtcrime.securesms.dom.ElementImpl;
public class SmilElementImpl extends ElementImpl implements SMILElement {
/**
* This constructor is used by the factory methods of the SmilDocument.
*
* @param owner The SMIL document to which this element belongs to
* @param tagName The tag name of the element
*/
SmilElementImpl(SmilDocumentImpl owner, String tagName)
{
super(owner, tagName.toLowerCase());
}
public String getId() {
// TODO Auto-generated method stub
return null;
}
public void setId(String id) throws DOMException {
// TODO Auto-generated method stub
}
}
| 1,444 | 29.104167 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilLayoutElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.thoughtcrime.securesms.util.SmilUtil;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILLayoutElement;
import org.w3c.dom.smil.SMILRootLayoutElement;
public class SmilLayoutElementImpl extends SmilElementImpl implements
SMILLayoutElement {
SmilLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public boolean getResolved() {
// TODO Auto-generated method stub
return false;
}
public String getType() {
return this.getAttribute("type");
}
public NodeList getRegions() {
return this.getElementsByTagName("region");
}
public SMILRootLayoutElement getRootLayout() {
NodeList childNodes = this.getChildNodes();
SMILRootLayoutElement rootLayoutNode = null;
int childrenCount = childNodes.getLength();
for (int i = 0; i < childrenCount; i++) {
if (childNodes.item(i).getNodeName().equals("root-layout")) {
rootLayoutNode = (SMILRootLayoutElement)childNodes.item(i);
}
}
if (null == rootLayoutNode) {
// root-layout node is not set. Create a default one.
rootLayoutNode = (SMILRootLayoutElement) getOwnerDocument().createElement("root-layout");
rootLayoutNode.setWidth(SmilUtil.ROOT_WIDTH);
rootLayoutNode.setHeight(SmilUtil.ROOT_HEIGHT);
appendChild(rootLayoutNode);
}
return rootLayoutNode;
}
}
| 2,202 | 33.421875 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilMediaElementImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.TimeList;
import android.util.Log;
import org.thoughtcrime.securesms.dom.events.EventImpl;
public class SmilMediaElementImpl extends SmilElementImpl implements
SMILMediaElement {
public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart";
public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd";
public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause";
public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek";
private final static String TAG = "Mms:smil";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
ElementTime mElementTime = new ElementTimeImpl(this) {
private Event createEvent(String eventType) {
DocumentEvent doc =
(DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument();
Event event = doc.createEvent("Event");
event.initEvent(eventType, false, false);
if (LOCAL_LOGV) {
Log.v(TAG, "Dispatching 'begin' event to "
+ SmilMediaElementImpl.this.getTagName() + " "
+ SmilMediaElementImpl.this.getSrc() + " at "
+ System.currentTimeMillis());
}
return event;
}
private Event createEvent(String eventType, int seekTo) {
DocumentEvent doc =
(DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument();
EventImpl event = (EventImpl) doc.createEvent("Event");
event.initEvent(eventType, false, false, seekTo);
if (LOCAL_LOGV) {
Log.v(TAG, "Dispatching 'begin' event to "
+ SmilMediaElementImpl.this.getTagName() + " "
+ SmilMediaElementImpl.this.getSrc() + " at "
+ System.currentTimeMillis());
}
return event;
}
public boolean beginElement() {
Event startEvent = createEvent(SMIL_MEDIA_START_EVENT);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
Event endEvent = createEvent(SMIL_MEDIA_END_EVENT);
dispatchEvent(endEvent);
return true;
}
public void resumeElement() {
Event resumeEvent = createEvent(SMIL_MEDIA_START_EVENT);
dispatchEvent(resumeEvent);
}
public void pauseElement() {
Event pauseEvent = createEvent(SMIL_MEDIA_PAUSE_EVENT);
dispatchEvent(pauseEvent);
}
public void seekElement(float seekTo) {
Event seekEvent = createEvent(SMIL_MEDIA_SEEK_EVENT, (int) seekTo);
dispatchEvent(seekEvent);
}
@Override
public float getDur() {
float dur = super.getDur();
if (dur == 0) {
// Duration is not specified, So get the implicit duration.
String tag = getTagName();
if (tag.equals("video") || tag.equals("audio")) {
// Continuous media
// FIXME Should get the duration of the media. "indefinite" instead here.
dur = -1.0F;
} else if (tag.equals("text") || tag.equals("img")) {
// Discrete media
dur = 0;
} else {
Log.w(TAG, "Unknown media type");
}
}
return dur;
}
@Override
ElementTime getParentElementTime() {
return ((SmilParElementImpl) mSmilElement.getParentNode()).mParTimeContainer;
}
};
/*
* Internal Interface
*/
SmilMediaElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
/*
* SMILMediaElement Interface
*/
public String getAbstractAttr() {
return this.getAttribute("abstract");
}
public String getAlt() {
return this.getAttribute("alt");
}
public String getAuthor() {
return this.getAttribute("author");
}
public String getClipBegin() {
return this.getAttribute("clipBegin");
}
public String getClipEnd() {
return this.getAttribute("clipEnd");
}
public String getCopyright() {
return this.getAttribute("copyright");
}
public String getLongdesc() {
return this.getAttribute("longdesc");
}
public String getPort() {
return this.getAttribute("port");
}
public String getReadIndex() {
return this.getAttribute("readIndex");
}
public String getRtpformat() {
return this.getAttribute("rtpformat");
}
public String getSrc() {
return this.getAttribute("src");
}
public String getStripRepeat() {
return this.getAttribute("stripRepeat");
}
public String getTitle() {
return this.getAttribute("title");
}
public String getTransport() {
return this.getAttribute("transport");
}
public String getType() {
return this.getAttribute("type");
}
public void setAbstractAttr(String abstractAttr) throws DOMException {
this.setAttribute("abstract", abstractAttr);
}
public void setAlt(String alt) throws DOMException {
this.setAttribute("alt", alt);
}
public void setAuthor(String author) throws DOMException {
this.setAttribute("author", author);
}
public void setClipBegin(String clipBegin) throws DOMException {
this.setAttribute("clipBegin", clipBegin);
}
public void setClipEnd(String clipEnd) throws DOMException {
this.setAttribute("clipEnd", clipEnd);
}
public void setCopyright(String copyright) throws DOMException {
this.setAttribute("copyright", copyright);
}
public void setLongdesc(String longdesc) throws DOMException {
this.setAttribute("longdesc", longdesc);
}
public void setPort(String port) throws DOMException {
this.setAttribute("port", port);
}
public void setReadIndex(String readIndex) throws DOMException {
this.setAttribute("readIndex", readIndex);
}
public void setRtpformat(String rtpformat) throws DOMException {
this.setAttribute("rtpformat", rtpformat);
}
public void setSrc(String src) throws DOMException {
this.setAttribute("src", src);
}
public void setStripRepeat(String stripRepeat) throws DOMException {
this.setAttribute("stripRepeat", stripRepeat);
}
public void setTitle(String title) throws DOMException {
this.setAttribute("title", title);
}
public void setTransport(String transport) throws DOMException {
this.setAttribute("transport", transport);
}
public void setType(String type) throws DOMException {
this.setAttribute("type", type);
}
/*
* TimeElement Interface
*/
public boolean beginElement() {
return mElementTime.beginElement();
}
public boolean endElement() {
return mElementTime.endElement();
}
public TimeList getBegin() {
return mElementTime.getBegin();
}
public float getDur() {
return mElementTime.getDur();
}
public TimeList getEnd() {
return mElementTime.getEnd();
}
public short getFill() {
return mElementTime.getFill();
}
public short getFillDefault() {
return mElementTime.getFillDefault();
}
public float getRepeatCount() {
return mElementTime.getRepeatCount();
}
public float getRepeatDur() {
return mElementTime.getRepeatDur();
}
public short getRestart() {
return mElementTime.getRestart();
}
public void pauseElement() {
mElementTime.pauseElement();
}
public void resumeElement() {
mElementTime.resumeElement();
}
public void seekElement(float seekTo) {
mElementTime.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mElementTime.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mElementTime.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mElementTime.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mElementTime.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mElementTime.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mElementTime.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mElementTime.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mElementTime.setRestart(restart);
}
}
| 10,194 | 28.636628 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilParElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.SMILParElement;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
public class SmilParElementImpl extends SmilElementImpl implements SMILParElement {
public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart";
public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd";
ElementParallelTimeContainer mParTimeContainer =
new ElementParallelTimeContainerImpl(this) {
@Override
public TimeList getBegin() {
/*
* For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value.
*/
TimeList beginTimeList = super.getBegin();
if (beginTimeList.getLength() > 1) {
ArrayList<Time> singleTimeContainer = new ArrayList<Time>();
singleTimeContainer.add(beginTimeList.item(0));
beginTimeList = new TimeListImpl(singleTimeContainer);
}
return beginTimeList;
}
public NodeList getTimeChildren() {
return getChildNodes();
}
public boolean beginElement() {
DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument();
Event startEvent = doc.createEvent("Event");
startEvent.initEvent(SMIL_SLIDE_START_EVENT, false, false);
dispatchEvent(startEvent);
return true;
}
public boolean endElement() {
DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument();
Event endEvent = doc.createEvent("Event");
endEvent.initEvent(SMIL_SLIDE_END_EVENT, false, false);
dispatchEvent(endEvent);
return true;
}
public void pauseElement() {
// TODO Auto-generated method stub
}
public void resumeElement() {
// TODO Auto-generated method stub
}
public void seekElement(float seekTo) {
// TODO Auto-generated method stub
}
ElementTime getParentElementTime() {
return ((SmilDocumentImpl) mSmilElement.getOwnerDocument()).mSeqTimeContainer;
}
};
/*
* Internal Interface
*/
SmilParElementImpl(SmilDocumentImpl owner, String tagName)
{
super(owner, tagName.toUpperCase());
}
int getBeginConstraints() {
/*
* For children of a sequence, the only legal value for begin is
* a (single) non-negative offset value.
*/
return (TimeImpl.ALLOW_OFFSET_VALUE); // Do not set ALLOW_NEGATIVE_VALUE
}
/*
* ElementParallelTimeContainer
*/
public String getEndSync() {
return mParTimeContainer.getEndSync();
}
public float getImplicitDuration() {
return mParTimeContainer.getImplicitDuration();
}
public void setEndSync(String endSync) throws DOMException {
mParTimeContainer.setEndSync(endSync);
}
public NodeList getActiveChildrenAt(float instant) {
return mParTimeContainer.getActiveChildrenAt(instant);
}
public NodeList getTimeChildren() {
return mParTimeContainer.getTimeChildren();
}
public boolean beginElement() {
return mParTimeContainer.beginElement();
}
public boolean endElement() {
return mParTimeContainer.endElement();
}
public TimeList getBegin() {
return mParTimeContainer.getBegin();
}
public float getDur() {
return mParTimeContainer.getDur();
}
public TimeList getEnd() {
return mParTimeContainer.getEnd();
}
public short getFill() {
return mParTimeContainer.getFill();
}
public short getFillDefault() {
return mParTimeContainer.getFillDefault();
}
public float getRepeatCount() {
return mParTimeContainer.getRepeatCount();
}
public float getRepeatDur() {
return mParTimeContainer.getRepeatDur();
}
public short getRestart() {
return mParTimeContainer.getRestart();
}
public void pauseElement() {
mParTimeContainer.pauseElement();
}
public void resumeElement() {
mParTimeContainer.resumeElement();
}
public void seekElement(float seekTo) {
mParTimeContainer.seekElement(seekTo);
}
public void setBegin(TimeList begin) throws DOMException {
mParTimeContainer.setBegin(begin);
}
public void setDur(float dur) throws DOMException {
mParTimeContainer.setDur(dur);
}
public void setEnd(TimeList end) throws DOMException {
mParTimeContainer.setEnd(end);
}
public void setFill(short fill) throws DOMException {
mParTimeContainer.setFill(fill);
}
public void setFillDefault(short fillDefault) throws DOMException {
mParTimeContainer.setFillDefault(fillDefault);
}
public void setRepeatCount(float repeatCount) throws DOMException {
mParTimeContainer.setRepeatCount(repeatCount);
}
public void setRepeatDur(float repeatDur) throws DOMException {
mParTimeContainer.setRepeatDur(repeatDur);
}
public void setRestart(short restart) throws DOMException {
mParTimeContainer.setRestart(restart);
}
}
| 6,283 | 27.825688 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilRefElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.smil.SMILRefElement;
public class SmilRefElementImpl extends SmilRegionMediaElementImpl implements
SMILRefElement {
SmilRefElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
}
| 952 | 30.766667 | 77 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilRegionElementImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import android.util.Log;
public class SmilRegionElementImpl extends SmilElementImpl implements
SMILRegionElement {
/*
* Internal Interface
*/
private static final String HIDDEN_ATTRIBUTE = "hidden";
private static final String SLICE_ATTRIBUTE = "slice";
private static final String SCROLL_ATTRIBUTE = "scroll";
private static final String MEET_ATTRIBUTE = "meet";
private static final String FILL_ATTRIBUTE = "fill";
private static final String ID_ATTRIBUTE_NAME = "id";
private static final String WIDTH_ATTRIBUTE_NAME = "width";
private static final String TITLE_ATTRIBUTE_NAME = "title";
private static final String HEIGHT_ATTRIBUTE_NAME = "height";
private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor";
private static final String Z_INDEX_ATTRIBUTE_NAME = "z-index";
private static final String TOP_ATTRIBUTE_NAME = "top";
private static final String LEFT_ATTRIBUTE_NAME = "left";
private static final String RIGHT_ATTRIBUTE_NAME = "right";
private static final String BOTTOM_ATTRIBUTE_NAME = "bottom";
private static final String FIT_ATTRIBUTE_NAME = "fit";
private static final String TAG = "SmilRegionElementImpl";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
/*
* SMILRegionElement Interface
*/
public String getFit() {
String fit = getAttribute(FIT_ATTRIBUTE_NAME);
if (FILL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return FILL_ATTRIBUTE;
} else if (MEET_ATTRIBUTE.equalsIgnoreCase(fit)) {
return MEET_ATTRIBUTE;
} else if (SCROLL_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SCROLL_ATTRIBUTE;
} else if (SLICE_ATTRIBUTE.equalsIgnoreCase(fit)) {
return SLICE_ATTRIBUTE;
} else {
return HIDDEN_ATTRIBUTE;
}
}
public int getLeft() {
try {
return parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Left attribute is not set or incorrect.");
}
}
try {
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
int right = parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return bbw - right - width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Right or width attribute is not set or incorrect.");
}
}
return 0;
}
public int getTop() {
try {
return parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Top attribute is not set or incorrect.");
}
}
try {
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
int bottom = parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return bbh - bottom - height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Bottom or height attribute is not set or incorrect.");
}
}
return 0;
}
public int getZIndex() {
try {
return Integer.parseInt(this.getAttribute(Z_INDEX_ATTRIBUTE_NAME));
} catch (NumberFormatException _) {
return 0;
}
}
public void setFit(String fit) throws DOMException {
if (fit.equalsIgnoreCase(FILL_ATTRIBUTE)
|| fit.equalsIgnoreCase(MEET_ATTRIBUTE)
|| fit.equalsIgnoreCase(SCROLL_ATTRIBUTE)
|| fit.equalsIgnoreCase(SLICE_ATTRIBUTE)) {
this.setAttribute(FIT_ATTRIBUTE_NAME, fit.toLowerCase());
} else {
this.setAttribute(FIT_ATTRIBUTE_NAME, HIDDEN_ATTRIBUTE);
}
}
public void setLeft(int left) throws DOMException {
this.setAttribute(LEFT_ATTRIBUTE_NAME, String.valueOf(left));
}
public void setTop(int top) throws DOMException {
this.setAttribute(TOP_ATTRIBUTE_NAME, String.valueOf(top));
}
public void setZIndex(int zIndex) throws DOMException {
if (zIndex > 0) {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(zIndex));
} else {
this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(0));
}
}
public String getBackgroundColor() {
return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME);
}
public int getHeight() {
try {
final int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false);
return height == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight() :
height;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Height attribute is not set or incorrect.");
}
}
int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
try {
bbh -= parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Top attribute is not set or incorrect.");
}
}
try {
bbh -= parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Bottom attribute is not set or incorrect.");
}
}
return bbh;
}
public String getTitle() {
return this.getAttribute(TITLE_ATTRIBUTE_NAME);
}
public int getWidth() {
try {
final int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true);
return width == 0 ?
((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth() :
width;
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Width attribute is not set or incorrect.");
}
}
int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
try {
bbw -= parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Left attribute is not set or incorrect.");
}
}
try {
bbw -= parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true);
} catch (NumberFormatException _) {
if (LOCAL_LOGV) {
Log.v(TAG, "Right attribute is not set or incorrect.");
}
}
return bbw;
}
public void setBackgroundColor(String backgroundColor) throws DOMException {
this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor);
}
public void setHeight(int height) throws DOMException {
this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px");
}
public void setTitle(String title) throws DOMException {
this.setAttribute(TITLE_ATTRIBUTE_NAME, title);
}
public void setWidth(int width) throws DOMException {
this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px");
}
/*
* SMILElement Interface
*/
@Override
public String getId() {
return this.getAttribute(ID_ATTRIBUTE_NAME);
}
@Override
public void setId(String id) throws DOMException {
this.setAttribute(ID_ATTRIBUTE_NAME, id);
}
/*
* Internal Interface
*/
private int parseRegionLength(String length, boolean horizontal) {
if (length.endsWith("px")) {
length = length.substring(0, length.indexOf("px"));
return Integer.parseInt(length);
} else if (length.endsWith("%")) {
double value = 0.01*Integer.parseInt(length.substring(0, length.length() - 1));
if (horizontal) {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth();
} else {
value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight();
}
return (int) Math.round(value);
} else {
return Integer.parseInt(length);
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString()
+ ": id=" + getId()
+ ", width=" + getWidth()
+ ", height=" + getHeight()
+ ", left=" + getLeft()
+ ", top=" + getTop();
}
}
| 10,136 | 34.693662 | 101 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilRegionMediaElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILRegionElement;
import org.w3c.dom.smil.SMILRegionMediaElement;
public class SmilRegionMediaElementImpl extends SmilMediaElementImpl implements
SMILRegionMediaElement {
private SMILRegionElement mRegion;
SmilRegionMediaElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public SMILRegionElement getRegion() {
if (mRegion == null) {
SMILDocument doc = (SMILDocument)this.getOwnerDocument();
NodeList regions = doc.getLayout().getElementsByTagName("region");
SMILRegionElement region = null;
for (int i = 0; i < regions.getLength(); i++) {
region = (SMILRegionElement)regions.item(i);
if (region.getId().equals(this.getAttribute("region"))) {
mRegion = region;
}
}
}
return mRegion;
}
public void setRegion(SMILRegionElement region) {
this.setAttribute("region", region.getId());
mRegion = region;
}
}
| 1,841 | 33.111111 | 79 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/SmilRootLayoutElementImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.smil.SMILRootLayoutElement;
public class SmilRootLayoutElementImpl extends SmilElementImpl implements
SMILRootLayoutElement {
private static final String WIDTH_ATTRIBUTE_NAME = "width";
private static final String HEIGHT_ATTRIBUTE_NAME = "height";
private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor";
private static final String TITLE_ATTRIBUTE_NAME = "title";
SmilRootLayoutElementImpl(SmilDocumentImpl owner, String tagName) {
super(owner, tagName);
}
public String getBackgroundColor() {
return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME);
}
public int getHeight() {
String heightString = this.getAttribute(HEIGHT_ATTRIBUTE_NAME);
return parseAbsoluteLength(heightString);
}
public String getTitle() {
return this.getAttribute(TITLE_ATTRIBUTE_NAME);
}
public int getWidth() {
String widthString = this.getAttribute(WIDTH_ATTRIBUTE_NAME);
return parseAbsoluteLength(widthString);
}
public void setBackgroundColor(String backgroundColor) throws DOMException {
this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor);
}
public void setHeight(int height) throws DOMException {
this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px");
}
public void setTitle(String title) throws DOMException {
this.setAttribute(TITLE_ATTRIBUTE_NAME, title);
}
public void setWidth(int width) throws DOMException {
this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px");
}
/*
* Internal Interface
*/
private int parseAbsoluteLength(String length) {
if (length.endsWith("px")) {
length = length.substring(0, length.indexOf("px"));
}
try {
return Integer.parseInt(length);
} catch (NumberFormatException e) {
return 0;
}
}
}
| 2,732 | 31.152941 | 84 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/TimeImpl.java | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.dom.smil;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.smil.Time;
public class TimeImpl implements Time {
static final int ALLOW_INDEFINITE_VALUE = (1 << 0);
static final int ALLOW_OFFSET_VALUE = (1 << 1);
static final int ALLOW_SYNCBASE_VALUE = (1 << 2);
static final int ALLOW_SYNCTOPREV_VALUE = (1 << 3);
static final int ALLOW_EVENT_VALUE = (1 << 4);
static final int ALLOW_MARKER_VALUE = (1 << 5);
static final int ALLOW_WALLCLOCK_VALUE = (1 << 6);
static final int ALLOW_NEGATIVE_VALUE = (1 << 7);
static final int ALLOW_ALL = 0xFF;
short mTimeType;
boolean mResolved;
double mResolvedOffset;
/**
* Creates a TimeImpl representation of a time-value represented as a String.
* Time-values have the following syntax:
* <p>
* <pre>
* Time-val ::= ( smil-1.0-syncbase-value
* | "indefinite"
* | offset-value
* | syncbase-value
* | syncToPrev-value
* | event-value
* | media-marker-value
* | wallclock-sync-value )
* Smil-1.0-syncbase-value ::=
* "id(" id-ref ")" ( "(" ( "begin" | "end" | clock-value ) ")" )?
* Offset-value ::= ( "+" | "-" )? clock-value
* Syncbase-value ::= ( id-ref "." ( "begin" | "end" ) ) ( ( "+" | "-" ) clock-value )?
* SyncToPrev-value ::= ( "prev.begin" | "prev.end" ) ( ( "+" | "-" ) clock-value )?
* Event-value ::= ( id-ref "." )? ( event-ref ) ( ( "+" | "-" ) clock-value )?
* Media-marker-value ::= id-ref ".marker(" marker-name ")"
* Wallclock-sync-value ::= "wallclock(" wallclock-value ")"
* </pre>
*
* @param timeValue A String in the representation specified above
* @param constraints Any combination of the #ALLOW_* flags
* @return A TimeImpl instance representing
* @exception java.lang.IllegalArgumentException if the timeValue input
* parameter does not comply with the defined syntax
* @exception java.lang.NullPointerException if the timekValue string is
* <code>null</code>
*/
TimeImpl(String timeValue, int constraints) {
/*
* We do not support yet:
* - smil-1.0-syncbase-value
* - syncbase-value
* - syncToPrev-value
* - event-value
* - Media-marker-value
* - Wallclock-sync-value
*/
// Will throw NullPointerException if timeValue is null
if (timeValue.equals("indefinite")
&& ((constraints & ALLOW_INDEFINITE_VALUE) != 0) ) {
mTimeType = SMIL_TIME_INDEFINITE;
} else if ((constraints & ALLOW_OFFSET_VALUE) != 0) {
int sign = 1;
if (timeValue.startsWith("+")) {
timeValue = timeValue.substring(1);
} else if (timeValue.startsWith("-")) {
timeValue = timeValue.substring(1);
sign = -1;
}
mResolvedOffset = sign*parseClockValue(timeValue)/1000.0;
mResolved = true;
mTimeType = SMIL_TIME_OFFSET;
} else {
throw new IllegalArgumentException("Unsupported time value");
}
}
/**
* Converts a String representation of a clock value into the float
* representation used in this API.
* <p>
* Clock values have the following syntax:
* </p>
* <p>
* <pre>
* Clock-val ::= ( Full-clock-val | Partial-clock-val | Timecount-val )
* Full-clock-val ::= Hours ":" Minutes ":" Seconds ("." Fraction)?
* Partial-clock-val ::= Minutes ":" Seconds ("." Fraction)?
* Timecount-val ::= Timecount ("." Fraction)? (Metric)?
* Metric ::= "h" | "min" | "s" | "ms"
* Hours ::= DIGIT+; any positive number
* Minutes ::= 2DIGIT; range from 00 to 59
* Seconds ::= 2DIGIT; range from 00 to 59
* Fraction ::= DIGIT+
* Timecount ::= DIGIT+
* 2DIGIT ::= DIGIT DIGIT
* DIGIT ::= [0-9]
* </pre>
*
* @param clockValue A String in the representation specified above
* @return A float value in milliseconds that matches the string
* representation given as the parameter
* @exception java.lang.IllegalArgumentException if the clockValue input
* parameter does not comply with the defined syntax
* @exception java.lang.NullPointerException if the clockValue string is
* <code>null</code>
*/
public static float parseClockValue(String clockValue) {
try {
float result = 0;
// Will throw NullPointerException if clockValue is null
clockValue = clockValue.trim();
// Handle first 'Timecount-val' cases with metric
if (clockValue.endsWith("ms")) {
result = parseFloat(clockValue, 2, true);
} else if (clockValue.endsWith("s")) {
result = 1000*parseFloat(clockValue, 1, true);
} else if (clockValue.endsWith("min")) {
result = 60000*parseFloat(clockValue, 3, true);
} else if (clockValue.endsWith("h")) {
result = 3600000*parseFloat(clockValue, 1, true);
} else {
// Handle Timecount-val without metric
try {
return parseFloat(clockValue, 0, true) * 1000;
} catch (NumberFormatException _) {
// Ignore
}
// Split in {[Hours], Minutes, Seconds}
String[] timeValues = clockValue.split(":");
// Read Hours if present and remember location of Minutes
int indexOfMinutes;
if (timeValues.length == 2) {
indexOfMinutes = 0;
} else if (timeValues.length == 3) {
result = 3600000*(int)parseFloat(timeValues[0], 0, false);
indexOfMinutes = 1;
} else {
throw new IllegalArgumentException();
}
// Read Minutes
int minutes = (int)parseFloat(timeValues[indexOfMinutes], 0, false);
if ((minutes >= 00) && (minutes <= 59)) {
result += 60000*minutes;
} else {
throw new IllegalArgumentException();
}
// Read Seconds
float seconds = parseFloat(timeValues[indexOfMinutes + 1], 0, true);
if ((seconds >= 00) && (seconds < 60)) {
result += 60000*seconds;
} else {
throw new IllegalArgumentException();
}
}
return result;
} catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
}
/**
* Parse a value formatted as follows:
* <p>
* <pre>
* Value ::= Number ("." Decimal)? (Text)?
* Number ::= DIGIT+; any positive number
* Decimal ::= DIGIT+; any positive number
* Text ::= CHAR*; any sequence of chars
* DIGIT ::= [0-9]
* </pre>
* @param value The Value to parse
* @param ignoreLast The size of Text to ignore
* @param parseDecimal Whether Decimal is expected
* @return The float value without Text, rounded to 3 digits after '.'
* @throws IllegalArgumentException if Decimal was not expected but encountered
*/
private static float parseFloat(String value, int ignoreLast, boolean parseDecimal) {
// Ignore last characters
value = value.substring(0, value.length() - ignoreLast);
float result;
int indexOfComma = value.indexOf('.');
if (indexOfComma != -1) {
if (!parseDecimal) {
throw new IllegalArgumentException("int value contains decimal");
}
// Ensure that there are at least 3 decimals
value = value + "000";
// Read value up to 3 decimals and cut the rest
result = Float.parseFloat(value.substring(0, indexOfComma));
result += Float.parseFloat(
value.substring(indexOfComma + 1, indexOfComma + 4))/1000;
} else {
result = Integer.parseInt(value);
}
return result;
}
/*
* Time Interface
*/
public boolean getBaseBegin() {
// TODO Auto-generated method stub
return false;
}
public Element getBaseElement() {
// TODO Auto-generated method stub
return null;
}
public String getEvent() {
// TODO Auto-generated method stub
return null;
}
public String getMarker() {
// TODO Auto-generated method stub
return null;
}
public double getOffset() {
// TODO Auto-generated method stub
return 0;
}
public boolean getResolved() {
return mResolved;
}
public double getResolvedOffset() {
return mResolvedOffset;
}
public short getTimeType() {
return mTimeType;
}
public void setBaseBegin(boolean baseBegin) throws DOMException {
// TODO Auto-generated method stub
}
public void setBaseElement(Element baseElement) throws DOMException {
// TODO Auto-generated method stub
}
public void setEvent(String event) throws DOMException {
// TODO Auto-generated method stub
}
public void setMarker(String marker) throws DOMException {
// TODO Auto-generated method stub
}
public void setOffset(double offset) throws DOMException {
// TODO Auto-generated method stub
}
}
| 10,747 | 35.310811 | 97 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/TimeListImpl.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil;
import java.util.ArrayList;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
public class TimeListImpl implements TimeList {
private final ArrayList<Time> mTimes;
/*
* Internal Interface
*/
TimeListImpl(ArrayList<Time> times) {
mTimes = times;
}
/*
* TimeList Interface
*/
public int getLength() {
return mTimes.size();
}
public Time item(int index) {
Time time = null;
try {
time = mTimes.get(index);
} catch (IndexOutOfBoundsException e) {
// Do nothing and return null
}
return time;
}
}
| 1,351 | 24.037037 | 75 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/dom/smil/parser/SmilXmlSerializer.java | /*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 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.dom.smil.parser;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
public class SmilXmlSerializer {
public static void serialize(SMILDocument smilDoc, OutputStream out) {
try {
Writer writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"), 2048);
writeElement(writer, smilDoc.getDocumentElement());
writer.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void writeElement(Writer writer, Element element)
throws IOException {
writer.write('<');
writer.write(element.getTagName());
if (element.hasAttributes()) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr)attributes.item(i);
writer.write(" " + attribute.getName());
writer.write("=\"" + attribute.getValue() + "\"");
}
}
// FIXME: Might throw ClassCastException
SMILElement childElement = (SMILElement) element.getFirstChild();
if (childElement != null) {
writer.write('>');
do {
writeElement(writer, childElement);
childElement = (SMILElement) childElement.getNextSibling();
} while (childElement != null);
writer.write("</");
writer.write(element.getTagName());
writer.write('>');
} else {
writer.write("/>");
}
}
}
| 2,646 | 31.679012 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/events/PartProgressEvent.java | package org.thoughtcrime.securesms.events;
import android.support.annotation.NonNull;
import org.thoughtcrime.securesms.attachments.Attachment;
public class PartProgressEvent {
public final Attachment attachment;
public final long total;
public final long progress;
public PartProgressEvent(@NonNull Attachment attachment, long total, long progress) {
this.attachment = attachment;
this.total = total;
this.progress = progress;
}
}
| 479 | 23 | 87 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/events/RedPhoneEvent.java | package org.thoughtcrime.securesms.events;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.thoughtcrime.securesms.recipients.Recipient;
public class RedPhoneEvent {
public enum Type {
CALL_CONNECTED,
WAITING_FOR_RESPONDER,
SERVER_FAILURE,
PERFORMING_HANDSHAKE,
HANDSHAKE_FAILED,
CONNECTING_TO_INITIATOR,
CALL_DISCONNECTED,
CALL_RINGING,
SERVER_MESSAGE,
RECIPIENT_UNAVAILABLE,
INCOMING_CALL,
OUTGOING_CALL,
CALL_BUSY,
LOGIN_FAILED,
CLIENT_FAILURE,
DEBUG_INFO,
NO_SUCH_USER
}
private final @NonNull Type type;
private final @NonNull Recipient recipient;
private final @Nullable String extra;
public RedPhoneEvent(@NonNull Type type, @NonNull Recipient recipient, @Nullable String extra) {
this.type = type;
this.recipient = recipient;
this.extra = extra;
}
public @NonNull Type getType() {
return type;
}
public @NonNull Recipient getRecipient() {
return recipient;
}
public @Nullable String getExtra() {
return extra;
}
}
| 1,117 | 20.5 | 98 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/gcm/GcmBroadcastReceiver.java | package org.thoughtcrime.securesms.gcm;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.thoughtcrime.redphone.RedPhoneService;
import org.thoughtcrime.redphone.crypto.EncryptedSignalMessage;
import org.thoughtcrime.redphone.crypto.InvalidEncryptedSignalException;
import org.thoughtcrime.redphone.signaling.SessionDescriptor;
import org.thoughtcrime.redphone.signaling.signals.CompressedInitiateSignalProtocol.CompressedInitiateSignal;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.jobs.PushContentReceiveJob;
import org.thoughtcrime.securesms.jobs.PushNotificationReceiveJob;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.io.IOException;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
private static final String TAG = GcmBroadcastReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.w(TAG, "GCM message...");
if (!TextSecurePreferences.isPushRegistered(context)) {
Log.w(TAG, "Not push registered!");
return;
}
String messageData = intent.getStringExtra("message");
String receiptData = intent.getStringExtra("receipt");
String callData = intent.getStringExtra("call");
if (!TextUtils.isEmpty(messageData)) handleReceivedMessage(context, messageData);
else if (!TextUtils.isEmpty(receiptData)) handleReceivedMessage(context, receiptData);
else if (intent.hasExtra("notification")) handleReceivedNotification(context);
else if (!TextUtils.isEmpty(callData)) handleReceivedCall(context, callData);
}
}
private void handleReceivedMessage(Context context, String data) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new PushContentReceiveJob(context, data));
}
private void handleReceivedNotification(Context context) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new PushNotificationReceiveJob(context));
}
private void handleReceivedCall(final Context context, final String data) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
String signalingKey = TextSecurePreferences.getSignalingKey(context);
EncryptedSignalMessage encryptedSignalMessage = new EncryptedSignalMessage(data, signalingKey);
CompressedInitiateSignal signal = CompressedInitiateSignal.parseFrom(encryptedSignalMessage.getPlaintext());
Recipients recipients = RecipientFactory.getRecipientsFromString(context, signal.getInitiator(), false);
if (!recipients.isBlocked()) {
Intent intent = new Intent(context, RedPhoneService.class);
intent.setAction(RedPhoneService.ACTION_INCOMING_CALL);
intent.putExtra(RedPhoneService.EXTRA_REMOTE_NUMBER, signal.getInitiator());
intent.putExtra(RedPhoneService.EXTRA_SESSION_DESCRIPTOR, new SessionDescriptor(signal.getServerName(),
signal.getPort(),
signal.getSessionId(),
signal.getVersion()));
context.startService(intent);
} else {
Log.w(TAG, "*** Received incoming call from blocked number, ignoring...");
}
} catch (InvalidEncryptedSignalException | IOException e) {
Log.w(TAG, e);
}
return null;
}
}.execute();
}
} | 4,404 | 44.885417 | 140 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/groups/GroupManager.java | package org.thoughtcrime.securesms.groups;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.protobuf.ByteString;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.UriAttachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.mms.OutgoingGroupMediaMessage;
import org.thoughtcrime.securesms.providers.SingleUseBlobProvider;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.sms.MessageSender;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import ws.com.google.android.mms.ContentType;
public class GroupManager {
public static @NonNull GroupActionResult createGroup(@NonNull Context context,
@NonNull MasterSecret masterSecret,
@NonNull Set<Recipient> members,
@Nullable Bitmap avatar,
@Nullable String name)
throws InvalidNumberException
{
final byte[] avatarBytes = BitmapUtil.toByteArray(avatar);
final GroupDatabase groupDatabase = DatabaseFactory.getGroupDatabase(context);
final byte[] groupId = groupDatabase.allocateGroupId();
final Set<String> memberE164Numbers = getE164Numbers(context, members);
memberE164Numbers.add(TextSecurePreferences.getLocalNumber(context));
groupDatabase.create(groupId, name, new LinkedList<>(memberE164Numbers), null, null);
groupDatabase.updateAvatar(groupId, avatarBytes);
return sendGroupUpdate(context, masterSecret, groupId, memberE164Numbers, name, avatarBytes);
}
private static Set<String> getE164Numbers(Context context, Collection<Recipient> recipients)
throws InvalidNumberException
{
final Set<String> results = new HashSet<>();
for (Recipient recipient : recipients) {
results.add(Util.canonicalizeNumber(context, recipient.getNumber()));
}
return results;
}
public static GroupActionResult updateGroup(@NonNull Context context,
@NonNull MasterSecret masterSecret,
@NonNull byte[] groupId,
@NonNull Set<Recipient> members,
@Nullable Bitmap avatar,
@Nullable String name)
throws InvalidNumberException
{
final GroupDatabase groupDatabase = DatabaseFactory.getGroupDatabase(context);
final Set<String> memberE164Numbers = getE164Numbers(context, members);
final byte[] avatarBytes = BitmapUtil.toByteArray(avatar);
memberE164Numbers.add(TextSecurePreferences.getLocalNumber(context));
groupDatabase.updateMembers(groupId, new LinkedList<>(memberE164Numbers));
groupDatabase.updateTitle(groupId, name);
groupDatabase.updateAvatar(groupId, avatarBytes);
return sendGroupUpdate(context, masterSecret, groupId, memberE164Numbers, name, avatarBytes);
}
private static GroupActionResult sendGroupUpdate(@NonNull Context context,
@NonNull MasterSecret masterSecret,
@NonNull byte[] groupId,
@NonNull Set<String> e164numbers,
@Nullable String groupName,
@Nullable byte[] avatar)
{
Attachment avatarAttachment = null;
String groupRecipientId = GroupUtil.getEncodedId(groupId);
Recipients groupRecipient = RecipientFactory.getRecipientsFromString(context, groupRecipientId, false);
GroupContext.Builder groupContextBuilder = GroupContext.newBuilder()
.setId(ByteString.copyFrom(groupId))
.setType(GroupContext.Type.UPDATE)
.addAllMembers(e164numbers);
if (groupName != null) groupContextBuilder.setName(groupName);
GroupContext groupContext = groupContextBuilder.build();
if (avatar != null) {
Uri avatarUri = SingleUseBlobProvider.getInstance().createUri(avatar);
avatarAttachment = new UriAttachment(avatarUri, ContentType.IMAGE_JPEG, AttachmentDatabase.TRANSFER_PROGRESS_DONE, avatar.length);
}
OutgoingGroupMediaMessage outgoingMessage = new OutgoingGroupMediaMessage(groupRecipient, groupContext, avatarAttachment, System.currentTimeMillis());
long threadId = MessageSender.send(context, masterSecret, outgoingMessage, -1, false);
return new GroupActionResult(groupRecipient, threadId);
}
public static class GroupActionResult {
private Recipients groupRecipient;
private long threadId;
public GroupActionResult(Recipients groupRecipient, long threadId) {
this.groupRecipient = groupRecipient;
this.threadId = threadId;
}
public Recipients getGroupRecipient() {
return groupRecipient;
}
public long getThreadId() {
return threadId;
}
}
}
| 6,325 | 46.208955 | 155 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/groups/GroupMessageProcessor.java | package org.thoughtcrime.securesms.groups;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.Pair;
import com.google.protobuf.ByteString;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.EncryptingSmsDatabase;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.jobs.AvatarDownloadJob;
import org.thoughtcrime.securesms.mms.OutgoingGroupMediaMessage;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.sms.IncomingGroupMessage;
import org.thoughtcrime.securesms.sms.IncomingTextMessage;
import org.thoughtcrime.securesms.util.Base64;
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.TextSecureDataMessage;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.whispersystems.textsecure.api.messages.TextSecureGroup;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import ws.com.google.android.mms.MmsException;
import static org.thoughtcrime.securesms.database.GroupDatabase.GroupRecord;
import static org.whispersystems.textsecure.internal.push.TextSecureProtos.AttachmentPointer;
import static org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext;
public class GroupMessageProcessor {
private static final String TAG = GroupMessageProcessor.class.getSimpleName();
public static void process(@NonNull Context context,
@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureDataMessage message,
boolean outgoing)
{
if (!message.getGroupInfo().isPresent() || message.getGroupInfo().get().getGroupId() == null) {
Log.w(TAG, "Received group message with no id! Ignoring...");
return;
}
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
TextSecureGroup group = message.getGroupInfo().get();
byte[] id = group.getGroupId();
GroupRecord record = database.getGroup(id);
if (record != null && group.getType() == TextSecureGroup.Type.UPDATE) {
handleGroupUpdate(context, masterSecret, envelope, group, record, outgoing);
} else if (record == null && group.getType() == TextSecureGroup.Type.UPDATE) {
handleGroupCreate(context, masterSecret, envelope, group, outgoing);
} else if (record != null && group.getType() == TextSecureGroup.Type.QUIT) {
handleGroupLeave(context, masterSecret, envelope, group, record, outgoing);
} else {
Log.w(TAG, "Received unknown type, ignoring...");
}
}
private static void handleGroupCreate(@NonNull Context context,
@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureGroup group,
boolean outgoing)
{
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
byte[] id = group.getGroupId();
GroupContext.Builder builder = createGroupContext(group);
builder.setType(GroupContext.Type.UPDATE);
TextSecureAttachment avatar = group.getAvatar().orNull();
database.create(id, group.getName().orNull(), group.getMembers().orNull(),
avatar != null && avatar.isPointer() ? avatar.asPointer() : null,
envelope.getRelay());
storeMessage(context, masterSecret, envelope, group, builder.build(), outgoing);
}
private static void handleGroupUpdate(@NonNull Context context,
@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureGroup group,
@NonNull GroupRecord groupRecord,
boolean outgoing)
{
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
byte[] id = group.getGroupId();
Set<String> recordMembers = new HashSet<>(groupRecord.getMembers());
Set<String> messageMembers = new HashSet<>(group.getMembers().get());
Set<String> addedMembers = new HashSet<>(messageMembers);
addedMembers.removeAll(recordMembers);
Set<String> missingMembers = new HashSet<>(recordMembers);
missingMembers.removeAll(messageMembers);
GroupContext.Builder builder = createGroupContext(group);
builder.setType(GroupContext.Type.UPDATE);
if (addedMembers.size() > 0) {
Set<String> unionMembers = new HashSet<>(recordMembers);
unionMembers.addAll(messageMembers);
database.updateMembers(id, new LinkedList<>(unionMembers));
builder.clearMembers().addAllMembers(addedMembers);
} else {
builder.clearMembers();
}
if (missingMembers.size() > 0) {
// TODO We should tell added and missing about each-other.
}
if (group.getName().isPresent() || group.getAvatar().isPresent()) {
TextSecureAttachment avatar = group.getAvatar().orNull();
database.update(id, group.getName().orNull(), avatar != null ? avatar.asPointer() : null);
}
if (group.getName().isPresent() && group.getName().get().equals(groupRecord.getTitle())) {
builder.clearName();
}
if (!groupRecord.isActive()) database.setActive(id, true);
storeMessage(context, masterSecret, envelope, group, builder.build(), outgoing);
}
private static void handleGroupLeave(@NonNull Context context,
@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureGroup group,
@NonNull GroupRecord record,
boolean outgoing)
{
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
byte[] id = group.getGroupId();
List<String> members = record.getMembers();
GroupContext.Builder builder = createGroupContext(group);
builder.setType(GroupContext.Type.QUIT);
if (members.contains(envelope.getSource())) {
database.remove(id, envelope.getSource());
if (outgoing) database.setActive(id, false);
storeMessage(context, masterSecret, envelope, group, builder.build(), outgoing);
}
}
private static void storeMessage(@NonNull Context context,
@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureGroup group,
@NonNull GroupContext storage,
boolean outgoing)
{
if (group.getAvatar().isPresent()) {
ApplicationContext.getInstance(context).getJobManager()
.add(new AvatarDownloadJob(context, group.getGroupId()));
}
try {
if (outgoing) {
MmsDatabase mmsDatabase = DatabaseFactory.getMmsDatabase(context);
Recipients recipients = RecipientFactory.getRecipientsFromString(context, GroupUtil.getEncodedId(group.getGroupId()), false);
OutgoingGroupMediaMessage outgoingMessage = new OutgoingGroupMediaMessage(recipients, storage, null, envelope.getTimestamp());
long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
long messageId = mmsDatabase.insertMessageOutbox(masterSecret, outgoingMessage, threadId, false);
mmsDatabase.markAsSent(messageId);
} else {
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
String body = Base64.encodeBytes(storage.toByteArray());
IncomingTextMessage incoming = new IncomingTextMessage(envelope.getSource(), envelope.getSourceDevice(), envelope.getTimestamp(), body, Optional.of(group));
IncomingGroupMessage groupMessage = new IncomingGroupMessage(incoming, storage, body);
Pair<Long, Long> messageAndThreadId = smsDatabase.insertMessageInbox(masterSecret, groupMessage);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
}
} catch (MmsException e) {
Log.w(TAG, e);
}
}
private static GroupContext.Builder createGroupContext(TextSecureGroup group) {
GroupContext.Builder builder = GroupContext.newBuilder();
builder.setId(ByteString.copyFrom(group.getGroupId()));
if (group.getAvatar().isPresent() && group.getAvatar().get().isPointer()) {
builder.setAvatar(AttachmentPointer.newBuilder()
.setId(group.getAvatar().get().asPointer().getId())
.setKey(ByteString.copyFrom(group.getAvatar().get().asPointer().getKey()))
.setContentType(group.getAvatar().get().getContentType()));
}
if (group.getName().isPresent()) {
builder.setName(group.getName().get());
}
if (group.getMembers().isPresent()) {
builder.addAllMembers(group.getMembers().get());
}
return builder;
}
}
| 10,128 | 43.818584 | 170 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/AttachmentDownloadJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.AttachmentId;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.crypto.MediaKey;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.events.PartProgressEvent;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.jobs.requirements.MediaNetworkRequirement;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.util.VisibleForTesting;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment.ProgressListener;
import org.whispersystems.textsecure.api.messages.TextSecureAttachmentPointer;
import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import de.greenrobot.event.EventBus;
import ws.com.google.android.mms.MmsException;
public class AttachmentDownloadJob extends MasterSecretJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = AttachmentDownloadJob.class.getSimpleName();
@Inject transient TextSecureMessageReceiver messageReceiver;
private final long messageId;
private final long partRowId;
private final long partUniqueId;
public AttachmentDownloadJob(Context context, long messageId, AttachmentId attachmentId) {
super(context, JobParameters.newBuilder()
.withGroupId(AttachmentDownloadJob.class.getCanonicalName())
.withRequirement(new MasterSecretRequirement(context))
.withRequirement(new NetworkRequirement(context))
.withRequirement(new MediaNetworkRequirement(context, messageId, attachmentId))
.withPersistence()
.create());
this.messageId = messageId;
this.partRowId = attachmentId.getRowId();
this.partUniqueId = attachmentId.getUniqueId();
}
@Override
public void onAdded() {
}
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
final AttachmentId attachmentId = new AttachmentId(partRowId, partUniqueId);
final Attachment attachment = DatabaseFactory.getAttachmentDatabase(context).getAttachment(attachmentId);
if (attachment == null) {
Log.w(TAG, "attachment no longer exists.");
return;
}
if (!attachment.isInProgress()) {
Log.w(TAG, "Attachment was already downloaded.");
return;
}
Log.w(TAG, "Downloading push part " + attachmentId);
retrieveAttachment(masterSecret, messageId, attachmentId, attachment);
MessageNotifier.updateNotification(context, masterSecret);
}
@Override
public void onCanceled() {
final AttachmentId attachmentId = new AttachmentId(partRowId, partUniqueId);
markFailed(messageId, attachmentId);
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
return (exception instanceof PushNetworkException);
}
private void retrieveAttachment(MasterSecret masterSecret,
long messageId,
final AttachmentId attachmentId,
final Attachment attachment)
throws IOException
{
AttachmentDatabase database = DatabaseFactory.getAttachmentDatabase(context);
File attachmentFile = null;
try {
attachmentFile = createTempFile();
TextSecureAttachmentPointer pointer = createAttachmentPointer(masterSecret, attachment);
InputStream stream = messageReceiver.retrieveAttachment(pointer, attachmentFile, new ProgressListener() {
@Override
public void onAttachmentProgress(long total, long progress) {
EventBus.getDefault().postSticky(new PartProgressEvent(attachment, total, progress));
}
});
database.insertAttachmentsForPlaceholder(masterSecret, messageId, attachmentId, stream);
} catch (InvalidPartException | NonSuccessfulResponseCodeException | InvalidMessageException | MmsException e) {
Log.w(TAG, e);
markFailed(messageId, attachmentId);
} finally {
if (attachmentFile != null)
attachmentFile.delete();
}
}
@VisibleForTesting
TextSecureAttachmentPointer createAttachmentPointer(MasterSecret masterSecret, Attachment attachment)
throws InvalidPartException
{
if (TextUtils.isEmpty(attachment.getLocation())) {
throw new InvalidPartException("empty content id");
}
if (TextUtils.isEmpty(attachment.getKey())) {
throw new InvalidPartException("empty encrypted key");
}
try {
AsymmetricMasterSecret asymmetricMasterSecret = MasterSecretUtil.getAsymmetricMasterSecret(context, masterSecret);
long id = Long.parseLong(attachment.getLocation());
byte[] key = MediaKey.getDecrypted(masterSecret, asymmetricMasterSecret, attachment.getKey());
String relay = null;
if (TextUtils.isEmpty(attachment.getRelay())) {
relay = attachment.getRelay();
}
return new TextSecureAttachmentPointer(id, null, key, relay);
} catch (InvalidMessageException | IOException e) {
Log.w(TAG, e);
throw new InvalidPartException(e);
}
}
private File createTempFile() throws InvalidPartException {
try {
File file = File.createTempFile("push-attachment", "tmp", context.getCacheDir());
file.deleteOnExit();
return file;
} catch (IOException e) {
throw new InvalidPartException(e);
}
}
private void markFailed(long messageId, AttachmentId attachmentId) {
try {
AttachmentDatabase database = DatabaseFactory.getAttachmentDatabase(context);
database.setTransferProgressFailed(attachmentId, messageId);
} catch (MmsException e) {
Log.w(TAG, e);
}
}
@VisibleForTesting static class InvalidPartException extends Exception {
public InvalidPartException(String s) {super(s);}
public InvalidPartException(Exception e) {super(e);}
}
}
| 7,130 | 37.545946 | 135 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/AvatarDownloadJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import org.thoughtcrime.securesms.BuildConfig;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.mms.AttachmentStreamUriLoader.AttachmentModel;
import org.thoughtcrime.securesms.push.TextSecurePushTrustStore;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException;
import org.whispersystems.textsecure.internal.push.PushServiceSocket;
import org.whispersystems.textsecure.internal.util.StaticCredentialsProvider;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class AvatarDownloadJob extends MasterSecretJob {
private static final String TAG = AvatarDownloadJob.class.getSimpleName();
private final byte[] groupId;
public AvatarDownloadJob(Context context, byte[] groupId) {
super(context, JobParameters.newBuilder()
.withRequirement(new MasterSecretRequirement(context))
.withRequirement(new NetworkRequirement(context))
.withPersistence()
.create());
this.groupId = groupId;
}
@Override
public void onAdded() {}
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
GroupDatabase.GroupRecord record = database.getGroup(groupId);
File attachment = null;
try {
if (record != null) {
long avatarId = record.getAvatarId();
byte[] key = record.getAvatarKey();
String relay = record.getRelay();
if (avatarId == -1 || key == null) {
return;
}
attachment = downloadAttachment(relay, avatarId);
Bitmap avatar = BitmapUtil.createScaledBitmap(context, new AttachmentModel(attachment, key), 500, 500);
database.updateAvatar(groupId, avatar);
}
} catch (ExecutionException | NonSuccessfulResponseCodeException e) {
Log.w(TAG, e);
} finally {
if (attachment != null)
attachment.delete();
}
}
@Override
public void onCanceled() {}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof IOException) return true;
return false;
}
private File downloadAttachment(String relay, long contentLocation) throws IOException {
PushServiceSocket socket = new PushServiceSocket(BuildConfig.TEXTSECURE_URL,
new TextSecurePushTrustStore(context),
new StaticCredentialsProvider(TextSecurePreferences.getLocalNumber(context),
TextSecurePreferences.getPushServerPassword(context),
null),
BuildConfig.USER_AGENT);
File destination = File.createTempFile("avatar", "tmp");
destination.deleteOnExit();
socket.retrieveAttachment(relay, contentLocation, destination, null);
return destination;
}
}
| 3,808 | 36.712871 | 136 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/CleanPreKeysJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyStore;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.SignedPreKeyEntity;
import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import static org.thoughtcrime.securesms.dependencies.AxolotlStorageModule.SignedPreKeyStoreFactory;
public class CleanPreKeysJob extends MasterSecretJob implements InjectableType {
private static final String TAG = CleanPreKeysJob.class.getSimpleName();
private static final int ARCHIVE_AGE_DAYS = 15;
@Inject transient TextSecureAccountManager accountManager;
@Inject transient SignedPreKeyStoreFactory signedPreKeyStoreFactory;
public CleanPreKeysJob(Context context) {
super(context, JobParameters.newBuilder()
.withGroupId(CleanPreKeysJob.class.getSimpleName())
.withRequirement(new MasterSecretRequirement(context))
.withRetryCount(5)
.create());
}
@Override
public void onAdded() {
}
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
try {
SignedPreKeyStore signedPreKeyStore = signedPreKeyStoreFactory.create();
SignedPreKeyEntity currentSignedPreKey = accountManager.getSignedPreKey();
if (currentSignedPreKey == null) return;
SignedPreKeyRecord currentRecord = signedPreKeyStore.loadSignedPreKey(currentSignedPreKey.getKeyId());
List<SignedPreKeyRecord> allRecords = signedPreKeyStore.loadSignedPreKeys();
LinkedList<SignedPreKeyRecord> oldRecords = removeRecordFrom(currentRecord, allRecords);
Collections.sort(oldRecords, new SignedPreKeySorter());
Log.w(TAG, "Old signed prekey record count: " + oldRecords.size());
boolean foundAgedRecord = false;
for (SignedPreKeyRecord oldRecord : oldRecords) {
long archiveDuration = System.currentTimeMillis() - oldRecord.getTimestamp();
if (archiveDuration >= TimeUnit.DAYS.toMillis(ARCHIVE_AGE_DAYS)) {
if (!foundAgedRecord) {
foundAgedRecord = true;
} else {
Log.w(TAG, "Removing signed prekey record: " + oldRecord.getId() + " with timestamp: " + oldRecord.getTimestamp());
signedPreKeyStore.removeSignedPreKey(oldRecord.getId());
}
}
}
} catch (InvalidKeyIdException e) {
Log.w(TAG, e);
}
}
@Override
public boolean onShouldRetryThrowable(Exception throwable) {
if (throwable instanceof NonSuccessfulResponseCodeException) return false;
if (throwable instanceof PushNetworkException) return true;
return false;
}
@Override
public void onCanceled() {
Log.w(TAG, "Failed to execute clean signed prekeys task.");
}
private LinkedList<SignedPreKeyRecord> removeRecordFrom(SignedPreKeyRecord currentRecord,
List<SignedPreKeyRecord> records)
{
LinkedList<SignedPreKeyRecord> others = new LinkedList<>();
for (SignedPreKeyRecord record : records) {
if (record.getId() != currentRecord.getId()) {
others.add(record);
}
}
return others;
}
private static class SignedPreKeySorter implements Comparator<SignedPreKeyRecord> {
@Override
public int compare(SignedPreKeyRecord lhs, SignedPreKeyRecord rhs) {
if (lhs.getTimestamp() > rhs.getTimestamp()) return -1;
else if (lhs.getTimestamp() < rhs.getTimestamp()) return 1;
else return 0;
}
}
}
| 4,462 | 35.284553 | 127 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/ContextJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import org.whispersystems.jobqueue.Job;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.dependencies.ContextDependent;
public abstract class ContextJob extends Job implements ContextDependent {
protected transient Context context;
protected ContextJob(Context context, JobParameters parameters) {
super(parameters);
this.context = context;
}
public void setContext(Context context) {
this.context = context;
}
protected Context getContext() {
return context;
}
}
| 610 | 22.5 | 74 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/CreateSignedPreKeyJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
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.SignedPreKeyRecord;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import javax.inject.Inject;
public class CreateSignedPreKeyJob extends MasterSecretJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = CreateSignedPreKeyJob.class.getSimpleName();
@Inject transient TextSecureAccountManager accountManager;
public CreateSignedPreKeyJob(Context context) {
super(context, JobParameters.newBuilder()
.withPersistence()
.withRequirement(new NetworkRequirement(context))
.withRequirement(new MasterSecretRequirement(context))
.withGroupId(CreateSignedPreKeyJob.class.getSimpleName())
.create());
}
@Override
public void onAdded() {}
@Override
public void onRun(MasterSecret masterSecret) throws IOException {
if (TextSecurePreferences.isSignedPreKeyRegistered(context)) {
Log.w(TAG, "Signed prekey already registered...");
return;
}
IdentityKeyPair identityKeyPair = IdentityKeyUtil.getIdentityKeyPair(context);
SignedPreKeyRecord signedPreKeyRecord = PreKeyUtil.generateSignedPreKey(context, identityKeyPair);
accountManager.setSignedPreKey(signedPreKeyRecord);
TextSecurePreferences.setSignedPreKeyRegistered(context, true);
}
@Override
public void onCanceled() {}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof PushNetworkException) return true;
return false;
}
}
| 2,440 | 35.984848 | 102 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/DeliveryReceiptJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import javax.inject.Inject;
import static org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
public class DeliveryReceiptJob extends ContextJob implements InjectableType {
private static final String TAG = DeliveryReceiptJob.class.getSimpleName();
@Inject transient TextSecureMessageSenderFactory messageSenderFactory;
private final String destination;
private final long timestamp;
private final String relay;
public DeliveryReceiptJob(Context context, String destination, long timestamp, String relay) {
super(context, JobParameters.newBuilder()
.withRequirement(new NetworkRequirement(context))
.withPersistence()
.withRetryCount(50)
.create());
this.destination = destination;
this.timestamp = timestamp;
this.relay = relay;
}
@Override
public void onAdded() {}
@Override
public void onRun() throws IOException {
Log.w("DeliveryReceiptJob", "Sending delivery receipt...");
TextSecureMessageSender messageSender = messageSenderFactory.create();
TextSecureAddress textSecureAddress = new TextSecureAddress(destination, Optional.fromNullable(relay));
messageSender.sendDeliveryReceipt(textSecureAddress, timestamp);
}
@Override
public void onCanceled() {
Log.w(TAG, "Failed to send receipt after retry exhausted!");
}
@Override
public boolean onShouldRetry(Exception exception) {
Log.w(TAG, exception);
if (exception instanceof NonSuccessfulResponseCodeException) return false;
if (exception instanceof PushNetworkException) return true;
return false;
}
}
| 2,444 | 33.928571 | 115 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/DirectoryRefreshJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.SecurityEvent;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.util.DirectoryHelper;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
public class DirectoryRefreshJob extends ContextJob {
@Nullable private transient Recipients recipients;
@Nullable private transient MasterSecret masterSecret;
public DirectoryRefreshJob(@NonNull Context context) {
this(context, null, null);
}
public DirectoryRefreshJob(@NonNull Context context,
@Nullable MasterSecret masterSecret,
@Nullable Recipients recipients)
{
super(context, JobParameters.newBuilder()
.withGroupId(DirectoryRefreshJob.class.getSimpleName())
.withRequirement(new NetworkRequirement(context))
.create());
this.recipients = recipients;
this.masterSecret = masterSecret;
}
@Override
public void onAdded() {}
@Override
public void onRun() throws IOException {
Log.w("DirectoryRefreshJob", "DirectoryRefreshJob.onRun()");
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Directory Refresh");
try {
wakeLock.acquire();
if (recipients == null) {
DirectoryHelper.refreshDirectory(context, KeyCachingService.getMasterSecret(context));
} else {
DirectoryHelper.refreshDirectoryFor(context, masterSecret, recipients, TextSecurePreferences.getLocalNumber(context));
}
SecurityEvent.broadcastSecurityUpdateEvent(context);
} finally {
if (wakeLock.isHeld()) wakeLock.release();
}
}
@Override
public boolean onShouldRetry(Exception exception) {
if (exception instanceof PushNetworkException) return true;
return false;
}
@Override
public void onCanceled() {}
}
| 2,612 | 34.310811 | 126 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/GcmRefreshJob.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.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager;
import org.thoughtcrime.redphone.signaling.UnauthorizedException;
import org.thoughtcrime.securesms.PlayServicesProblemActivity;
import org.thoughtcrime.securesms.R;
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.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureAccountManager;
import org.whispersystems.textsecure.api.push.exceptions.NonSuccessfulResponseCodeException;
import javax.inject.Inject;
public class GcmRefreshJob extends ContextJob implements InjectableType {
private static final String TAG = GcmRefreshJob.class.getSimpleName();
public static final String REGISTRATION_ID = "312334754206";
@Inject transient TextSecureAccountManager textSecureAccountManager;
@Inject transient RedPhoneAccountManager redPhoneAccountManager;
public GcmRefreshJob(Context context) {
super(context, JobParameters.newBuilder().withRequirement(new NetworkRequirement(context)).create());
}
@Override
public void onAdded() {}
@Override
public void onRun() throws Exception {
String registrationId = TextSecurePreferences.getGcmRegistrationId(context);
if (registrationId == null) {
Log.w(TAG, "GCM registrationId expired, reregistering...");
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (result != ConnectionResult.SUCCESS) {
notifyGcmFailure();
} else {
String gcmId = GoogleCloudMessaging.getInstance(context).register(REGISTRATION_ID);
textSecureAccountManager.setGcmId(Optional.of(gcmId));
try {
redPhoneAccountManager.setGcmId(Optional.of(gcmId));
} catch (UnauthorizedException e) {
Log.w(TAG, e);
}
TextSecurePreferences.setGcmRegistrationId(context, gcmId);
TextSecurePreferences.setWebsocketRegistered(context, true);
}
}
}
@Override
public void onCanceled() {
Log.w(TAG, "GCM reregistration failed after retry attempt exhaustion!");
}
@Override
public boolean onShouldRetry(Exception throwable) {
if (throwable instanceof NonSuccessfulResponseCodeException) return false;
return true;
}
private void notifyGcmFailure() {
Intent intent = new Intent(context, PlayServicesProblemActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1122, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.icon_notification);
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_action_warning_red));
builder.setContentTitle(context.getString(R.string.GcmRefreshJob_Permanent_Signal_communication_failure));
builder.setContentText(context.getString(R.string.GcmRefreshJob_Signal_was_unable_to_register_with_Google_Play_Services));
builder.setTicker(context.getString(R.string.GcmRefreshJob_Permanent_Signal_communication_failure));
builder.setVibrate(new long[] {0, 1000});
builder.setContentIntent(pendingIntent);
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE))
.notify(12, builder.build());
}
}
| 4,752 | 39.623932 | 131 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MasterSecretDecryptJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterCipher;
import org.thoughtcrime.securesms.crypto.AsymmetricMasterSecret;
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.database.MmsDatabase;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.model.MessageRecord;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.libaxolotl.InvalidMessageException;
import java.io.IOException;
public class MasterSecretDecryptJob extends MasterSecretJob {
private static final long serialVersionUID = 1L;
private static final String TAG = MasterSecretDecryptJob.class.getSimpleName();
public MasterSecretDecryptJob(Context context) {
super(context, JobParameters.newBuilder()
.withRequirement(new MasterSecretRequirement(context))
.create());
}
@Override
public void onRun(MasterSecret masterSecret) {
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
SmsDatabase.Reader smsReader = smsDatabase.getDecryptInProgressMessages(masterSecret);
SmsMessageRecord smsRecord;
while ((smsRecord = smsReader.getNext()) != null) {
try {
String body = getAsymmetricDecryptedBody(masterSecret, smsRecord.getBody().getBody());
smsDatabase.updateMessageBody(new MasterSecretUnion(masterSecret), smsRecord.getId(), body);
} catch (InvalidMessageException e) {
Log.w(TAG, e);
}
}
MmsDatabase mmsDatabase = DatabaseFactory.getMmsDatabase(context);
MmsDatabase.Reader mmsReader = mmsDatabase.getDecryptInProgressMessages(masterSecret);
MessageRecord mmsRecord;
while ((mmsRecord = mmsReader.getNext()) != null) {
try {
String body = getAsymmetricDecryptedBody(masterSecret, mmsRecord.getBody().getBody());
mmsDatabase.updateMessageBody(new MasterSecretUnion(masterSecret), mmsRecord.getId(), body);
} catch (InvalidMessageException e) {
Log.w(TAG, e);
}
}
smsReader.close();
mmsReader.close();
MessageNotifier.updateNotification(context, masterSecret);
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
return false;
}
@Override
public void onAdded() {
}
@Override
public void onCanceled() {
}
private String getAsymmetricDecryptedBody(MasterSecret masterSecret, String body)
throws InvalidMessageException
{
try {
AsymmetricMasterSecret asymmetricMasterSecret = MasterSecretUtil.getAsymmetricMasterSecret(context, masterSecret);
AsymmetricMasterCipher asymmetricMasterCipher = new AsymmetricMasterCipher(asymmetricMasterSecret);
if (TextUtils.isEmpty(body)) return "";
else return asymmetricMasterCipher.decryptBody(body);
} catch (IOException e) {
throw new InvalidMessageException(e);
}
}
}
| 3,595 | 33.576923 | 120 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MasterSecretJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.whispersystems.jobqueue.JobParameters;
public abstract class MasterSecretJob extends ContextJob {
public MasterSecretJob(Context context, JobParameters parameters) {
super(context, parameters);
}
@Override
public void onRun() throws Exception {
MasterSecret masterSecret = getMasterSecret();
onRun(masterSecret);
}
@Override
public boolean onShouldRetry(Exception exception) {
if (exception instanceof RequirementNotMetException) return true;
return onShouldRetryThrowable(exception);
}
public abstract void onRun(MasterSecret masterSecret) throws Exception;
public abstract boolean onShouldRetryThrowable(Exception exception);
private MasterSecret getMasterSecret() throws RequirementNotMetException {
MasterSecret masterSecret = KeyCachingService.getMasterSecret(context);
if (masterSecret == null) throw new RequirementNotMetException();
else return masterSecret;
}
protected static class RequirementNotMetException extends Exception {}
}
| 1,232 | 29.825 | 76 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MmsDownloadJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.attachments.UriAttachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.mms.ApnUnavailableException;
import org.thoughtcrime.securesms.mms.CompatMmsConnection;
import org.thoughtcrime.securesms.mms.IncomingMediaMessage;
import org.thoughtcrime.securesms.mms.MmsRadioException;
import org.thoughtcrime.securesms.mms.PartParser;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.providers.SingleUseBlobProvider;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.DuplicateMessageException;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.LegacyMessageException;
import org.whispersystems.libaxolotl.NoSessionException;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import ws.com.google.android.mms.ContentType;
import ws.com.google.android.mms.MmsException;
import ws.com.google.android.mms.pdu.EncodedStringValue;
import ws.com.google.android.mms.pdu.NotificationInd;
import ws.com.google.android.mms.pdu.PduBody;
import ws.com.google.android.mms.pdu.PduPart;
import ws.com.google.android.mms.pdu.RetrieveConf;
public class MmsDownloadJob extends MasterSecretJob {
private static final String TAG = MmsDownloadJob.class.getSimpleName();
private final long messageId;
private final long threadId;
private final boolean automatic;
public MmsDownloadJob(Context context, long messageId, long threadId, boolean automatic) {
super(context, JobParameters.newBuilder()
.withPersistence()
.withRequirement(new MasterSecretRequirement(context))
.withRequirement(new NetworkRequirement(context))
.withGroupId("mms-operation")
.withWakeLock(true, 30, TimeUnit.SECONDS)
.create());
this.messageId = messageId;
this.threadId = threadId;
this.automatic = automatic;
}
@Override
public void onAdded() {
if (automatic && KeyCachingService.getMasterSecret(context) == null) {
DatabaseFactory.getMmsDatabase(context).markIncomingNotificationReceived(threadId);
MessageNotifier.updateNotification(context, null);
}
}
@Override
public void onRun(MasterSecret masterSecret) {
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
Optional<NotificationInd> notification = database.getNotification(messageId);
if (!notification.isPresent()) {
Log.w(TAG, "No notification for ID: " + messageId);
return;
}
try {
if (notification.get().getContentLocation() == null) {
throw new MmsException("Notification content location was null.");
}
database.markDownloadState(messageId, MmsDatabase.Status.DOWNLOAD_CONNECTING);
String contentLocation = new String(notification.get().getContentLocation());
byte[] transactionId = notification.get().getTransactionId();
Log.w(TAG, "Downloading mms at " + Uri.parse(contentLocation).getHost());
RetrieveConf retrieveConf = new CompatMmsConnection(context).retrieve(contentLocation, transactionId);
if (retrieveConf == null) {
throw new MmsException("RetrieveConf was null");
}
storeRetrievedMms(masterSecret, contentLocation, messageId, threadId, retrieveConf);
} catch (ApnUnavailableException e) {
Log.w(TAG, e);
handleDownloadError(masterSecret, messageId, threadId, MmsDatabase.Status.DOWNLOAD_APN_UNAVAILABLE,
automatic);
} catch (MmsException e) {
Log.w(TAG, e);
handleDownloadError(masterSecret, messageId, threadId,
MmsDatabase.Status.DOWNLOAD_HARD_FAILURE,
automatic);
} catch (MmsRadioException | IOException e) {
Log.w(TAG, e);
handleDownloadError(masterSecret, messageId, threadId,
MmsDatabase.Status.DOWNLOAD_SOFT_FAILURE,
automatic);
} catch (DuplicateMessageException e) {
Log.w(TAG, e);
database.markAsDecryptDuplicate(messageId, threadId);
} catch (LegacyMessageException e) {
Log.w(TAG, e);
database.markAsLegacyVersion(messageId, threadId);
} catch (NoSessionException e) {
Log.w(TAG, e);
database.markAsNoSession(messageId, threadId);
} catch (InvalidMessageException e) {
Log.w(TAG, e);
database.markAsDecryptFailed(messageId, threadId);
}
}
@Override
public void onCanceled() {
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
database.markDownloadState(messageId, MmsDatabase.Status.DOWNLOAD_SOFT_FAILURE);
if (automatic) {
database.markIncomingNotificationReceived(threadId);
MessageNotifier.updateNotification(context, null, threadId);
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
return false;
}
private void storeRetrievedMms(MasterSecret masterSecret, String contentLocation,
long messageId, long threadId, RetrieveConf retrieved)
throws MmsException, NoSessionException, DuplicateMessageException, InvalidMessageException,
LegacyMessageException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
SingleUseBlobProvider provider = SingleUseBlobProvider.getInstance();
String from = null;
List<String> to = new LinkedList<>();
List<String> cc = new LinkedList<>();
String body = null;
List<Attachment> attachments = new LinkedList<>();
if (retrieved.getFrom() != null) {
from = Util.toIsoString(retrieved.getFrom().getTextString());
}
if (retrieved.getTo() != null) {
for (EncodedStringValue toValue : retrieved.getTo()) {
to.add(Util.toIsoString(toValue.getTextString()));
}
}
if (retrieved.getCc() != null) {
for (EncodedStringValue ccValue : retrieved.getCc()) {
cc.add(Util.toIsoString(ccValue.getTextString()));
}
}
if (retrieved.getBody() != null) {
body = PartParser.getMessageText(retrieved.getBody());
PduBody media = PartParser.getSupportedMediaParts(retrieved.getBody());
for (int i=0;i<media.getPartsNum();i++) {
PduPart part = media.getPart(i);
if (part.getData() != null) {
Uri uri = provider.createUri(part.getData());
attachments.add(new UriAttachment(uri, Util.toIsoString(part.getContentType()),
AttachmentDatabase.TRANSFER_PROGRESS_DONE,
part.getData().length));
}
}
}
IncomingMediaMessage message = new IncomingMediaMessage(from, to, cc, body, retrieved.getDate() * 1000L, attachments);
Pair<Long, Long> messageAndThreadId = database.insertMessageInbox(new MasterSecretUnion(masterSecret),
message, contentLocation, threadId);
database.delete(messageId);
MessageNotifier.updateNotification(context, masterSecret, messageAndThreadId.second);
}
private void handleDownloadError(MasterSecret masterSecret, long messageId, long threadId,
int downloadStatus, boolean automatic)
{
MmsDatabase db = DatabaseFactory.getMmsDatabase(context);
db.markDownloadState(messageId, downloadStatus);
if (automatic) {
db.markIncomingNotificationReceived(threadId);
MessageNotifier.updateNotification(context, masterSecret, threadId);
}
}
}
| 8,677 | 39.175926 | 123 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MmsReceiveJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobParameters;
import ws.com.google.android.mms.pdu.GenericPdu;
import ws.com.google.android.mms.pdu.NotificationInd;
import ws.com.google.android.mms.pdu.PduHeaders;
import ws.com.google.android.mms.pdu.PduParser;
public class MmsReceiveJob extends ContextJob {
private static final String TAG = MmsReceiveJob.class.getSimpleName();
private final byte[] data;
public MmsReceiveJob(Context context, byte[] data) {
super(context, JobParameters.newBuilder()
.withWakeLock(true)
.withPersistence().create());
this.data = data;
}
@Override
public void onAdded() {
}
@Override
public void onRun() {
if (data == null) {
Log.w(TAG, "Received NULL pdu, ignoring...");
return;
}
PduParser parser = new PduParser(data);
GenericPdu pdu = null;
try {
pdu = parser.parse();
} catch (RuntimeException e) {
Log.w(TAG, e);
}
if (isNotification(pdu) && !isBlocked(pdu)) {
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
Pair<Long, Long> messageAndThreadId = database.insertMessageInbox((NotificationInd)pdu);
Log.w(TAG, "Inserted received MMS notification...");
ApplicationContext.getInstance(context)
.getJobManager()
.add(new MmsDownloadJob(context,
messageAndThreadId.first,
messageAndThreadId.second,
true));
} else if (isNotification(pdu)) {
Log.w(TAG, "*** Received blocked MMS, ignoring...");
}
}
@Override
public void onCanceled() {
// TODO
}
@Override
public boolean onShouldRetry(Exception exception) {
return false;
}
private boolean isBlocked(GenericPdu pdu) {
if (pdu.getFrom() != null && pdu.getFrom().getTextString() != null) {
Recipients recipients = RecipientFactory.getRecipientsFromString(context, Util.toIsoString(pdu.getFrom().getTextString()), false);
return recipients.isBlocked();
}
return false;
}
private boolean isNotification(GenericPdu pdu) {
return pdu != null && pdu.getMessageType() == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND;
}
}
| 2,831 | 28.810526 | 136 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MmsSendJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
import org.thoughtcrime.securesms.database.ThreadDatabase.DistributionTypes;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.mms.CompatMmsConnection;
import org.thoughtcrime.securesms.mms.MediaConstraints;
import org.thoughtcrime.securesms.mms.MmsSendResult;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.mms.PartAuthority;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException;
import org.thoughtcrime.securesms.transport.UndeliverableMessageException;
import org.thoughtcrime.securesms.util.Hex;
import org.thoughtcrime.securesms.util.NumberUtil;
import org.thoughtcrime.securesms.util.SmilUtil;
import org.thoughtcrime.securesms.util.TelephonyUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import ws.com.google.android.mms.ContentType;
import ws.com.google.android.mms.MmsException;
import ws.com.google.android.mms.pdu.CharacterSets;
import ws.com.google.android.mms.pdu.EncodedStringValue;
import ws.com.google.android.mms.pdu.PduBody;
import ws.com.google.android.mms.pdu.PduComposer;
import ws.com.google.android.mms.pdu.PduHeaders;
import ws.com.google.android.mms.pdu.PduPart;
import ws.com.google.android.mms.pdu.SendConf;
import ws.com.google.android.mms.pdu.SendReq;
public class MmsSendJob extends SendJob {
private static final long serialVersionUID = 0L;
private static final String TAG = MmsSendJob.class.getSimpleName();
private final long messageId;
public MmsSendJob(Context context, long messageId) {
super(context, JobParameters.newBuilder()
.withGroupId("mms-operation")
.withRequirement(new NetworkRequirement(context))
.withRequirement(new MasterSecretRequirement(context))
.withPersistence()
.create());
this.messageId = messageId;
}
@Override
public void onAdded() {
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
database.markAsSending(messageId);
}
@Override
public void onSend(MasterSecret masterSecret) throws MmsException, NoSuchMessageException, IOException {
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
OutgoingMediaMessage message = database.getOutgoingMessage(masterSecret, messageId);
try {
SendReq pdu = constructSendPdu(masterSecret, message);
validateDestinations(message, pdu);
final byte[] pduBytes = getPduBytes(pdu);
final SendConf sendConf = new CompatMmsConnection(context).send(pduBytes);
final MmsSendResult result = getSendResult(sendConf, pdu);
database.markAsSent(messageId);
markAttachmentsUploaded(messageId, message.getAttachments());
} catch (UndeliverableMessageException | IOException e) {
Log.w(TAG, e);
database.markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
} catch (InsecureFallbackApprovalException e) {
Log.w(TAG, e);
database.markAsPendingInsecureSmsFallback(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
return false;
}
@Override
public void onCanceled() {
DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
private byte[] getPduBytes(SendReq message)
throws IOException, UndeliverableMessageException, InsecureFallbackApprovalException
{
String number = TelephonyUtil.getManager(context).getLine1Number();
message.setBody(SmilUtil.getSmilBody(message.getBody()));
if (!TextUtils.isEmpty(number)) {
message.setFrom(new EncodedStringValue(number));
}
byte[] pduBytes = new PduComposer(context, message).make();
if (pduBytes == null) {
throw new UndeliverableMessageException("PDU composition failed, null payload");
}
return pduBytes;
}
private MmsSendResult getSendResult(SendConf conf, SendReq message)
throws UndeliverableMessageException
{
if (conf == null) {
throw new UndeliverableMessageException("No M-Send.conf received in response to send.");
} else if (conf.getResponseStatus() != PduHeaders.RESPONSE_STATUS_OK) {
throw new UndeliverableMessageException("Got bad response: " + conf.getResponseStatus());
} else if (isInconsistentResponse(message, conf)) {
throw new UndeliverableMessageException("Mismatched response!");
} else {
return new MmsSendResult(conf.getMessageId(), conf.getResponseStatus());
}
}
private boolean isInconsistentResponse(SendReq message, SendConf response) {
Log.w(TAG, "Comparing: " + Hex.toString(message.getTransactionId()));
Log.w(TAG, "With: " + Hex.toString(response.getTransactionId()));
return !Arrays.equals(message.getTransactionId(), response.getTransactionId());
}
private void validateDestinations(EncodedStringValue[] destinations) throws UndeliverableMessageException {
if (destinations == null) return;
for (EncodedStringValue destination : destinations) {
if (destination == null || !NumberUtil.isValidSmsOrEmail(destination.getString())) {
throw new UndeliverableMessageException("Invalid destination: " +
(destination == null ? null : destination.getString()));
}
}
}
private void validateDestinations(OutgoingMediaMessage media, SendReq message) throws UndeliverableMessageException {
validateDestinations(message.getTo());
validateDestinations(message.getCc());
validateDestinations(message.getBcc());
if (message.getTo() == null && message.getCc() == null && message.getBcc() == null) {
throw new UndeliverableMessageException("No to, cc, or bcc specified!");
}
if (media.isSecure()) {
throw new UndeliverableMessageException("Attempt to send encrypted MMS?");
}
}
private SendReq constructSendPdu(MasterSecret masterSecret, OutgoingMediaMessage message)
throws UndeliverableMessageException
{
SendReq sendReq = new SendReq();
PduBody body = new PduBody();
List<String> numbers = message.getRecipients().toNumberStringList(true);
for (String number : numbers) {
if (message.getDistributionType() == DistributionTypes.CONVERSATION) {
sendReq.addTo(new EncodedStringValue(Util.toIsoBytes(number)));
} else {
sendReq.addBcc(new EncodedStringValue(Util.toIsoBytes(number)));
}
}
sendReq.setDate(message.getSentTimeMillis() / 1000L);
if (!TextUtils.isEmpty(message.getBody())) {
PduPart part = new PduPart();
part.setData(Util.toUtf8Bytes(message.getBody()));
part.setCharset(CharacterSets.UTF_8);
part.setContentType(ContentType.TEXT_PLAIN.getBytes());
part.setContentId((System.currentTimeMillis()+"").getBytes());
part.setName(("Text"+System.currentTimeMillis()).getBytes());
body.addPart(part);
}
List<Attachment> scaledAttachments = scaleAttachments(masterSecret, MediaConstraints.MMS_CONSTRAINTS, message.getAttachments());
for (Attachment attachment : scaledAttachments) {
try {
if (attachment.getDataUri() == null) throw new IOException("Assertion failed, attachment for outgoing MMS has no data!");
PduPart part = new PduPart();
part.setData(Util.readFully(PartAuthority.getAttachmentStream(context, masterSecret, attachment.getDataUri())));
part.setContentType(Util.toIsoBytes(attachment.getContentType()));
part.setContentId((System.currentTimeMillis() + "").getBytes());
part.setName((System.currentTimeMillis() + "").getBytes());
body.addPart(part);
} catch (IOException e) {
Log.w(TAG, e);
}
}
sendReq.setBody(body);
return sendReq;
}
private void notifyMediaMessageDeliveryFailed(Context context, long messageId) {
long threadId = DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(messageId);
Recipients recipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId);
if (recipients != null) {
MessageNotifier.notifyMessageDeliveryFailed(context, recipients, threadId);
}
}
}
| 9,446 | 38.860759 | 132 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MultiDeviceContactUpdateJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.util.Log;
import org.thoughtcrime.securesms.contacts.ContactAccessor;
import org.thoughtcrime.securesms.contacts.ContactAccessor.ContactData;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment;
import org.whispersystems.textsecure.api.messages.TextSecureAttachmentStream;
import org.whispersystems.textsecure.api.messages.multidevice.DeviceContact;
import org.whispersystems.textsecure.api.messages.multidevice.DeviceContactsOutputStream;
import org.whispersystems.textsecure.api.messages.multidevice.TextSecureSyncMessage;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import javax.inject.Inject;
public class MultiDeviceContactUpdateJob extends MasterSecretJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = MultiDeviceContactUpdateJob.class.getSimpleName();
@Inject transient TextSecureMessageSenderFactory messageSenderFactory;
public MultiDeviceContactUpdateJob(Context context) {
super(context, JobParameters.newBuilder()
.withRequirement(new NetworkRequirement(context))
.withRequirement(new MasterSecretRequirement(context))
.withGroupId(MultiDeviceContactUpdateJob.class.getSimpleName())
.withPersistence()
.create());
}
@Override
public void onRun(MasterSecret masterSecret)
throws IOException, UntrustedIdentityException, NetworkException
{
TextSecureMessageSender messageSender = messageSenderFactory.create();
File contactDataFile = createTempFile("multidevice-contact-update");
try {
DeviceContactsOutputStream out = new DeviceContactsOutputStream(new FileOutputStream(contactDataFile));
Collection<ContactData> contacts = ContactAccessor.getInstance().getContactsWithPush(context);
for (ContactData contactData : contacts) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactData.id));
String number = contactData.numbers.get(0).number;
Optional<String> name = Optional.fromNullable(contactData.name);
out.write(new DeviceContact(number, name, getAvatar(contactUri)));
}
out.close();
sendUpdate(messageSender, contactDataFile);
} finally {
if (contactDataFile != null) contactDataFile.delete();
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof PushNetworkException) return true;
return false;
}
@Override
public void onAdded() {
}
@Override
public void onCanceled() {
}
private void sendUpdate(TextSecureMessageSender messageSender, File contactsFile)
throws IOException, UntrustedIdentityException, NetworkException
{
if (contactsFile.length() > 0) {
FileInputStream contactsFileStream = new FileInputStream(contactsFile);
TextSecureAttachmentStream attachmentStream = TextSecureAttachment.newStreamBuilder()
.withStream(contactsFileStream)
.withContentType("application/octet-stream")
.withLength(contactsFile.length())
.build();
try {
messageSender.sendMessage(TextSecureSyncMessage.forContacts(attachmentStream));
} catch (IOException ioe) {
throw new NetworkException(ioe);
}
}
}
private Optional<TextSecureAttachmentStream> getAvatar(Uri uri) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
Uri displayPhotoUri = Uri.withAppendedPath(uri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
AssetFileDescriptor fd = context.getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
return Optional.of(TextSecureAttachment.newStreamBuilder()
.withStream(fd.createInputStream())
.withContentType("image/*")
.withLength(fd.getLength())
.build());
} catch (IOException e) {
Log.w(TAG, e);
}
}
Uri photoUri = Uri.withAppendedPath(uri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
if (photoUri == null) {
return Optional.absent();
}
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO,
ContactsContract.CommonDataKinds.Phone.MIMETYPE
}, null, null, null);
try {
if (cursor != null && cursor.moveToNext()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return Optional.of(TextSecureAttachment.newStreamBuilder()
.withStream(new ByteArrayInputStream(data))
.withContentType("image/*")
.withLength(data.length)
.build());
}
}
return Optional.absent();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private File createTempFile(String prefix) throws IOException {
File file = File.createTempFile(prefix, "tmp", context.getCacheDir());
file.deleteOnExit();
return file;
}
private static class NetworkException extends Exception {
public NetworkException(Exception ioe) {
super(ioe);
}
}
}
| 7,360 | 39.005435 | 130 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/MultiDeviceGroupUpdateJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment;
import org.whispersystems.textsecure.api.messages.TextSecureAttachmentStream;
import org.whispersystems.textsecure.api.messages.multidevice.DeviceGroup;
import org.whispersystems.textsecure.api.messages.multidevice.DeviceGroupsOutputStream;
import org.whispersystems.textsecure.api.messages.multidevice.TextSecureSyncMessage;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.inject.Inject;
public class MultiDeviceGroupUpdateJob extends MasterSecretJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = MultiDeviceGroupUpdateJob.class.getSimpleName();
@Inject
transient TextSecureCommunicationModule.TextSecureMessageSenderFactory messageSenderFactory;
public MultiDeviceGroupUpdateJob(Context context) {
super(context, JobParameters.newBuilder()
.withRequirement(new NetworkRequirement(context))
.withRequirement(new MasterSecretRequirement(context))
.withGroupId(MultiDeviceGroupUpdateJob.class.getSimpleName())
.withPersistence()
.create());
}
@Override
public void onRun(MasterSecret masterSecret) throws Exception {
TextSecureMessageSender messageSender = messageSenderFactory.create();
File contactDataFile = createTempFile("multidevice-contact-update");
GroupDatabase.Reader reader = null;
GroupDatabase.GroupRecord record;
try {
DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(new FileOutputStream(contactDataFile));
reader = DatabaseFactory.getGroupDatabase(context).getGroups();
while ((record = reader.getNext()) != null) {
out.write(new DeviceGroup(record.getId(), Optional.fromNullable(record.getTitle()),
record.getMembers(), getAvatar(record.getAvatar())));
}
out.close();
if (contactDataFile.exists() && contactDataFile.length() > 0) {
sendUpdate(messageSender, contactDataFile);
} else {
Log.w(TAG, "No groups present for sync message...");
}
} finally {
if (contactDataFile != null) contactDataFile.delete();
if (reader != null) reader.close();
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof PushNetworkException) return true;
return false;
}
@Override
public void onAdded() {
}
@Override
public void onCanceled() {
}
private void sendUpdate(TextSecureMessageSender messageSender, File contactsFile)
throws IOException, UntrustedIdentityException
{
FileInputStream contactsFileStream = new FileInputStream(contactsFile);
TextSecureAttachmentStream attachmentStream = TextSecureAttachment.newStreamBuilder()
.withStream(contactsFileStream)
.withContentType("application/octet-stream")
.withLength(contactsFile.length())
.build();
messageSender.sendMessage(TextSecureSyncMessage.forGroups(attachmentStream));
}
private Optional<TextSecureAttachmentStream> getAvatar(@Nullable byte[] avatar) {
if (avatar == null) return Optional.absent();
return Optional.of(TextSecureAttachment.newStreamBuilder()
.withStream(new ByteArrayInputStream(avatar))
.withContentType("image/*")
.withLength(avatar.length)
.build());
}
private File createTempFile(String prefix) throws IOException {
File file = File.createTempFile(prefix, "tmp", context.getCacheDir());
file.deleteOnExit();
return file;
}
}
| 5,196 | 38.371212 | 116 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushContentReceiveJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.jobqueue.JobManager;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.libaxolotl.InvalidVersionException;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import org.thoughtcrime.securesms.database.NotInDirectoryException;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
import java.io.IOException;
public class PushContentReceiveJob extends PushReceivedJob {
private static final String TAG = PushContentReceiveJob.class.getSimpleName();
private final String data;
public PushContentReceiveJob(Context context) {
super(context, JobParameters.newBuilder().create());
this.data = null;
}
public PushContentReceiveJob(Context context, String data) {
super(context, JobParameters.newBuilder()
.withPersistence()
.withWakeLock(true)
.create());
this.data = data;
}
@Override
public void onAdded() {}
@Override
public void onRun() {
try {
String sessionKey = TextSecurePreferences.getSignalingKey(context);
TextSecureEnvelope envelope = new TextSecureEnvelope(data, sessionKey);
handle(envelope, true);
} catch (IOException | InvalidVersionException e) {
Log.w(TAG, e);
}
}
@Override
public void onCanceled() {
}
@Override
public boolean onShouldRetry(Exception exception) {
return false;
}
}
| 1,834 | 27.671875 | 85 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushDecryptJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.util.Pair;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
import org.thoughtcrime.securesms.attachments.PointerAttachment;
import org.thoughtcrime.securesms.crypto.IdentityKeyUtil;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.crypto.MasterSecretUnion;
import org.thoughtcrime.securesms.crypto.MasterSecretUtil;
import org.thoughtcrime.securesms.crypto.SecurityEvent;
import org.thoughtcrime.securesms.crypto.storage.TextSecureAxolotlStore;
import org.thoughtcrime.securesms.crypto.storage.TextSecureSessionStore;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.EncryptingSmsDatabase;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
import org.thoughtcrime.securesms.database.PushDatabase;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.groups.GroupMessageProcessor;
import org.thoughtcrime.securesms.mms.IncomingMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage;
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.IncomingEncryptedMessage;
import org.thoughtcrime.securesms.sms.IncomingEndSessionMessage;
import org.thoughtcrime.securesms.sms.IncomingPreKeyBundleMessage;
import org.thoughtcrime.securesms.sms.IncomingTextMessage;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage;
import org.thoughtcrime.securesms.util.Base64;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.libaxolotl.DuplicateMessageException;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.InvalidMessageException;
import org.whispersystems.libaxolotl.InvalidVersionException;
import org.whispersystems.libaxolotl.LegacyMessageException;
import org.whispersystems.libaxolotl.NoSessionException;
import org.whispersystems.libaxolotl.UntrustedIdentityException;
import org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage;
import org.whispersystems.libaxolotl.state.AxolotlStore;
import org.whispersystems.libaxolotl.state.SessionStore;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.crypto.TextSecureCipher;
import org.whispersystems.textsecure.api.messages.TextSecureContent;
import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.whispersystems.textsecure.api.messages.TextSecureGroup;
import org.whispersystems.textsecure.api.messages.multidevice.RequestMessage;
import org.whispersystems.textsecure.api.messages.multidevice.SentTranscriptMessage;
import org.whispersystems.textsecure.api.messages.multidevice.TextSecureSyncMessage;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
import ws.com.google.android.mms.MmsException;
public class PushDecryptJob extends ContextJob {
private static final long serialVersionUID = 2L;
public static final String TAG = PushDecryptJob.class.getSimpleName();
private final long messageId;
private final long smsMessageId;
public PushDecryptJob(Context context, long pushMessageId, String sender) {
this(context, pushMessageId, -1, sender);
}
public PushDecryptJob(Context context, long pushMessageId, long smsMessageId, String sender) {
super(context, JobParameters.newBuilder()
.withPersistence()
.withGroupId("__PUSH_DECRYPT_JOB__")
.withWakeLock(true, 5, TimeUnit.SECONDS)
.create());
this.messageId = pushMessageId;
this.smsMessageId = smsMessageId;
}
@Override
public void onAdded() {}
@Override
public void onRun() throws NoSuchMessageException {
if (!IdentityKeyUtil.hasIdentityKey(context)) {
Log.w(TAG, "Skipping job, waiting for migration...");
MessageNotifier.updateNotification(context, null, true, -2);
return;
}
MasterSecret masterSecret = KeyCachingService.getMasterSecret(context);
PushDatabase database = DatabaseFactory.getPushDatabase(context);
TextSecureEnvelope envelope = database.get(messageId);
Optional<Long> optionalSmsMessageId = smsMessageId > 0 ? Optional.of(smsMessageId) :
Optional.<Long>absent();
MasterSecretUnion masterSecretUnion;
if (masterSecret == null) masterSecretUnion = new MasterSecretUnion(MasterSecretUtil.getAsymmetricMasterSecret(context, null));
else masterSecretUnion = new MasterSecretUnion(masterSecret);
handleMessage(masterSecretUnion, envelope, optionalSmsMessageId);
database.delete(messageId);
}
@Override
public boolean onShouldRetry(Exception exception) {
return false;
}
@Override
public void onCanceled() {
}
private void handleMessage(MasterSecretUnion masterSecret, TextSecureEnvelope envelope, Optional<Long> smsMessageId) {
try {
AxolotlStore axolotlStore = new TextSecureAxolotlStore(context);
TextSecureAddress localAddress = new TextSecureAddress(TextSecurePreferences.getLocalNumber(context));
TextSecureCipher cipher = new TextSecureCipher(localAddress, axolotlStore);
TextSecureContent content = cipher.decrypt(envelope);
if (content.getDataMessage().isPresent()) {
TextSecureDataMessage message = content.getDataMessage().get();
if (message.isEndSession()) handleEndSessionMessage(masterSecret, envelope, message, smsMessageId);
else if (message.isGroupUpdate()) handleGroupMessage(masterSecret, envelope, message, smsMessageId);
else if (message.getAttachments().isPresent()) handleMediaMessage(masterSecret, envelope, message, smsMessageId);
else handleTextMessage(masterSecret, envelope, message, smsMessageId);
} else if (content.getSyncMessage().isPresent()) {
TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
if (syncMessage.getSent().isPresent()) handleSynchronizeSentMessage(masterSecret, envelope, syncMessage.getSent().get(), smsMessageId);
else if (syncMessage.getRequest().isPresent()) handleSynchronizeRequestMessage(masterSecret, syncMessage.getRequest().get());
}
if (envelope.isPreKeyWhisperMessage()) {
ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context));
}
} catch (InvalidVersionException e) {
Log.w(TAG, e);
handleInvalidVersionMessage(masterSecret, envelope, smsMessageId);
} catch (InvalidMessageException | InvalidKeyIdException | InvalidKeyException | MmsException e) {
Log.w(TAG, e);
handleCorruptMessage(masterSecret, envelope, smsMessageId);
} catch (NoSessionException e) {
Log.w(TAG, e);
handleNoSessionMessage(masterSecret, envelope, smsMessageId);
} catch (LegacyMessageException e) {
Log.w(TAG, e);
handleLegacyMessage(masterSecret, envelope, smsMessageId);
} catch (DuplicateMessageException e) {
Log.w(TAG, e);
handleDuplicateMessage(masterSecret, envelope, smsMessageId);
} catch (UntrustedIdentityException e) {
Log.w(TAG, e);
handleUntrustedIdentityMessage(masterSecret, envelope, smsMessageId);
}
}
private void handleEndSessionMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureDataMessage message,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
IncomingTextMessage incomingTextMessage = new IncomingTextMessage(envelope.getSource(),
envelope.getSourceDevice(),
message.getTimestamp(),
"", Optional.<TextSecureGroup>absent());
long threadId;
if (!smsMessageId.isPresent()) {
IncomingEndSessionMessage incomingEndSessionMessage = new IncomingEndSessionMessage(incomingTextMessage);
Pair<Long, Long> messageAndThreadId = smsDatabase.insertMessageInbox(masterSecret, incomingEndSessionMessage);
threadId = messageAndThreadId.second;
} else {
smsDatabase.markAsEndSession(smsMessageId.get());
threadId = smsDatabase.getThreadIdForMessage(smsMessageId.get());
}
SessionStore sessionStore = new TextSecureSessionStore(context);
sessionStore.deleteAllSessions(envelope.getSource());
SecurityEvent.broadcastSecurityUpdateEvent(context);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), threadId);
}
private void handleGroupMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureDataMessage message,
@NonNull Optional<Long> smsMessageId)
{
GroupMessageProcessor.process(context, masterSecret, envelope, message, false);
if (smsMessageId.isPresent()) {
DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
}
}
private void handleSynchronizeSentMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull SentTranscriptMessage message,
@NonNull Optional<Long> smsMessageId)
throws MmsException
{
if (message.getMessage().isGroupUpdate()) {
GroupMessageProcessor.process(context, masterSecret, envelope, message.getMessage(), true);
} else if (message.getMessage().getAttachments().isPresent()) {
handleSynchronizeSentMediaMessage(masterSecret, message, smsMessageId);
} else {
handleSynchronizeSentTextMessage(masterSecret, message, smsMessageId);
}
}
private void handleSynchronizeRequestMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull RequestMessage message)
{
if (message.isContactsRequest()) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new MultiDeviceContactUpdateJob(getContext()));
}
if (message.isGroupsRequest()) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new MultiDeviceGroupUpdateJob(getContext()));
}
}
private void handleMediaMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureDataMessage message,
@NonNull Optional<Long> smsMessageId)
throws MmsException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
String localNumber = TextSecurePreferences.getLocalNumber(context);
IncomingMediaMessage mediaMessage = new IncomingMediaMessage(masterSecret, envelope.getSource(),
localNumber, message.getTimestamp(),
Optional.fromNullable(envelope.getRelay()),
message.getBody(),
message.getGroupInfo(),
message.getAttachments());
Pair<Long, Long> messageAndThreadId = database.insertSecureDecryptedMessageInbox(masterSecret, mediaMessage, -1);
List<DatabaseAttachment> attachments = DatabaseFactory.getAttachmentDatabase(context).getAttachmentsForMessage(messageAndThreadId.first);
for (DatabaseAttachment attachment : attachments) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new AttachmentDownloadJob(context, messageAndThreadId.first,
attachment.getAttachmentId()));
}
if (smsMessageId.isPresent()) {
DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
}
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
}
private void handleSynchronizeSentMediaMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull SentTranscriptMessage message,
@NonNull Optional<Long> smsMessageId)
throws MmsException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
Recipients recipients = getSyncMessageDestination(message);
OutgoingMediaMessage mediaMessage = new OutgoingMediaMessage(recipients, message.getMessage().getBody().orNull(),
PointerAttachment.forPointers(masterSecret, message.getMessage().getAttachments()),
message.getTimestamp(), ThreadDatabase.DistributionTypes.DEFAULT);
mediaMessage = new OutgoingSecureMediaMessage(mediaMessage);
long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
long messageId = database.insertMessageOutbox(masterSecret, mediaMessage, threadId, false);
database.markAsSent(messageId);
database.markAsPush(messageId);
for (DatabaseAttachment attachment : DatabaseFactory.getAttachmentDatabase(context).getAttachmentsForMessage(messageId)) {
ApplicationContext.getInstance(context)
.getJobManager()
.add(new AttachmentDownloadJob(context, messageId, attachment.getAttachmentId()));
}
if (smsMessageId.isPresent()) {
DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
}
}
private void handleTextMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull TextSecureDataMessage message,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
String body = message.getBody().isPresent() ? message.getBody().get() : "";
Pair<Long, Long> messageAndThreadId;
if (smsMessageId.isPresent()) {
messageAndThreadId = database.updateBundleMessageBody(masterSecret, smsMessageId.get(), body);
} else {
IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(),
envelope.getSourceDevice(),
message.getTimestamp(), body,
message.getGroupInfo());
textMessage = new IncomingEncryptedMessage(textMessage, body);
messageAndThreadId = database.insertMessageInbox(masterSecret, textMessage);
}
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
}
private void handleSynchronizeSentTextMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull SentTranscriptMessage message,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
Recipients recipients = getSyncMessageDestination(message);
String body = message.getMessage().getBody().or("");
OutgoingTextMessage outgoingTextMessage = new OutgoingTextMessage(recipients, body);
long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
long messageId = database.insertMessageOutbox(masterSecret, threadId, outgoingTextMessage, false, message.getTimestamp());
database.markAsSent(messageId);
database.markAsPush(messageId);
database.markAsSecure(messageId);
if (smsMessageId.isPresent()) {
database.deleteMessage(smsMessageId.get());
}
}
private void handleInvalidVersionMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
if (!smsMessageId.isPresent()) {
Pair<Long, Long> messageAndThreadId = insertPlaceholder(envelope);
smsDatabase.markAsInvalidVersionKeyExchange(messageAndThreadId.first);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
} else {
smsDatabase.markAsInvalidVersionKeyExchange(smsMessageId.get());
}
}
private void handleCorruptMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
if (!smsMessageId.isPresent()) {
Pair<Long, Long> messageAndThreadId = insertPlaceholder(envelope);
smsDatabase.markAsDecryptFailed(messageAndThreadId.first);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
} else {
smsDatabase.markAsDecryptFailed(smsMessageId.get());
}
}
private void handleNoSessionMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
if (!smsMessageId.isPresent()) {
Pair<Long, Long> messageAndThreadId = insertPlaceholder(envelope);
smsDatabase.markAsNoSession(messageAndThreadId.first);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
} else {
smsDatabase.markAsNoSession(smsMessageId.get());
}
}
private void handleLegacyMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
EncryptingSmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
if (!smsMessageId.isPresent()) {
Pair<Long, Long> messageAndThreadId = insertPlaceholder(envelope);
smsDatabase.markAsLegacyVersion(messageAndThreadId.first);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
} else {
smsDatabase.markAsLegacyVersion(smsMessageId.get());
}
}
private void handleDuplicateMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
// Let's start ignoring these now
// SmsDatabase smsDatabase = DatabaseFactory.getEncryptingSmsDatabase(context);
//
// if (smsMessageId <= 0) {
// Pair<Long, Long> messageAndThreadId = insertPlaceholder(masterSecret, envelope);
// smsDatabase.markAsDecryptDuplicate(messageAndThreadId.first);
// MessageNotifier.updateNotification(context, masterSecret, messageAndThreadId.second);
// } else {
// smsDatabase.markAsDecryptDuplicate(smsMessageId);
// }
}
private void handleUntrustedIdentityMessage(@NonNull MasterSecretUnion masterSecret,
@NonNull TextSecureEnvelope envelope,
@NonNull Optional<Long> smsMessageId)
{
try {
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
Recipients recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false);
long recipientId = recipients.getPrimaryRecipient().getRecipientId();
PreKeyWhisperMessage whisperMessage = new PreKeyWhisperMessage(envelope.getLegacyMessage());
IdentityKey identityKey = whisperMessage.getIdentityKey();
String encoded = Base64.encodeBytes(envelope.getLegacyMessage());
IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(), envelope.getSourceDevice(),
envelope.getTimestamp(), encoded,
Optional.<TextSecureGroup>absent());
if (!smsMessageId.isPresent()) {
IncomingPreKeyBundleMessage bundleMessage = new IncomingPreKeyBundleMessage(textMessage, encoded);
Pair<Long, Long> messageAndThreadId = database.insertMessageInbox(masterSecret, bundleMessage);
database.setMismatchedIdentity(messageAndThreadId.first, recipientId, identityKey);
MessageNotifier.updateNotification(context, masterSecret.getMasterSecret().orNull(), messageAndThreadId.second);
} else {
database.updateMessageBody(masterSecret, smsMessageId.get(), encoded);
database.markAsPreKeyBundle(smsMessageId.get());
database.setMismatchedIdentity(smsMessageId.get(), recipientId, identityKey);
}
} catch (InvalidMessageException | InvalidVersionException e) {
throw new AssertionError(e);
}
}
private Pair<Long, Long> insertPlaceholder(@NonNull TextSecureEnvelope envelope) {
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
IncomingTextMessage textMessage = new IncomingTextMessage(envelope.getSource(), envelope.getSourceDevice(),
envelope.getTimestamp(), "",
Optional.<TextSecureGroup>absent());
textMessage = new IncomingEncryptedMessage(textMessage, "");
return database.insertMessageInbox(textMessage);
}
private Recipients getSyncMessageDestination(SentTranscriptMessage message) {
if (message.getMessage().getGroupInfo().isPresent()) {
return RecipientFactory.getRecipientsFromString(context, GroupUtil.getEncodedId(message.getMessage().getGroupInfo().get().getGroupId()), false);
} else {
return RecipientFactory.getRecipientsFromString(context, message.getDestination().get(), false);
}
}
}
| 24,355 | 49.636175 | 151 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushGroupSendJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
import org.thoughtcrime.securesms.database.documents.NetworkFailure;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.mms.OutgoingGroupMediaMessage;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.RecipientFormattingException;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.transport.UndeliverableMessageException;
import org.thoughtcrime.securesms.util.GroupUtil;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment;
import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
import org.whispersystems.textsecure.api.messages.TextSecureGroup;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
import org.whispersystems.textsecure.api.push.exceptions.NetworkFailureException;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import org.whispersystems.textsecure.internal.push.TextSecureProtos.GroupContext;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import ws.com.google.android.mms.MmsException;
import static org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
public class PushGroupSendJob extends PushSendJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = PushGroupSendJob.class.getSimpleName();
@Inject transient TextSecureMessageSenderFactory messageSenderFactory;
private final long messageId;
private final long filterRecipientId;
public PushGroupSendJob(Context context, long messageId, String destination, long filterRecipientId) {
super(context, JobParameters.newBuilder()
.withPersistence()
.withGroupId(destination)
.withRequirement(new MasterSecretRequirement(context))
.withRequirement(new NetworkRequirement(context))
.withRetryCount(5)
.create());
this.messageId = messageId;
this.filterRecipientId = filterRecipientId;
}
@Override
public void onAdded() {
DatabaseFactory.getMmsDatabase(context)
.markAsSending(messageId);
}
@Override
public void onSend(MasterSecret masterSecret)
throws MmsException, IOException, NoSuchMessageException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
OutgoingMediaMessage message = database.getOutgoingMessage(masterSecret, messageId);
try {
deliver(masterSecret, message, filterRecipientId);
database.markAsPush(messageId);
database.markAsSecure(messageId);
database.markAsSent(messageId);
markAttachmentsUploaded(messageId, message.getAttachments());
} catch (InvalidNumberException | RecipientFormattingException | UndeliverableMessageException e) {
Log.w(TAG, e);
database.markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
} catch (EncapsulatedExceptions e) {
Log.w(TAG, e);
List<NetworkFailure> failures = new LinkedList<>();
for (NetworkFailureException nfe : e.getNetworkExceptions()) {
Recipient recipient = RecipientFactory.getRecipientsFromString(context, nfe.getE164number(), false).getPrimaryRecipient();
failures.add(new NetworkFailure(recipient.getRecipientId()));
}
for (UntrustedIdentityException uie : e.getUntrustedIdentityExceptions()) {
Recipient recipient = RecipientFactory.getRecipientsFromString(context, uie.getE164Number(), false).getPrimaryRecipient();
database.addMismatchedIdentity(messageId, recipient.getRecipientId(), uie.getIdentityKey());
}
database.addFailures(messageId, failures);
database.markAsSentFailed(messageId);
database.markAsPush(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof IOException) return true;
return false;
}
@Override
public void onCanceled() {
DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
}
private void deliver(MasterSecret masterSecret, OutgoingMediaMessage message, long filterRecipientId)
throws IOException, RecipientFormattingException, InvalidNumberException,
EncapsulatedExceptions, UndeliverableMessageException
{
TextSecureMessageSender messageSender = messageSenderFactory.create();
byte[] groupId = GroupUtil.getDecodedId(message.getRecipients().getPrimaryRecipient().getNumber());
Recipients recipients = DatabaseFactory.getGroupDatabase(context).getGroupMembers(groupId, false);
List<TextSecureAttachment> attachments = getAttachmentsFor(masterSecret, message.getAttachments());
List<TextSecureAddress> addresses;
if (filterRecipientId >= 0) addresses = getPushAddresses(filterRecipientId);
else addresses = getPushAddresses(recipients);
if (message.isGroup()) {
OutgoingGroupMediaMessage groupMessage = (OutgoingGroupMediaMessage) message;
GroupContext groupContext = groupMessage.getGroupContext();
TextSecureAttachment avatar = attachments.isEmpty() ? null : attachments.get(0);
TextSecureGroup.Type type = groupMessage.isGroupQuit() ? TextSecureGroup.Type.QUIT : TextSecureGroup.Type.UPDATE;
TextSecureGroup group = new TextSecureGroup(type, groupId, groupContext.getName(), groupContext.getMembersList(), avatar);
TextSecureDataMessage groupDataMessage = new TextSecureDataMessage(message.getSentTimeMillis(), group, null, null);
messageSender.sendMessage(addresses, groupDataMessage);
} else {
TextSecureGroup group = new TextSecureGroup(groupId);
TextSecureDataMessage groupMessage = new TextSecureDataMessage(message.getSentTimeMillis(), group, attachments, message.getBody());
messageSender.sendMessage(addresses, groupMessage);
}
}
private List<TextSecureAddress> getPushAddresses(Recipients recipients) throws InvalidNumberException {
List<TextSecureAddress> addresses = new LinkedList<>();
for (Recipient recipient : recipients.getRecipientsList()) {
addresses.add(getPushAddress(recipient.getNumber()));
}
return addresses;
}
private List<TextSecureAddress> getPushAddresses(long filterRecipientId) throws InvalidNumberException {
List<TextSecureAddress> addresses = new LinkedList<>();
addresses.add(getPushAddress(RecipientFactory.getRecipientForId(context, filterRecipientId, false).getNumber()));
return addresses;
}
}
| 7,851 | 44.651163 | 149 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushMediaSendJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.thoughtcrime.securesms.mms.MediaConstraints;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException;
import org.thoughtcrime.securesms.transport.RetryLaterException;
import org.thoughtcrime.securesms.transport.UndeliverableMessageException;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment;
import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.push.exceptions.UnregisteredUserException;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import ws.com.google.android.mms.MmsException;
import static org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
public class PushMediaSendJob extends PushSendJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = PushMediaSendJob.class.getSimpleName();
@Inject transient TextSecureMessageSenderFactory messageSenderFactory;
private final long messageId;
public PushMediaSendJob(Context context, long messageId, String destination) {
super(context, constructParameters(context, destination));
this.messageId = messageId;
}
@Override
public void onAdded() {
MmsDatabase mmsDatabase = DatabaseFactory.getMmsDatabase(context);
mmsDatabase.markAsSending(messageId);
mmsDatabase.markAsPush(messageId);
}
@Override
public void onSend(MasterSecret masterSecret)
throws RetryLaterException, MmsException, NoSuchMessageException,
UndeliverableMessageException
{
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
OutgoingMediaMessage message = database.getOutgoingMessage(masterSecret, messageId);
try {
deliver(masterSecret, message);
database.markAsPush(messageId);
database.markAsSecure(messageId);
database.markAsSent(messageId);
markAttachmentsUploaded(messageId, message.getAttachments());
} catch (InsecureFallbackApprovalException ifae) {
Log.w(TAG, ifae);
database.markAsPendingInsecureSmsFallback(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
ApplicationContext.getInstance(context).getJobManager().add(new DirectoryRefreshJob(context));
} catch (UntrustedIdentityException uie) {
Log.w(TAG, uie);
Recipients recipients = RecipientFactory.getRecipientsFromString(context, uie.getE164Number(), false);
long recipientId = recipients.getPrimaryRecipient().getRecipientId();
database.addMismatchedIdentity(messageId, recipientId, uie.getIdentityKey());
database.markAsSentFailed(messageId);
database.markAsPush(messageId);
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof RequirementNotMetException) return true;
if (exception instanceof RetryLaterException) return true;
return false;
}
@Override
public void onCanceled() {
DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
private void deliver(MasterSecret masterSecret, OutgoingMediaMessage message)
throws RetryLaterException, InsecureFallbackApprovalException, UntrustedIdentityException,
UndeliverableMessageException
{
if (message.getRecipients() == null ||
message.getRecipients().getPrimaryRecipient() == null ||
message.getRecipients().getPrimaryRecipient().getNumber() == null)
{
throw new UndeliverableMessageException("No destination address.");
}
TextSecureMessageSender messageSender = messageSenderFactory.create();
try {
TextSecureAddress address = getPushAddress(message.getRecipients().getPrimaryRecipient().getNumber());
List<Attachment> scaledAttachments = scaleAttachments(masterSecret, MediaConstraints.PUSH_CONSTRAINTS, message.getAttachments());
List<TextSecureAttachment> attachmentStreams = getAttachmentsFor(masterSecret, scaledAttachments);
TextSecureDataMessage mediaMessage = TextSecureDataMessage.newBuilder()
.withBody(message.getBody())
.withAttachments(attachmentStreams)
.withTimestamp(message.getSentTimeMillis())
.build();
messageSender.sendMessage(address, mediaMessage);
} catch (InvalidNumberException | UnregisteredUserException e) {
Log.w(TAG, e);
throw new InsecureFallbackApprovalException(e);
} catch (FileNotFoundException e) {
Log.w(TAG, e);
throw new UndeliverableMessageException(e);
} catch (IOException e) {
Log.w(TAG, e);
throw new RetryLaterException(e);
}
}
}
| 6,084 | 42.464286 | 145 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushNotificationReceiveJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.dependencies.InjectableType;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.whispersystems.textsecure.api.push.exceptions.PushNetworkException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
public class PushNotificationReceiveJob extends PushReceivedJob implements InjectableType {
private static final String TAG = PushNotificationReceiveJob.class.getSimpleName();
@Inject transient TextSecureMessageReceiver receiver;
public PushNotificationReceiveJob(Context context) {
super(context, JobParameters.newBuilder()
.withRequirement(new NetworkRequirement(context))
.withGroupId("__notification_received")
.withWakeLock(true, 30, TimeUnit.SECONDS).create());
}
@Override
public void onAdded() {}
@Override
public void onRun() throws IOException {
receiver.retrieveMessages(new TextSecureMessageReceiver.MessageReceivedCallback() {
@Override
public void onMessage(TextSecureEnvelope envelope) {
handle(envelope, false);
}
});
}
@Override
public boolean onShouldRetry(Exception e) {
Log.w(TAG, e);
return e instanceof PushNetworkException;
}
@Override
public void onCanceled() {
Log.w(TAG, "***** Failed to download pending message!");
}
}
| 1,725 | 30.381818 | 91 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushReceivedJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.NotInDirectoryException;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.whispersystems.jobqueue.JobManager;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
import org.whispersystems.textsecure.api.push.ContactTokenDetails;
public abstract class PushReceivedJob extends ContextJob {
private static final String TAG = PushReceivedJob.class.getSimpleName();
protected PushReceivedJob(Context context, JobParameters parameters) {
super(context, parameters);
}
public void handle(TextSecureEnvelope envelope, boolean sendExplicitReceipt) {
if (!isActiveNumber(context, envelope.getSource())) {
TextSecureDirectory directory = TextSecureDirectory.getInstance(context);
ContactTokenDetails contactTokenDetails = new ContactTokenDetails();
contactTokenDetails.setNumber(envelope.getSource());
directory.setNumber(contactTokenDetails, true);
Recipients recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false);
ApplicationContext.getInstance(context).getJobManager().add(new DirectoryRefreshJob(context, KeyCachingService.getMasterSecret(context), recipients));
}
if (envelope.isReceipt()) {
handleReceipt(envelope);
} else if (envelope.isPreKeyWhisperMessage() || envelope.isWhisperMessage()) {
handleMessage(envelope, sendExplicitReceipt);
} else {
Log.w(TAG, "Received envelope of unknown type: " + envelope.getType());
}
}
private void handleMessage(TextSecureEnvelope envelope, boolean sendExplicitReceipt) {
Recipients recipients = RecipientFactory.getRecipientsFromString(context, envelope.getSource(), false);
JobManager jobManager = ApplicationContext.getInstance(context).getJobManager();
if (!recipients.isBlocked()) {
long messageId = DatabaseFactory.getPushDatabase(context).insert(envelope);
jobManager.add(new PushDecryptJob(context, messageId, envelope.getSource()));
} else {
Log.w(TAG, "*** Received blocked push message, ignoring...");
}
if (sendExplicitReceipt) {
jobManager.add(new DeliveryReceiptJob(context, envelope.getSource(),
envelope.getTimestamp(),
envelope.getRelay()));
}
}
private void handleReceipt(TextSecureEnvelope envelope) {
Log.w(TAG, String.format("Received receipt: (XXXXX, %d)", envelope.getTimestamp()));
DatabaseFactory.getMmsSmsDatabase(context).incrementDeliveryReceiptCount(envelope.getSource(),
envelope.getTimestamp());
}
private boolean isActiveNumber(Context context, String e164number) {
boolean isActiveNumber;
try {
isActiveNumber = TextSecureDirectory.getInstance(context).isSecureTextSupported(e164number);
} catch (NotInDirectoryException e) {
isActiveNumber = false;
}
return isActiveNumber;
}
}
| 3,505 | 40.247059 | 156 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushSendJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.attachments.Attachment;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.TextSecureDirectory;
import org.thoughtcrime.securesms.events.PartProgressEvent;
import org.thoughtcrime.securesms.jobs.requirements.MasterSecretRequirement;
import org.thoughtcrime.securesms.mms.PartAuthority;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.jobqueue.JobParameters;
import org.whispersystems.jobqueue.requirements.NetworkRequirement;
import org.whispersystems.libaxolotl.util.guava.Optional;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment;
import org.whispersystems.textsecure.api.messages.TextSecureAttachment.ProgressListener;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import de.greenrobot.event.EventBus;
import ws.com.google.android.mms.ContentType;
public abstract class PushSendJob extends SendJob {
private static final String TAG = PushSendJob.class.getSimpleName();
protected PushSendJob(Context context, JobParameters parameters) {
super(context, parameters);
}
protected static JobParameters constructParameters(Context context, String destination) {
JobParameters.Builder builder = JobParameters.newBuilder();
builder.withPersistence();
builder.withGroupId(destination);
builder.withRequirement(new MasterSecretRequirement(context));
builder.withRequirement(new NetworkRequirement(context));
builder.withRetryCount(5);
return builder.create();
}
protected TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
String e164number = Util.canonicalizeNumber(context, number);
String relay = TextSecureDirectory.getInstance(context).getRelay(e164number);
return new TextSecureAddress(e164number, Optional.fromNullable(relay));
}
protected List<TextSecureAttachment> getAttachmentsFor(MasterSecret masterSecret, List<Attachment> parts) {
List<TextSecureAttachment> attachments = new LinkedList<>();
for (final Attachment attachment : parts) {
if (ContentType.isImageType(attachment.getContentType()) ||
ContentType.isAudioType(attachment.getContentType()) ||
ContentType.isVideoType(attachment.getContentType()))
{
try {
if (attachment.getDataUri() == null) throw new IOException("Assertion failed, outgoing attachment has no data!");
InputStream is = PartAuthority.getAttachmentStream(context, masterSecret, attachment.getDataUri());
attachments.add(TextSecureAttachment.newStreamBuilder()
.withStream(is)
.withContentType(attachment.getContentType())
.withLength(attachment.getSize())
.withListener(new ProgressListener() {
@Override
public void onAttachmentProgress(long total, long progress) {
EventBus.getDefault().postSticky(new PartProgressEvent(attachment, total, progress));
}
})
.build());
} catch (IOException ioe) {
Log.w(TAG, "Couldn't open attachment", ioe);
}
}
}
return attachments;
}
protected void notifyMediaMessageDeliveryFailed(Context context, long messageId) {
long threadId = DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(messageId);
Recipients recipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId);
if (threadId != -1 && recipients != null) {
MessageNotifier.notifyMessageDeliveryFailed(context, recipients, threadId);
}
}
}
| 4,440 | 44.783505 | 135 | java |
cryptoguard | cryptoguard-master/Notebook/Custom_Android_Tests/Signal-Android-3.5.0/src/org/thoughtcrime/securesms/jobs/PushTextSendJob.java | package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
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.dependencies.InjectableType;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.recipients.RecipientFactory;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException;
import org.thoughtcrime.securesms.transport.RetryLaterException;
import org.whispersystems.textsecure.api.TextSecureMessageSender;
import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
import org.whispersystems.textsecure.api.push.TextSecureAddress;
import org.whispersystems.textsecure.api.push.exceptions.UnregisteredUserException;
import org.whispersystems.textsecure.api.util.InvalidNumberException;
import java.io.IOException;
import javax.inject.Inject;
import static org.thoughtcrime.securesms.dependencies.TextSecureCommunicationModule.TextSecureMessageSenderFactory;
public class PushTextSendJob extends PushSendJob implements InjectableType {
private static final long serialVersionUID = 1L;
private static final String TAG = PushTextSendJob.class.getSimpleName();
@Inject transient TextSecureMessageSenderFactory messageSenderFactory;
private final long messageId;
public PushTextSendJob(Context context, long messageId, String destination) {
super(context, constructParameters(context, destination));
this.messageId = messageId;
}
@Override
public void onAdded() {
SmsDatabase smsDatabase = DatabaseFactory.getSmsDatabase(context);
smsDatabase.markAsSending(messageId);
smsDatabase.markAsPush(messageId);
}
@Override
public void onSend(MasterSecret masterSecret) throws NoSuchMessageException, RetryLaterException {
EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);
SmsMessageRecord record = database.getMessage(masterSecret, messageId);
try {
Log.w(TAG, "Sending message: " + messageId);
deliver(record);
database.markAsPush(messageId);
database.markAsSecure(messageId);
database.markAsSent(messageId);
} catch (InsecureFallbackApprovalException e) {
Log.w(TAG, e);
database.markAsPendingInsecureSmsFallback(record.getId());
MessageNotifier.notifyMessageDeliveryFailed(context, record.getRecipients(), record.getThreadId());
ApplicationContext.getInstance(context).getJobManager().add(new DirectoryRefreshJob(context));
} catch (UntrustedIdentityException e) {
Log.w(TAG, e);
Recipients recipients = RecipientFactory.getRecipientsFromString(context, e.getE164Number(), false);
long recipientId = recipients.getPrimaryRecipient().getRecipientId();
database.addMismatchedIdentity(record.getId(), recipientId, e.getIdentityKey());
database.markAsSentFailed(record.getId());
database.markAsPush(record.getId());
}
}
@Override
public boolean onShouldRetryThrowable(Exception exception) {
if (exception instanceof RetryLaterException) return true;
return false;
}
@Override
public void onCanceled() {
DatabaseFactory.getSmsDatabase(context).markAsSentFailed(messageId);
long threadId = DatabaseFactory.getSmsDatabase(context).getThreadIdForMessage(messageId);
Recipients recipients = DatabaseFactory.getThreadDatabase(context).getRecipientsForThreadId(threadId);
if (threadId != -1 && recipients != null) {
MessageNotifier.notifyMessageDeliveryFailed(context, recipients, threadId);
}
}
private void deliver(SmsMessageRecord message)
throws UntrustedIdentityException, InsecureFallbackApprovalException, RetryLaterException
{
try {
TextSecureAddress address = getPushAddress(message.getIndividualRecipient().getNumber());
TextSecureMessageSender messageSender = messageSenderFactory.create();
TextSecureDataMessage textSecureMessage = TextSecureDataMessage.newBuilder()
.withTimestamp(message.getDateSent())
.withBody(message.getBody().getBody())
.asEndSessionMessage(message.isEndSession())
.build();
messageSender.sendMessage(address, textSecureMessage);
} catch (InvalidNumberException | UnregisteredUserException e) {
Log.w(TAG, e);
throw new InsecureFallbackApprovalException(e);
} catch (IOException e) {
Log.w(TAG, e);
throw new RetryLaterException(e);
}
}
}
| 5,285 | 41.288 | 115 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.