file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Effect.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/sound/Effect.java |
/**
* org.hermit.android.sound: sound effects for Android.
*
* These classes provide functions to help apps manage their sound effects.
*
* <br>Copyright 2009-2010 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.sound;
/**
* Class representing a specific sound effect. Apps can create an
* instance by calling {@link Player#addEffect(int)}, or
* {@link Player#addEffect(int, float)}.
*/
public class Effect
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a sound effect description. This constructor is not public;
* outside users get an instance by calling {@link Player#addEffect(int)},
* or {@link Player#addEffect(int, float)}.
*
* @param player The Player this effect belongs to.
* @param resId Resource ID of the sound sample for this effect.
* @param vol Base volume for this effect (used to modify the
* sound file's inherent volume, if needed). 1 is
* normal.
*/
Effect(Player player, int resId, float vol) {
soundPlayer = player;
clipResourceId = resId;
playerSoundId = -1;
playVol = vol;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the resource ID of the sound sample for this effect.
*
* @return Resource ID of the sound sample for this effect.
*/
final int getResourceId() {
return clipResourceId;
}
/**
* Get the player's ID for this sound.
*
* @return Player's ID of this effect. -1 f we don't have
* one.
*/
final int getSoundId() {
return playerSoundId;
}
/**
* Set the player's ID for this sound.
*
* @param id Player's ID of this effect. -1 f we don't have
* one.
*/
final void setSoundId(int id) {
playerSoundId = id;
}
/**
* Get the player for this sound.
*
* @return Current player of this effect. null if not playing.
*/
final Player.PoolPlayer getPlayer() {
return player;
}
/**
* Set the player for this sound.
*
* @param p Current player of this effect. null if not playing.
*/
final void setPlayer(Player.PoolPlayer p) {
player = p;
}
/**
* Get the effect's volume.
*
* @return Base volume for this effect.
*/
final float getPlayVol() {
return playVol;
}
/**
* Set the effect's volume.
*
* @param playVol New base volume.
*/
final void setPlayVol(float vol) {
playVol = vol;
}
// ******************************************************************** //
// Playing.
// ******************************************************************** //
/**
* Play this sound effect.
*/
public void play() {
soundPlayer.play(this, playVol, false);
}
/**
* Play this sound effect.
*
* @param rvol Relative volume for this sound, 0 - 1.
*/
public void play(float rvol) {
soundPlayer.play(this, rvol * playVol, false);
}
/**
* Start playing this sound effect in a continuous loop.
*/
public void loop() {
soundPlayer.play(this, playVol, true);
}
/**
* Play this sound effect.
*
* @param rvol Relative volume for this sound, 0 - 1.
* @param loop If true, loop the sound forever.
*/
void play(float rvol, boolean loop) {
soundPlayer.play(this, rvol * playVol, loop);
}
/**
* Stop this sound effect immediately.
*/
public void stop() {
soundPlayer.stop(this);
}
/**
* Determine whether this effect is playing.
*
* @return True if this sound effect is playing.
*/
public final boolean isPlaying() {
return player != null && player.isPlaying(this);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// The player this effect is attached to.
private final Player soundPlayer;
// Base volume for this effect.
private float playVol;
// Resource ID of the effect's audio clip.
private final int clipResourceId;
// Sound ID of this effect in the sound player. -1 if not set; e.g.
// we don't currently have a media connection.
private int playerSoundId;
// The pool player which is playing this effect; null
// if it's not playing.
private Player.PoolPlayer player = null;
}
| 5,529 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DbRow.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/provider/DbRow.java |
/**
* org.hermit.android.provider: classes for building content providers.
*
* These classes are designed to help build content providers in Android.
*
* <br>Copyright 2010-2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.provider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
/**
* Utility class for managing a row from a content provider.
*/
public abstract class DbRow {
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a database row instance from a Cursor.
*
* @param schema Schema of the table the row belongs to.
* @param c Cursor to read the row data from.
*/
protected DbRow(TableSchema schema, Cursor c) {
this(schema, c, schema.getDefaultProjection());
}
/**
* Create a database row instance from a Cursor.
*
* @param schema Schema of the table the row belongs to.
* @param c Cursor to read the row data from.
* @param projection The fields to read.
*/
protected DbRow(TableSchema schema, Cursor c, String[] projection) {
tableSchema = schema;
rowValues = new ContentValues();
DatabaseUtils.cursorRowToContentValues(c, rowValues);
}
// ******************************************************************** //
// Public Accessors.
// ******************************************************************** //
// ******************************************************************** //
// Local Accessors.
// ******************************************************************** //
/**
* Save the contents of this row to the given ContentValues.
*
* @param values Object to write to.
*/
void getValues(ContentValues values) {
values.putAll(rowValues);
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Schema of the table this row belongs to.
@SuppressWarnings("unused")
private final TableSchema tableSchema;
// The values of the fields in this row.
private final ContentValues rowValues;
}
| 2,914 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DatabaseHelper.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/provider/DatabaseHelper.java |
/**
* org.hermit.android.provider: classes for building content providers.
*
* These classes are designed to help build content providers in Android.
*
* <br>Copyright 2010-2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.provider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* This class helps open, create, and upgrade the database file.
*
* <p>Applications may use this class as is, or override it, for example to
* provide a database upgrade handler. If you don't wish to override it,
* nothing need be done. If you wish to subclass it, then create your
* subclass and override {@link TableProvider#getHelper()} to return it.
*/
public class DatabaseHelper
extends SQLiteOpenHelper
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Creater a helper instance.
*
* @param context Application context.
* @param schema Schema for this database.
*/
public DatabaseHelper(Context context, DbSchema schema) {
super(context, schema.getDbName(), null, schema.getDbVersion());
dbSchema = schema;
}
// ******************************************************************** //
// Database Create.
// ******************************************************************** //
/**
* Called when the database is created for the first time. This is
* where the creation of tables and the initial population of the
* tables should happen.
*
* <p>The default implementation creates all the fields specified in
* all of the table schemas. Subclasses may override this, for example
* to add special fields.
*
* @param db The new database.
*/
@Override
public void onCreate(SQLiteDatabase db) {
StringBuilder qb = new StringBuilder();
for (TableSchema t : dbSchema.getDbTables()) {
qb.setLength(0);
qb.append("CREATE TABLE " + t.getTableName() + " ( ");
TableSchema.FieldDesc[] fields = t.getTableFields();
for (int i = 0; i < fields.length; ++i) {
TableSchema.FieldDesc field = fields[i];
if (i > 0)
qb.append(", ");
qb.append(field.name);
qb.append(" ");
qb.append(field.type);
}
qb.append(" );");
db.execSQL(qb.toString());
}
}
// ******************************************************************** //
// Database Upgrade.
// ******************************************************************** //
/**
* Called when the database needs to be upgraded. The implementation
* should use this method to drop tables, add tables, or do anything
* else it needs to upgrade to the new schema version.
*
* <p>The default implementation simply deletes all tables and calls
* {@link #onOpen(SQLiteDatabase)}. Subclasses may override this method
* to do a more intelligent upgrade.
*
* <p>If you add new columns you can use ALTER TABLE to insert them into
* a live table. If you rename or remove columns you can use ALTER TABLE
* to rename the old table, then create the new table and then populate
* the new table with the contents of the old table.
*
* @param db The new database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TableProvider.TAG, "Upgrading database from version " +
oldVersion + " to " + newVersion +
", which will destroy all old data");
for (TableSchema t : dbSchema.getDbTables())
db.execSQL("DROP TABLE IF EXISTS " + t.getTableName());
onCreate(db);
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the database schema.
*
* @return The schema for this database.
*/
protected DbSchema getSchema() {
return dbSchema;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Our database schema.
private final DbSchema dbSchema;
}
| 5,251 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
DbSchema.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/provider/DbSchema.java |
/**
* org.hermit.android.provider: classes for building content providers.
*
* These classes are designed to help build content providers in Android.
*
* <br>Copyright 2010-2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.provider;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.hermit.android.provider.TableSchema.FieldDesc;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
/**
* Class encapsulating the schema for a content provider. Applications
* must subclass this, and provide the necessary information in the
* call to this base class's constructor.
*
* <p>An application's subclass will typically provide the following:
*
* <ul>
* <li>Inner classes which are subclasses of {@link TableSchema},
* defining the schemas of the individual tables.
* <li>A constructor which calls this class's constructor, passing the
* required information.
* </ul>
*/
public abstract class DbSchema {
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a database schema instance.
*
* @param name Name for the database; e.g. "passages".
* @param version Version number of the database. The upgrade
* process will be run when this increments.
* @param auth Authority name for this content provider; e.g.
* "org.hermit.provider.PassageData".
* @param tables List of table schemas.
*/
protected DbSchema(String name, int version, String auth, TableSchema[] tables) {
dbName = name;
dbVersion = version;
dbAuth = auth;
dbTables = tables;
for (TableSchema t : dbTables)
t.init(this);
}
// ******************************************************************** //
// Public Accessors.
// ******************************************************************** //
/**
* Get the database name.
*
* @return The name of the database.
*/
public String getDbName() {
return dbName;
}
/**
* Get the database version number.
*
* @return The database version number.
*/
public int getDbVersion() {
return dbVersion;
}
// ******************************************************************** //
// Local Accessors.
// ******************************************************************** //
/**
* Get the content provider authority string.
*
* @return The authority string.
*/
String getDbAuth() {
return dbAuth;
}
/**
* Get the database table schemas.
*
* @return The table schemas.
*/
TableSchema[] getDbTables() {
return dbTables;
}
/**
* Get the schema for a specified table.
*
* @param name The name of the table we want.
* @return The schema for the given table.
* @throws IllegalArgumentException No such table.
*/
protected TableSchema getTable(String name)
throws IllegalArgumentException
{
for (TableSchema t : dbTables)
if (t.getTableName().equals(name))
return t;
throw new IllegalArgumentException("No such table: " + name);
}
// ******************************************************************** //
// Backup.
// ******************************************************************** //
public void backupDb(Context c, File where)
throws FileNotFoundException, IOException
{
File bakDir = new File(where, dbName + ".bak");
if (!bakDir.isDirectory() && !bakDir.mkdirs())
throw new IOException("can't create backup dir " + bakDir);
// Back up all the tables in the database.
ContentResolver cr = c.getContentResolver();
TableSchema[] tables = getDbTables();
for (TableSchema t : tables) {
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
File bakFile = new File(bakDir, t.getTableName() + ".tb");
fos = new FileOutputStream(bakFile);
dos = new DataOutputStream(fos);
// Write a header containing a magic number, the backup format
// version, and the database schema version.
dos.writeInt(BACKUP_MAGIC);
dos.writeInt(BACKUP_VERSION);
dos.writeInt(dbVersion);
backupTable(cr, t, dos);
} finally {
if (dos != null) try {
dos.close();
} catch (IOException e) { }
if (fos != null) try {
fos.close();
} catch (IOException e) { }
}
}
}
private void backupTable(ContentResolver cr,
TableSchema ts, DataOutputStream dos)
throws IOException
{
Log.v(TAG, "BACKUP " + ts.getTableName());
// Create a where clause based on the backup mode.
String where = null;
String[] wargs = null;
// Query for the records to back up.
Cursor c = null;
try {
c = cr.query(ts.getContentUri(), ts.getDefaultProjection(),
where, wargs, ts.getSortOrder());
Log.v(TAG, "==> " + c.getCount());
// If there's no data, do nothing.
if (!c.moveToFirst())
return;
// Get the column indices for all the columns.
FieldDesc[] fields = ts.getTableFields();
int[] cols = new int[fields.length];
for (int i = 0; i < fields.length; ++i)
cols[i] = c.getColumnIndex(fields[i].name);
// Save all the rows.
while (!c.isAfterLast()) {
dos.writeInt(ROW_MAGIC);
// Save all the fields in this row, each preceded by
// its column number.
StringBuilder sb1 = new StringBuilder(12);
StringBuilder sb2 = new StringBuilder(120);
for (int i = 0; i < fields.length; ++i) {
TableSchema.FieldDesc fd = fields[i];
TableSchema.FieldType ft = fd.type;
// Skip absent fields.
if (c.isNull(i) || (ft == TableSchema.FieldType.TEXT && c.getString(cols[i]) == null)) {
sb1.append('_');
continue;
}
sb1.append('x');
sb2.append(" | " + fd.name + "=" + c.getString(cols[i]));
dos.writeInt(i);
switch (ft) {
case _ID:
case BIGINT:
long lv = c.getLong(cols[i]);
dos.writeLong(lv);
break;
case INT:
int iv = c.getInt(cols[i]);
dos.writeInt(iv);
break;
case DOUBLE:
case FLOAT:
double dv = c.getDouble(cols[i]);
dos.writeDouble(dv);
break;
case REAL:
float fv = c.getFloat(cols[i]);
dos.writeFloat(fv);
break;
case BOOLEAN:
boolean bv = c.getInt(cols[i]) != 0;
dos.writeBoolean(bv);
break;
case TEXT:
String sv = c.getString(cols[i]);
dos.writeUTF(sv);
break;
}
}
Log.v(TAG, ">> " + sb1 + sb2);
dos.writeInt(ROW_END);
c.moveToNext();
}
} finally {
c.close();
}
}
// ******************************************************************** //
// Restore.
// ******************************************************************** //
public void restoreDb(Context c, File where)
throws FileNotFoundException, IOException
{
File bakDir = new File(where, dbName + ".bak");
if (!bakDir.isDirectory())
throw new IOException("can't find backup dir " + bakDir);
// Back up all the tables in the database.
ContentResolver cr = c.getContentResolver();
TableSchema[] tables = getDbTables();
for (TableSchema t : tables) {
FileInputStream fis = null;
DataInputStream dis = null;
try {
File bakFile = new File(bakDir, t.getTableName() + ".tb");
if (!bakFile.isFile())
throw new IOException("can't find backup file " + bakFile);
fis = new FileInputStream(bakFile);
dis = new DataInputStream(fis);
// Write a header containing a magic number, the backup format
// version, and the database schema version.
checkInt(dis, BACKUP_MAGIC, "magic number", bakFile);
checkInt(dis, BACKUP_VERSION, "backup format version", bakFile);
checkInt(dis, dbVersion, "database schema version", bakFile);
wipeTable(cr, t);
restoreTable(cr, t, dis, bakFile);
} finally {
if (dis != null) try {
dis.close();
} catch (IOException e) { }
if (fis != null) try {
fis.close();
} catch (IOException e) { }
}
}
}
private void wipeTable(ContentResolver cr, TableSchema ts) {
Log.v(TAG, "WIPE " + ts.getTableName());
cr.delete(ts.getContentUri(), null, null);
}
private void restoreTable(ContentResolver cr,
TableSchema ts, DataInputStream dis, File bakFile)
throws IOException
{
Log.v(TAG, "RESTORE " + ts.getTableName());
// Get the column indices for all the columns.
FieldDesc[] fields = ts.getTableFields();
// Save all the rows.
ContentValues values = new ContentValues();
while (dis.available() > 0) {
checkInt(dis, ROW_MAGIC, "row header", bakFile);
values.clear();
int i;
while ((i = dis.readInt()) != ROW_END) {
if (i < 0 || i >= fields.length)
throw new IOException("bad column number " + i +
" in " + bakFile);
TableSchema.FieldType t = fields[i].type;
switch (t) {
case _ID:
case BIGINT:
values.put(fields[i].name, dis.readLong());
break;
case INT:
values.put(fields[i].name, dis.readInt());
break;
case DOUBLE:
case FLOAT:
values.put(fields[i].name, dis.readDouble());
break;
case REAL:
values.put(fields[i].name, dis.readFloat());
break;
case BOOLEAN:
values.put(fields[i].name, dis.readBoolean());
break;
case TEXT:
values.put(fields[i].name, dis.readUTF());
break;
}
}
cr.insert(ts.getContentUri(), values);
dontInsert(values, fields);
}
}
private void checkInt(DataInputStream dis, int expect, String desc, File file)
throws IOException
{
int actual = dis.readInt();
if (actual != expect)
throw new IOException("bad " + desc + " in " + file.getName() +
": expected 0x" + Integer.toHexString(expect) +
"; got 0x" + Integer.toHexString(actual));
}
private void dontInsert(ContentValues values, FieldDesc[] fields) {
StringBuilder sb1 = new StringBuilder(12);
StringBuilder sb2 = new StringBuilder(120);
for (FieldDesc fd : fields) {
if (values.containsKey(fd.name)) {
sb1.append('x');
sb2.append(" | " + fd.name + "=" + values.getAsString(fd.name));
} else {
sb1.append('_');
}
}
Log.v(TAG, ">> " + sb1 + sb2);
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
static final String TAG = "DbSchema";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Magic number to identify backup files.
private static final int BACKUP_MAGIC = 0x4d7e870a;
// Version number of the backup file format.
private static final int BACKUP_VERSION = 0x00010000;
// Magic number to identify a row in a backup file. This must be
// distinct from any column number.
private static final int ROW_MAGIC = 0xf5e782c3;
// Magic number to identify the end of a row in a backup file.
private static final int ROW_END = 0x82c3f5e7;
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Database name and version.
private final String dbName;
private final int dbVersion;
// Content provider authority.
private final String dbAuth;
// Definitions of our tables.
private final TableSchema[] dbTables;
}
| 13,128 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TableSchema.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/provider/TableSchema.java |
/**
* org.hermit.android.provider: classes for building content providers.
*
* These classes are designed to help build content providers in Android.
*
* <br>Copyright 2010-2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.provider;
import java.util.HashMap;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Class encapsulating the schema for a table within a content provider.
* Applications must subclass this, and provide the necessary information
* in the call to this base class's constructor.
*
* <p>An application's subclass will typically provide the following:
*
* <ul>
* <li>A <code>public static final Uri CONTENT_URI</code> field, defining
* the content URI for the table.
* <li>A <code>public static final String SORT_ORDER</code> field, defining
* the default sort clause for the table.
* <li>For each column in the table, a <code>public static final String</code>
* field defining the column's database name.
* <li>A <code>public static final String[] PROJECTION</code> field, defining
* the default projection for the table.
* <li>A constructor which calls this class's constructor, passing the
* required information.
* </ul>
*/
public abstract class TableSchema
implements BaseColumns
{
// ******************************************************************** //
// Public Classes.
// ******************************************************************** //
/**
* Enum defining the type of a field.
*
* <p>Note: these enum names are also the SQL type names, and are
* used directly in building the SQL statements to create the tables.
*/
public enum FieldType {
/**
* Field type: row ID, mandatory.
*/
_ID("INTEGER PRIMARY KEY"),
/**
* Field type: 64-bit integer value.
*/
BIGINT,
/**
* Field type: 32-bit integer value.
*/
INT,
/**
* Field type: 32-bit float value.
*/
REAL,
/**
* Field type: 64-bit float value.
*/
FLOAT,
/**
* Field type: 64-bit float value.
*/
DOUBLE,
/**
* Field type: boolean value.
*/
BOOLEAN,
/**
* Field type: text string.
*/
TEXT;
private FieldType(String t) {
textRep = t;
}
private FieldType() {
textRep = name();
}
@Override
public String toString() {
return textRep;
}
private final String textRep;
}
/**
* Descriptor for a field in the database.
*/
public static final class FieldDesc {
public FieldDesc(FieldType type) {
if (type != FieldType._ID)
throw new IllegalArgumentException("Can't use one-arg ctor" +
" with a normal type");
this.name = BaseColumns._ID;
this.type = type;
}
public FieldDesc(String name, FieldType type) {
this.name = name;
this.type = type;
}
public final String name;
public final FieldType type;
}
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create a table schema instance. Create a default projection for
* the table.
*
* @param name Name for the table; e.g. "points".
* @param type Base MIME type identifying the content of this
* table; e.g. "vnd.org.hermit.passage.point".
* @param uri Content URI for this table.
* @param sort Default sort order for this table; e.g.
* "time ASC".
* @param fields List of field definitions. The standard ID
* field "_id" will be prepended automatically.
*/
protected TableSchema(String name, String type,
Uri uri, String sort,
FieldDesc[] fields)
{
tableName = name;
itemType = type;
contentUri = uri;
sortOrder = sort;
fieldDefs = fields;
defProjection = makeProjection(fields);
}
// ******************************************************************** //
// Setup.
// ******************************************************************** //
/**
* Init function called when this table has been added to a database.
*
* @param db Parent database.
*/
void init(DbSchema db) {
// Create the projection map, and all-fields projection.
projectionMap = new HashMap<String, String>();
for (FieldDesc field : fieldDefs)
projectionMap.put(field.name, field.name);
}
// ******************************************************************** //
// Utilities.
// ******************************************************************** //
/**
* This method creates a projection from a set of field definitions.
* It can be used by subclasses to set up a default projection. The
* returned projection includes all fields, including the implicit
* "_id" field, which should <b>not</b> be in the supplied field list.
*
* @param fields List of field definitions. The standard ID
* field "_id" will be prepended automatically.
* @return An all-fields projection for the given fields
* list.
*/
protected static String[] makeProjection(FieldDesc[] fields) {
String[] projection = new String[fields.length];
int np = 0;
for (FieldDesc field : fields)
projection[np++] = field.name;
return projection;
}
// ******************************************************************** //
// Public Accessors.
// ******************************************************************** //
/**
* Get the table name.
*
* @return The table's name in the database.
*/
public String getTableName() {
return tableName;
}
/**
* Get the table's content URI.
*
* @return The "content://" content URI for this table.
*/
public Uri getContentUri() {
return contentUri;
}
/**
* Get the MIME type for the table as a whole.
*
* @return The "vnd.android.cursor.dir/" MIME type for the table.
*/
public String getTableType() {
return "vnd.android.cursor.dir/" + itemType;
}
/**
* Get the MIME type for the items in the table.
*
* @return The "vnd.android.cursor.item/" MIME type for the items.
*/
public String getItemType() {
return "vnd.android.cursor.item/" + itemType;
}
/**
* Get the default projection. The returned projection includes all
* fields, including the implicit "_id" field.
*
* @return An all-fields projection for this table.
*/
public String[] getDefaultProjection() {
return defProjection;
}
// ******************************************************************** //
// Event Handlers.
// ******************************************************************** //
/**
* This method is called when a new row is added into this table.
* Subclasses can override this to fill in any missing values.
*
* @param values The fields being added.
*/
public void onInsert(ContentValues values) {
}
// ******************************************************************** //
// Local Accessors.
// ******************************************************************** //
/**
* Get the specifications of the fields of this table.
*
* @return The field specs, not including the "_id" field.
*/
FieldDesc[] getTableFields() {
return fieldDefs;
}
/**
* Get the table's default sort order.
*
* @return Default sort order.
*/
String getSortOrder() {
return sortOrder;
}
/**
* Get the table's null hack field.
*
* @return A field which can safely be set to NULL if no
* fields at all are present.
*/
String getNullHack() {
return getTableFields()[0].name;
}
/**
* Get the table's projection map.
*
* @return Projection map.
*/
HashMap<String, String> getProjectionMap() {
return projectionMap;
}
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Table's name, item type, and sort order.
private final String tableName;
private final String itemType;
private final String sortOrder;
// Content URI for this table.
private final Uri contentUri;
// Definitions of the fields.
private final FieldDesc[] fieldDefs;
// The default projection for this table.
private final String[] defProjection;
// Projection map for this table.
private HashMap<String, String> projectionMap;
}
| 9,636 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TableProvider.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/org/hermit/android/provider/TableProvider.java |
/**
* org.hermit.android.provider: classes for building content providers.
*
* These classes are designed to help build content providers in Android.
*
* <br>Copyright 2010-2011 Ian Cameron Smith
*
* <p>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation (see COPYING).
*
* <p>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.
*/
package org.hermit.android.provider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
/**
* This class is a base for content providers which provide access to
* table-organized data in an SQL database.
*
* <p>Typically, this is used by creating a subclass which is empty
* other than providing an appropriate schema to this class's constructor.
* The bulk of the work in creating a content provider is in creating
* the schema, a subclass of {@link DbSchema}.
*/
public class TableProvider
extends ContentProvider
{
// ******************************************************************** //
// Constructor.
// ******************************************************************** //
/**
* Create an instance of this content provider.
*
* @param schema Structure defining the database schema.
*/
public TableProvider(DbSchema schema) {
dbSchema = schema;
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
String auth = schema.getDbAuth();
int i = 0;
for (TableSchema t : schema.getDbTables()) {
String tn = t.getTableName();
sUriMatcher.addURI(auth, tn, i);
sUriMatcher.addURI(auth, tn + "/#", 0x10000 | i);
Log.i(TAG, "Match " + auth + "/" + tn + "=" + i);
++i;
}
}
// ******************************************************************** //
// Initialization.
// ******************************************************************** //
/**
* Called when the provider is being started.
*
* @return true if the provider was successfully loaded,
* false otherwise.
*/
@Override
public boolean onCreate() {
mOpenHelper = getHelper();
return true;
}
// ******************************************************************** //
// Accessors.
// ******************************************************************** //
/**
* Get the database schema.
*
* @return The schema for this database.
*/
protected DbSchema getSchema() {
return dbSchema;
}
/**
* Get the schema for a specified table.
*
* @param name The name of the table we want.
* @return The schema for the given table.
* @throws IllegalArgumentException No such table.
*/
protected TableSchema getTableSchema(String name)
throws IllegalArgumentException
{
return dbSchema.getTable(name);
}
// ******************************************************************** //
// Database Helper.
// ******************************************************************** //
/**
* Get the database helper which this content provider will use.
*
* <p>Subclasses may override this to provide a smarter database
* helper; for example, to implement a smarter database upgrade
* process. See {@link DatabaseHelper}.
*
* @return A database helper for this content provider.
*/
protected DatabaseHelper getHelper() {
return new DatabaseHelper(getContext(), getSchema());
}
// ******************************************************************** //
// Data Access.
// ******************************************************************** //
/**
* Return the MIME type of the data at the given URI. This should
* start with vnd.android.cursor.item/ for a single record, or
* vnd.android.cursor.dir/ for multiple items.
*
* @param uri The URI to query.
* @return MIME type string for the given URI, or null
* if there is no type.
*/
@Override
public String getType(Uri uri) {
int tindex = sUriMatcher.match(uri);
if (tindex == UriMatcher.NO_MATCH)
throw new IllegalArgumentException("Unknown URI " + uri +
" in getType()");
boolean isItem = (tindex & 0x10000) != 0;
tindex &= 0xffff;
if (tindex < 0 || tindex >= dbSchema.getDbTables().length)
throw new IllegalArgumentException("Invalid table in " + uri +
" in getType()");
TableSchema t = dbSchema.getDbTables()[tindex];
if (!isItem)
return t.getTableType();
else
return t.getItemType();
}
/**
* Receives a query request from a client in a local process, and
* returns a Cursor. This is called internally by the ContentResolver.
*
* @param uri The URI to query. This will be the full URI
* sent by the client; if the client is requesting
* a specific record, the URI will end in a record
* number that the implementation should parse and
* add to a WHERE or HAVING clause, specifying that
* _id value.
* @param projection The list of columns to put into the cursor.
* If null all columns are included.
* @param where A selection criteria to apply when filtering
* rows. If null then all rows are included.
* @param whereArgs You may include ?s in selection, which will
* be replaced by the values from selectionArgs,
* in order that they appear in the selection.
* The values will be bound as Strings.
* @param sortOrder How the rows in the cursor should be sorted.
* If null then the provider is free to define the
* sort order.
* @return A Cursor or null.
*/
@Override
public Cursor query(Uri uri, String[] projection,
String where, String[] whereArgs,
String sortOrder)
{
int tindex = sUriMatcher.match(uri);
if (tindex == UriMatcher.NO_MATCH)
throw new IllegalArgumentException("Unknown URI " + uri +
" in query()");
boolean isItem = (tindex & 0x10000) != 0;
tindex &= 0xffff;
if (tindex < 0 || tindex >= dbSchema.getDbTables().length)
throw new IllegalArgumentException("Invalid table in " + uri +
" in query()");
TableSchema t = dbSchema.getDbTables()[tindex];
Cursor c;
if (isItem)
c = queryItem(t, projection, uri.getPathSegments().get(1));
else
c = queryItems(t, projection, where, whereArgs, sortOrder);
// Tell the cursor what uri to watch, so it knows when its
// source data changes.
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
/**
* Query for a specified item within a table.
*
* @param t The schema for the table to query.
* @param projection The list of columns to put into the cursor.
* If null all columns are included.
* @param id The ID of the item we want.
* @return A Cursor or null.
*/
protected Cursor queryItem(TableSchema t, String[] projection, long id) {
return queryItem(t, projection, "" + id);
}
/**
* Query for a specified item within a table.
*
* @param t The schema for the table to query.
* @param projection The list of columns to put into the cursor.
* If null all columns are included.
* @param id The ID of the item we want, as a String.
* @return A Cursor or null.
*/
protected Cursor queryItem(TableSchema t, String[] projection, String id) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(t.getTableName());
qb.setProjectionMap(t.getProjectionMap());
qb.appendWhere(BaseColumns._ID + "=" + id);
// Get the database and run the query.
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
return qb.query(db, projection, null, null, null, null, null);
}
/**
* Query for items within a table.
*
* @param t The schema for the table to query.
* @param projection The list of columns to put into the cursor.
* If null all columns are included.
* @param where A selection criteria to apply when filtering
* rows. If null then all rows are included.
* @param whereArgs You may include ?s in selection, which will
* be replaced by the values from selectionArgs,
* in order that they appear in the selection.
* The values will be bound as Strings.
* @param sortOrder How the rows in the cursor should be sorted.
* If null then the provider is free to define the
* sort order.
* @return A Cursor or null.
*/
protected Cursor queryItems(TableSchema t, String[] projection,
String where, String[] whereArgs,
String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(t.getTableName());
qb.setProjectionMap(t.getProjectionMap());
// If no sort order is specified, use the default for the table.
if (TextUtils.isEmpty(sortOrder))
sortOrder = t.getSortOrder();
// Get the database and run the query.
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
return qb.query(db, projection, where, whereArgs, null, null, sortOrder);
}
// ******************************************************************** //
// Data Insertion.
// ******************************************************************** //
/**
* This method is called prior to processing an insert; it is called
* after {@link TableSchema#onInsert(ContentValues)}. Subclasses
* can use this to carry out additional processing.
*
* @param uri The content:// URI of the insertion request.
* @param table The schema of the table we're inserting into.
* @param initValues A set of column_name/value pairs to add to
* the database.
*/
protected void onInsert(Uri uri, TableSchema table, ContentValues initValues) {
}
/**
* Implement this to insert a new row. As a courtesy, call
* notifyChange() after inserting.
*
* @param uri The content:// URI of the insertion request.
* @param initValues A set of column_name/value pairs to add to
* the database.
* @return The URI for the newly inserted item.
*/
@Override
public Uri insert(Uri uri, ContentValues initValues) {
int tindex = sUriMatcher.match(uri);
if (tindex == UriMatcher.NO_MATCH)
throw new IllegalArgumentException("Unknown URI " + uri +
" in insert()");
boolean isItem = (tindex & 0x10000) != 0;
tindex &= 0xffff;
if (tindex < 0 || tindex >= dbSchema.getDbTables().length)
throw new IllegalArgumentException("Invalid table in " + uri +
" in insert()");
TableSchema t = dbSchema.getDbTables()[tindex];
if (isItem)
throw new IllegalArgumentException("Can't insert into item URI " +
uri);
// Copy the values so we can add to it. Create it if needed.
ContentValues values;
if (initValues != null)
values = new ContentValues(initValues);
else
values = new ContentValues();
// Now, do type-specific setup, and fill in any missing values.
t.onInsert(values);
// Allow subclasses to do additional processing.
onInsert(uri, t, values);
// Insert the new row.
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowId = db.insert(t.getTableName(), t.getNullHack(), values);
if (rowId <= 0)
throw new SQLException("Failed to insert row into " + uri);
// Inform everyone about the change.
Uri tableUri = t.getContentUri();
Uri itemUri = ContentUris.withAppendedId(tableUri, rowId);
getContext().getContentResolver().notifyChange(itemUri, null);
return itemUri;
}
// ******************************************************************** //
// Data Deletion.
// ******************************************************************** //
/**
* A request to delete one or more rows. The selection clause is
* applied when performing the deletion, allowing the operation to
* affect multiple rows in a directory. As a courtesy, call
* notifyDelete() after deleting.
*
* The implementation is responsible for parsing out a row ID at the
* end of the URI, if a specific row is being deleted. That is, the
* client would pass in content://contacts/people/22 and the
* implementation is responsible for parsing the record number (22)
* when creating an SQL statement.
*
* @param uri The full URI to delete, including a row ID
* (if a specific record is to be deleted).
* @param where An optional restriction to apply to rows when
* deleting.
* @param whereArgs You may include ?s in where, which will
* be replaced by the values from whereArgs.
* @return The number of rows affected.
* @throws SQLException Database error.
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
int tindex = sUriMatcher.match(uri);
if (tindex == UriMatcher.NO_MATCH)
throw new IllegalArgumentException("Unknown URI " + uri +
" in delete()");
boolean isItem = (tindex & 0x10000) != 0;
tindex &= 0xffff;
if (tindex < 0 || tindex >= dbSchema.getDbTables().length)
throw new IllegalArgumentException("Invalid table in " + uri +
" in delete()");
TableSchema t = dbSchema.getDbTables()[tindex];
// If the URI specifies an item, add the item ID as a where condition.
String whereClause;
if (!isItem) {
whereClause = where;
} else {
String rowId = uri.getPathSegments().get(1);
whereClause = BaseColumns._ID + "=" + rowId;
if (!TextUtils.isEmpty(where))
whereClause += " AND (" + where + ')';
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.delete(t.getTableName(), whereClause, whereArgs);
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// ******************************************************************** //
// Data Updating.
// ******************************************************************** //
/**
* Update a content URI. All rows matching the optionally provided
* selection will have their columns listed as the keys in the values
* map with the values of those keys. As a courtesy, call notifyChange()
* after updating.
*
* @param uri The URI to update. This can potentially have a
* record ID if this is an update request for a
* specific record.
* @param values A Bundle mapping from column names to new column
* values (NULL is a valid value).
* @param where An optional restriction to apply to rows when
* updating.
* @param whereArgs You may include ?s in where, which will
* be replaced by the values from whereArgs.
* @return The number of rows affected.
*/
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
int tindex = sUriMatcher.match(uri);
if (tindex == UriMatcher.NO_MATCH)
throw new IllegalArgumentException("Unknown URI " + uri +
" in update()");
boolean isItem = (tindex & 0x10000) != 0;
tindex &= 0xffff;
if (tindex < 0 || tindex >= dbSchema.getDbTables().length)
throw new IllegalArgumentException("Invalid table in " + uri +
" in update()");
TableSchema t = dbSchema.getDbTables()[tindex];
// If the URI specifies an item, add the item ID as a where condition.
String whereClause;
if (!isItem) {
whereClause = where;
} else {
String rowId = uri.getPathSegments().get(1);
whereClause = BaseColumns._ID + "=" + rowId;
if (!TextUtils.isEmpty(where))
whereClause += " AND (" + where + ')';
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.update(t.getTableName(), values, whereClause, whereArgs);
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// ******************************************************************** //
// Class Data.
// ******************************************************************** //
// Debugging tag.
static final String TAG = "TableProvider";
// ******************************************************************** //
// Private Data.
// ******************************************************************** //
// Schema for this provider.
private final DbSchema dbSchema;
// The URI matcher determines, for a given URI, what is being accessed.
private final UriMatcher sUriMatcher;
// This content provider's database helper.
private DatabaseHelper mOpenHelper;
}
| 19,851 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
TouchListView.java | /FileExtraction/Java_unseen/SilentServices_Scrambled-Net/HermitAndroid/src/com/commonsware/cwac/tlv/TouchListView.java | /*
* Copyright (c) 2010 CommonsWare, LLC
* Portions Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.commonsware.cwac.tlv;
import org.hermit.android.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
public class TouchListView extends ListView {
private ImageView mDragView;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowParams;
private int mDragPos; // which item is being dragged
private int mFirstDragPos; // where was the dragged item originally
private int mDragPoint; // at what offset inside the item did the user grab it
private int mCoordOffset; // the difference between screen coordinates and coordinates in this view
private DragListener mDragListener;
private DropListener mDropListener;
private RemoveListener mRemoveListener;
private int mUpperBound;
private int mLowerBound;
private int mHeight;
private GestureDetector mGestureDetector;
public static final int FLING = 0;
public static final int SLIDE_RIGHT = 1;
public static final int SLIDE_LEFT = 2;
private int mRemoveMode = -1;
private Rect mTempRect = new Rect();
private Bitmap mDragBitmap;
private final int mTouchSlop;
private int mItemHeightNormal=-1;
private int mItemHeightExpanded=-1;
// private int grabberId=-1;
private int dragndropBackgroundColor=0x00000000;
public TouchListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TouchListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
if (attrs!=null) {
TypedArray a=getContext()
.obtainStyledAttributes(attrs,
R.styleable.TouchListView,
0, 0);
mItemHeightNormal=a.getDimensionPixelSize(R.styleable.TouchListView_normal_height, 0);
mItemHeightExpanded=a.getDimensionPixelSize(R.styleable.TouchListView_expanded_height, mItemHeightNormal);
// This is nice, but doesn't work in a library.
// grabberId=a.getResourceId(R.styleable.TouchListView_grabber, -1);
dragndropBackgroundColor=a.getColor(R.styleable.TouchListView_dragndrop_background, 0x00000000);
mRemoveMode=a.getInt(R.styleable.TouchListView_remove_mode, -1);
a.recycle();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mRemoveListener != null && mGestureDetector == null) {
if (mRemoveMode == FLING) {
mGestureDetector = new GestureDetector(getContext(), new SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (mDragView != null) {
if (velocityX > 1000) {
Rect r = mTempRect;
mDragView.getDrawingRect(r);
if ( e2.getX() > r.right * 2 / 3) {
// fast fling right with release near the right edge of the screen
stopDragging();
mRemoveListener.remove(mFirstDragPos);
unExpandViews(true);
}
}
// flinging while dragging should have no effect
return true;
}
return false;
}
});
}
}
if (mDragListener != null || mDropListener != null) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) ev.getX();
int y = (int) ev.getY();
int itemnum = pointToPosition(x, y);
if (itemnum == AdapterView.INVALID_POSITION) {
break;
}
ViewGroup item = (ViewGroup) getChildAt(itemnum - getFirstVisiblePosition());
mDragPoint = y - item.getTop();
mCoordOffset = ((int)ev.getRawY()) - y;
// Get the dragger by using the hardcoded ID defined in the
// library.
View dragger = item.findViewById(R.id.list_grabber);
Rect r = mTempRect;
// dragger.getDrawingRect(r);
r.left=dragger.getLeft();
r.right=dragger.getRight();
r.top=dragger.getTop();
r.bottom=dragger.getBottom();
if ((r.left<x) && (x<r.right)) {
item.setDrawingCacheEnabled(true);
// Create a copy of the drawing cache so that it does not get recycled
// by the framework when the list tries to clean up memory
Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache());
startDragging(bitmap, y);
mDragPos = itemnum;
mFirstDragPos = mDragPos;
mHeight = getHeight();
int touchSlop = mTouchSlop;
mUpperBound = Math.min(y - touchSlop, mHeight / 3);
mLowerBound = Math.max(y + touchSlop, mHeight * 2 /3);
return false;
}
mDragView = null;
break;
}
}
return super.onInterceptTouchEvent(ev);
}
/*
* pointToPosition() doesn't consider invisible views, but we
* need to, so implement a slightly different version.
*/
private int myPointToPosition(int x, int y) {
Rect frame = mTempRect;
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
child.getHitRect(frame);
if (frame.contains(x, y)) {
return getFirstVisiblePosition() + i;
}
}
return INVALID_POSITION;
}
private int getItemForPosition(int y) {
int adjustedy = y - mDragPoint - 32;
int pos = myPointToPosition(0, adjustedy);
if (pos >= 0) {
if (pos <= mFirstDragPos) {
pos += 1;
}
} else if (adjustedy < 0) {
pos = 0;
}
return pos;
}
private void adjustScrollBounds(int y) {
if (y >= mHeight / 3) {
mUpperBound = mHeight / 3;
}
if (y <= mHeight * 2 / 3) {
mLowerBound = mHeight * 2 / 3;
}
}
/*
* Restore size and visibility for all listitems
*/
private void unExpandViews(boolean deletion) {
for (int i = 0;; i++) {
View v = getChildAt(i);
if (v == null) {
if (deletion) {
// HACK force update of mItemCount
int position = getFirstVisiblePosition();
int y = getChildAt(0).getTop();
setAdapter(getAdapter());
setSelectionFromTop(position, y);
// end hack
}
layoutChildren(); // force children to be recreated where needed
v = getChildAt(i);
if (v == null) {
break;
}
}
ViewGroup.LayoutParams params = v.getLayoutParams();
params.height = mItemHeightNormal;
v.setLayoutParams(params);
v.setVisibility(View.VISIBLE);
}
}
/* Adjust visibility and size to make it appear as though
* an item is being dragged around and other items are making
* room for it:
* If dropping the item would result in it still being in the
* same place, then make the dragged listitem's size normal,
* but make the item invisible.
* Otherwise, if the dragged listitem is still on screen, make
* it as small as possible and expand the item below the insert
* point.
* If the dragged item is not on screen, only expand the item
* below the current insertpoint.
*/
private void doExpansion() {
int childnum = mDragPos - getFirstVisiblePosition();
if (mDragPos > mFirstDragPos) {
childnum++;
}
View first = getChildAt(mFirstDragPos - getFirstVisiblePosition());
for (int i = 0;; i++) {
View vv = getChildAt(i);
if (vv == null) {
break;
}
int height = mItemHeightNormal;
int visibility = View.VISIBLE;
if (vv.equals(first)) {
// processing the item that is being dragged
if (mDragPos == mFirstDragPos) {
// hovering over the original location
visibility = View.INVISIBLE;
} else {
// not hovering over it
height = 1;
}
} else if (i == childnum) {
if (mDragPos < getCount() - 1) {
height = mItemHeightExpanded;
}
}
ViewGroup.LayoutParams params = vv.getLayoutParams();
params.height = height;
vv.setLayoutParams(params);
vv.setVisibility(visibility);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mGestureDetector != null) {
mGestureDetector.onTouchEvent(ev);
}
if ((mDragListener != null || mDropListener != null) && mDragView != null) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
Rect r = mTempRect;
mDragView.getDrawingRect(r);
stopDragging();
if (mRemoveMode == SLIDE_RIGHT && ev.getX() > r.left+(r.width()*3/4)) {
if (mRemoveListener != null) {
mRemoveListener.remove(mFirstDragPos);
}
unExpandViews(true);
} else if (mRemoveMode == SLIDE_LEFT && ev.getX() < r.left+(r.width()/4)) {
if (mRemoveListener != null) {
mRemoveListener.remove(mFirstDragPos);
}
unExpandViews(true);
} else {
if (mDropListener != null && mDragPos >= 0 && mDragPos < getCount()) {
mDropListener.drop(mFirstDragPos, mDragPos);
}
unExpandViews(false);
}
break;
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int x = (int) ev.getX();
int y = (int) ev.getY();
dragView(x, y);
int itemnum = getItemForPosition(y);
if (itemnum >= 0) {
if (action == MotionEvent.ACTION_DOWN || itemnum != mDragPos) {
if (mDragListener != null) {
mDragListener.drag(mDragPos, itemnum);
}
mDragPos = itemnum;
doExpansion();
}
int speed = 0;
adjustScrollBounds(y);
if (y > mLowerBound) {
// scroll the list up a bit
speed = y > (mHeight + mLowerBound) / 2 ? 16 : 4;
} else if (y < mUpperBound) {
// scroll the list down a bit
speed = y < mUpperBound / 2 ? -16 : -4;
}
if (speed != 0) {
int ref = pointToPosition(0, mHeight / 2);
if (ref == AdapterView.INVALID_POSITION) {
//we hit a divider or an invisible view, check somewhere else
ref = pointToPosition(0, mHeight / 2 + getDividerHeight() + 64);
}
View v = getChildAt(ref - getFirstVisiblePosition());
if (v!= null) {
int pos = v.getTop();
setSelectionFromTop(ref, pos - speed);
}
}
}
break;
}
return true;
}
return super.onTouchEvent(ev);
}
private void startDragging(Bitmap bm, int y) {
stopDragging();
mWindowParams = new WindowManager.LayoutParams();
mWindowParams.gravity = Gravity.TOP;
mWindowParams.x = 0;
mWindowParams.y = y - mDragPoint + mCoordOffset;
mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
mWindowParams.format = PixelFormat.TRANSLUCENT;
mWindowParams.windowAnimations = 0;
ImageView v = new ImageView(getContext());
// int backGroundColor = getContext().getResources().getColor(R.color.dragndrop_background);
v.setBackgroundColor(dragndropBackgroundColor);
v.setImageBitmap(bm);
mDragBitmap = bm;
mWindowManager = (WindowManager)getContext().getSystemService("window");
mWindowManager.addView(v, mWindowParams);
mDragView = v;
}
private void dragView(int x, int y) {
float alpha = 1.0f;
int width = mDragView.getWidth();
if (mRemoveMode == SLIDE_RIGHT) {
if (x > width / 2) {
alpha = ((float)(width - x)) / (width / 2);
}
mWindowParams.alpha = alpha;
}
else if (mRemoveMode == SLIDE_LEFT) {
if (x < width / 2) {
alpha = ((float)x) / (width / 2);
}
mWindowParams.alpha = alpha;
}
mWindowParams.y = y - mDragPoint + mCoordOffset;
mWindowManager.updateViewLayout(mDragView, mWindowParams);
}
private void stopDragging() {
if (mDragView != null) {
WindowManager wm = (WindowManager)getContext().getSystemService("window");
wm.removeView(mDragView);
mDragView.setImageDrawable(null);
mDragView = null;
}
if (mDragBitmap != null) {
mDragBitmap.recycle();
mDragBitmap = null;
}
}
public void setDragListener(DragListener l) {
mDragListener = l;
}
public void setDropListener(DropListener l) {
mDropListener = l;
}
public void setRemoveListener(RemoveListener l) {
mRemoveListener = l;
}
public interface DragListener {
void drag(int from, int to);
}
public interface DropListener {
void drop(int from, int to);
}
public interface RemoveListener {
void remove(int which);
}
}
| 13,249 | Java | .java | SilentServices/Scrambled-Net | 14 | 11 | 2 | 2014-11-13T11:47:05Z | 2014-11-13T11:54:45Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/test/java/com/myspy/myspyandroid/ExampleUnitTest.java | package com.myspy.myspyandroid;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | 400 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
TabFragment2.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/TabFragment2.java | package com.myspy.myspyandroid;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment2 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_fragment2, container, false);
return view;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 806 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
BootStart.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/BootStart.java | package com.myspy.myspyandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by Miroslav Murin on 25.11.2016.
*/
public class BootStart extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MySpyService.class);
context.startService(myIntent);
}
}
| 432 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
StartActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/StartActivity.java | package com.myspy.myspyandroid;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.myspy.myspyandroid.Weather.WeatherLocationByLocation;
import com.myspy.myspyandroid.Weather.WeatherLocationByName;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.Encryption;
import java.util.List;
public class StartActivity extends Activity {
Context tcontext = this;
Activity activity = this;
LocationManager mLocationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final EditText password = (EditText) findViewById(R.id.editText2);
final EditText passwordrepeat = (EditText) findViewById(R.id.editText3);
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (password.getText().toString() != null && !password.getText().toString().isEmpty()) {
if (password.getText().toString().equals(passwordrepeat.getText().toString())) {
Encryption encryption = Encryption.getDefault("0GzyZdjKFMINl5vtC6rNjz5n9s", "vAlYXMwnrAJYlit5", new byte[16]);
String encrypted = encryption.encryptOrNull(password.getText().toString());
MySpyService.serviceSettings.EncodedPassword = encrypted;
ClassSaver classSaver = new ClassSaver();
classSaver.SaveClassToFile(MySpyService.serviceSettings, "MySpy", "Settings.dat", tcontext);
Log.d("ClassSaver", "Saved");
Toast.makeText(StartActivity.this, "OK", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(StartActivity.this, getResources().getString(R.string.NotEquals), Toast.LENGTH_LONG).show();
Log.d("StartActivity", "Passwords not equals");
}
} else {
Toast.makeText(StartActivity.this, getResources().getString(R.string.EmptyPassword), Toast.LENGTH_LONG).show();
Log.d("StartActivity", "Passwords is empty");
}
}
});
final TextView textweather = (TextView) findViewById(R.id.textViewWeatherLoc);
final Activity activity = this;
(findViewById(R.id.button7)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
WeatherLocationByName weatherLocationByName = new WeatherLocationByName();
weatherLocationByName.GetLocation(((EditText) findViewById(R.id.editTextLocationName)).getText().toString(), "[email protected]");
MySpyService.serviceSettings.WeatherLocationName = weatherLocationByName.GetLocationName();
MySpyService.serviceSettings.WeatherLocation = weatherLocationByName.GetLocationPoint();
final String textl = weatherLocationByName.GetLocationName();
activity.runOnUiThread(new Runnable() {
public void run() {
textweather.setText(textl);
}
});
} catch (Exception ex) {
Log.w("Error", "" + ex);
}
}
});
thread.start();
}
});
(findViewById(R.id.button6)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 99);
WeatherLocationByLocation weatherLocationByLocation = new WeatherLocationByLocation();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 99);
}
Location location = getLastKnownLocation();
weatherLocationByLocation.GetLocation((float) location.getLatitude(), (float) location.getLongitude(), "[email protected]");
MySpyService.serviceSettings.WeatherLocationName = weatherLocationByLocation.GetLocationName();
MySpyService.serviceSettings.WeatherLocation = weatherLocationByLocation.GetLocationPoint();
final String textl = weatherLocationByLocation.GetLocationName();
activity.runOnUiThread(new Runnable() {
public void run() {
textweather.setText(textl);
}
});
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
});
thread.start();
}
});
}
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)tcontext.getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 99);
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
@Override
public void onBackPressed() {
}
}
| 7,992 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
TabFragment1.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/TabFragment1.java | package com.myspy.myspyandroid;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.myspy.myspyandroid.variables.CallInfo;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class TabFragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
try {
UpdateGraphSMS(view);
UpdateCallLengthGraph(view);
}catch (Exception ex)
{
Log.e("ErrorFragment1",""+ex);
}
return view;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void UpdateGraphSMS(View view) {
BarChart mChart;
mChart = (BarChart) view.findViewById(R.id.chartSMSInfo);
mChart.setDrawBarShadow(false);
mChart.setDrawValueAboveBar(true);
mChart.getDescription().setEnabled(false);
mChart.setMaxVisibleValueCount(60);
mChart.setPinchZoom(false);
mChart.setDrawGridBackground(false);
mChart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
//mChart.setValueFormatter(new YourFormatter());
IAxisValueFormatter xAxisFormatter = new CustomFormatter();
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setGranularity(1f); // only intervals of 1 day
xAxis.setLabelCount(7);
xAxis.setValueFormatter(xAxisFormatter);
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setLabelCount(8, false);
leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
leftAxis.setSpaceTop(15f);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setLabelCount(8, false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
Legend l = mChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
l.setForm(Legend.LegendForm.CIRCLE);
l.setFormSize(9f);
l.setTextSize(11f);
l.setXEntrySpace(4f);
l.setExtra(ColorTemplate.MATERIAL_COLORS, new String[] { getResources().getString(R.string.Received),
getResources().getString(R.string.ReceivedAverage), getResources().getString(R.string.Sent), getResources().getString(R.string.SentAverage)});
ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
yVals1.add(new BarEntry(1, MySpyService.serviceVariables.SMSList.size()));
yVals1.add(new BarEntry(2, MySpyService.specialVariables.SMSReceivedAvg/7));
yVals1.add(new BarEntry(3, MySpyService.serviceVariables.SMSOutList.size()));
yVals1.add(new BarEntry(4, MySpyService.specialVariables.SMSSentAvg/7));
BarDataSet set1;
if (mChart.getData() != null &&
mChart.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
set1.setValues(yVals1);
mChart.getData().notifyDataChanged();
mChart.notifyDataSetChanged();
} else {
set1 = new BarDataSet(yVals1, getResources().getString(R.string.SMSStatistics));
set1.setColors(ColorTemplate.MATERIAL_COLORS);
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.setValueTextSize(10f);
data.setBarWidth(0.9f);
data.setValueFormatter(new CustomFormatter());
mChart.setData(data);
}
}
private void UpdateCallLengthGraph(View view) {
int inlength = 0;
int outlength =0;
for (CallInfo info : MySpyService.serviceVariables.CallList) {
if(!info.Missed) {
if(info.OutGoingCall) {
outlength += info.CallLength;
}
else {
inlength += info.CallLength;
}
}
}
PieChart pieChart = (PieChart) view.findViewById(R.id.chartCallInfo);
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.95f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleColor(Color.WHITE);
pieChart.setTransparentCircleAlpha(110);
pieChart.setHoleRadius(58f);
pieChart.setTransparentCircleRadius(62f);
pieChart.setDrawCenterText(true);
pieChart.setRotationAngle(0);
pieChart.setRotationEnabled(false);
pieChart.setHighlightPerTapEnabled(true);
PieDataSet dataSet = new PieDataSet(null,getResources().getString(R.string.CallsLength));
dataSet.addEntry(new PieEntry(outlength,getResources().getString(R.string.MadeLength)));
dataSet.addEntry(new PieEntry(inlength,getResources().getString(R.string.ReceivedLength)));
dataSet.addEntry(new PieEntry(MySpyService.specialVariables.CallTimeWeekIN,getResources().getString(R.string.ReceivedWeekLength)));
dataSet.addEntry(new PieEntry(MySpyService.specialVariables.CallTimeWeekOUT,getResources().getString(R.string.MadeWeekLength)));
dataSet.setColors(ColorTemplate.COLORFUL_COLORS);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new TimeValueFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
pieChart.setData(data);
pieChart.animateY(2000, Easing.EasingOption.EaseInOutQuad);
Legend l = pieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
pieChart.setEntryLabelColor(Color.BLACK);
pieChart.setEntryLabelTextSize(10f);
}
private class TimeValueFormatter implements IValueFormatter {
private DecimalFormat mFormat;
public TimeValueFormatter() {
mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
int Minutes = (int) Math.floor(entry.getY()/60);
int Seconds = ((int)entry.getY()-(Minutes*60));
return String.format("%02d", Minutes)+":"+String.format("%02d", Seconds)+" ( "+mFormat.format(value)+" % )"; // e.g. append a dollar-sign
}
}
private class CustomFormatter implements IAxisValueFormatter, IValueFormatter
{
private DecimalFormat mFormat;
public CustomFormatter() {
mFormat = new DecimalFormat("###");
}
// YAxis
@Override
public String getFormattedValue(float value, AxisBase axis) {
if(value==1)
return getResources().getString(R.string.Received);
else if(value == 2)
return getResources().getString(R.string.ReceivedAverage);
else if(value == 3)
return getResources().getString(R.string.Sent);
else
return getResources().getString(R.string.SentAverage);
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return ""+(int)value;
}
}
}
| 9,707 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
AdministratorActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/AdministratorActivity.java | package com.myspy.myspyandroid;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import com.myspy.myspyandroid.Reports.ChooseReportActivity;
import com.myspy.myspyandroid.Weather.WeatherUnit;
import com.myspy.myspyandroid.functions.ClassSaver;
import java.util.Calendar;
public class AdministratorActivity extends AppCompatActivity {
Calendar calendar = Calendar.getInstance();
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_administrator);
Intent intent = getIntent();
String value = intent.getStringExtra("Token");
Log.d("Value",value);
if(!value.equals(calendar.get(Calendar.DAY_OF_YEAR)+"-"+calendar.get(Calendar.HOUR))) {
Toast.makeText(this, getResources().getString(R.string.Error),Toast.LENGTH_LONG).show();
finish();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void ToSMSReport(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChooseReportActivity.class);
intent.putExtra("Report",1);
AdministratorActivity.this.startActivity(intent);
}
public void ToCallsReport(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChooseReportActivity.class);
intent.putExtra("Report",2);
AdministratorActivity.this.startActivity(intent);
}
public void ToMapReport(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChooseReportActivity.class);
intent.putExtra("Report",3);
AdministratorActivity.this.startActivity(intent);
}
public void ToAppReport(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChooseReportActivity.class);
intent.putExtra("Report",5);
AdministratorActivity.this.startActivity(intent);
}
public void ToRemoveReport(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChooseReportActivity.class);
intent.putExtra("Report",4);
AdministratorActivity.this.startActivity(intent);
}
public void ToChangePassword(View view)
{
Intent intent = new Intent(AdministratorActivity.this, ChangePasswordActivity.class);
AdministratorActivity.this.startActivity(intent);
}
public void ToWebLogin(View view)
{
Intent intent = new Intent(AdministratorActivity.this, WebLogin.class);
AdministratorActivity.this.startActivity(intent);
}
public void SaveSettings(View view)
{
MySpyService.serviceSettings.MonitorCalls = ((CheckBox)findViewById(R.id.checkBoxcalls)).isChecked();
MySpyService.serviceSettings.MonitorSMS = ((CheckBox)findViewById(R.id.checkBoxsms)).isChecked();
MySpyService.serviceSettings.MonitorPosition = ((CheckBox)findViewById(R.id.checkBoxlocation)).isChecked();
MySpyService.serviceSettings.ShowWeather = ((CheckBox)findViewById(R.id.checkBoxshoweather)).isChecked();
MySpyService.serviceSettings.MonitorApplications = ((CheckBox)findViewById(R.id.checkBoxmonitorapps)).isChecked();
MySpyService.serviceSettings.BlockSettings = ((CheckBox)findViewById(R.id.checkBoxblocksettings)).isChecked();
MySpyService.serviceSettings.WebData = ((CheckBox)findViewById(R.id.checkBoxWebSend)).isChecked();
MySpyService.serviceSettings.Alias = ((EditText)findViewById(R.id.editTextAlias)).getText().toString();
if(((RadioButton)findViewById(R.id.radioButtonCelsius)).isChecked())
MySpyService.serviceSettings.weatherUnit = WeatherUnit.Celsius;
else
MySpyService.serviceSettings.weatherUnit = WeatherUnit.Fahrenheit;
ClassSaver classSaver = new ClassSaver();
classSaver.SaveClassToFile(MySpyService.serviceSettings,"MySpy","Settings.dat",this);
}
public void ToBlockApplications(View view)
{
Intent intent = new Intent(AdministratorActivity.this, BlockAppsActivity.class);
AdministratorActivity.this.startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_administrator, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TabFragment1();
case 1:
return new TabFragment2();
case 2:
return new TabFragment3();
}
return null;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.Tab1);
case 1:
return getResources().getString(R.string.Tab2);
case 2:
return getResources().getString(R.string.Tab3);
}
return null;
}
}
}
| 7,805 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
MySpyService.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/MySpyService.java | package com.myspy.myspyandroid;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.GetLocation;
import com.myspy.myspyandroid.variables.ApplicationInformation;
import com.myspy.myspyandroid.variables.ApplicationPackage;
import com.myspy.myspyandroid.variables.SMSInfo;
import com.myspy.myspyandroid.variables.ServiceSettings;
import com.myspy.myspyandroid.variables.ServiceVariables;
import com.myspy.myspyandroid.variables.SpecialVariables;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
public class MySpyService extends Service {
ClassSaver classSaver = new ClassSaver();
ServiceReceiver serviceReceiver = new ServiceReceiver();
Calendar calendar = Calendar.getInstance();
private Context tcontext = this;
private short timervar = 0;
int day = calendar.get(Calendar.DAY_OF_MONTH);
public static ServiceVariables serviceVariables = new ServiceVariables();
public static ServiceSettings serviceSettings = new ServiceSettings();
public static SpecialVariables specialVariables = new SpecialVariables();
File dirn;
ServiceObserver serviceObserver = new ServiceObserver(new Handler());
ContentResolver contentResolver;
GetLocation getLocation;
IntentFilter filter;
String LastActivity = "";
Timer timer = new Timer();
public MySpyService() {
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.d("TaskRemoved","On Task Removed");
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
contentResolver = this.getContentResolver();
serviceObserver.contentResolver = contentResolver;
contentResolver.registerContentObserver(Uri.parse("content://sms"),true, serviceObserver);
filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction("android.provider.Telephony.SMS_SENT");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(serviceReceiver, filter);
return Service.START_STICKY;
}
@Override
public void onCreate(){
super.onCreate();
Start();
}
void Start()
{
dirn = new File( this.getDir("MySpy", Context.MODE_PRIVATE).getPath()+"/Monitoring");
Log.d("Service","Service started");
//nacitaju sa nastavenia
if(classSaver.FileExist("MySpy","Settings.dat",tcontext)) {
serviceSettings = (ServiceSettings) classSaver.LoadClassFromFile(serviceSettings.getClass(), "MySpy", "Settings.dat", tcontext);
Log.d("Settings","Settings Loaded");
}else{
Log.d("Settings","Not exists");
}
if(classSaver.FileExist("MySpy","Special.dat",tcontext)) {
specialVariables = (SpecialVariables) classSaver.LoadClassFromFile(specialVariables.getClass(), "MySpy", "Special.dat", tcontext);
Log.d("SpecialVariables","Variables Loaded");
}else{
Log.d("SpecialVariables","Not exists");
}
//nacitaju sa denne premenne ak existuju
if(new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat").exists()) {
serviceVariables = (ServiceVariables) classSaver.LoadClassFromSpecificFile(serviceVariables.getClass(), new File(dirn +"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat"));
Log.d("Loading Var","Loaded");
} else
Log.d("Loading Var","Not Exist");
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
CheckService();
SaveAll();
Log.d("Service","Timer"+calendar.getTime());
Log.d("Service","FILE: "+"Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat");
if(MySpyService.serviceSettings.WebData) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
PostDataToWeb();
} catch (Exception ex) {
Log.w("ThreadError", "" + ex);
}
}
});
thread.start();
}
}
}, 200000,200000);
String currentHomePackage = "";
try {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
currentHomePackage = resolveInfo.activityInfo.packageName;
Log.d("homepackage", "HOMEPACKAGE: " + currentHomePackage);
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
final String CurrentHomePackage = currentHomePackage;
final ActivityManager am = (ActivityManager) tcontext.getSystemService(ACTIVITY_SERVICE);
Timer timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
if(serviceSettings.MonitorApplications) {
String top = GetTopApp();
//block settings and packageinstaller if block uninstall is enabled
if(serviceSettings.BlockSettings) {
if (top.equals("com.android.settings") || top.equals("com.android.packageinstaller")) {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
}
//Block applications
//check all in list and block them if they are running
if(!specialVariables.Blockedapps.isEmpty())
{
for(ApplicationPackage app : specialVariables.Blockedapps)
{
if(top.equals(app.PackageName))
{
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
}
}
//Monitor applications
//Time,last running...
if(top!=null && !top.isEmpty() && !top.equals(CurrentHomePackage)) {
if (!ApplicationInformation.ContainsPackageName(serviceVariables.Appinfo, top)) {
PackageManager packageManager = getApplicationContext().getPackageManager();
String appName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(top, PackageManager.GET_META_DATA));
serviceVariables.Appinfo.add(new ApplicationInformation(top,appName));
LastActivity = top;
} else {
int pos = ApplicationInformation.GetPosition(serviceVariables.Appinfo, top);
if (pos != -1) {
serviceVariables.Appinfo.get(pos).AddTime(2);
LastActivity = top;
}
}
}else{
int pos = ApplicationInformation.GetPosition(serviceVariables.Appinfo, LastActivity);
if (pos != -1) {
serviceVariables.Appinfo.get(pos).AddTime(2);
}
}
}//monitorapplications
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
}, 2000,2000);
//com.android.packageinstaller
//com.android.settings
Log.d("DATE", SMSInfo.GetCurrentTime());
if(serviceSettings.MonitorPosition) {
try {
getLocation = new GetLocation(this);
} catch (Exception ex) {
Log.w("Error", "" + ex);
}
}
/*
String save = classSaver.SaveClass(serviceVariables);
Log.d("Save",save);
Log.d("Load", classSaver.LoadClass(save, ServiceVariables.class).toString());
*/
}
public String GetTopApp()
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
String topPackageName = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 5000, time);
// Sort the stats by the last time used
if (stats != null) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!mySortedMap.isEmpty()) {
topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
}
return topPackageName;
}else{
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
return am.getRunningTasks(1).get(0).topActivity .getPackageName();
}
}
public void CheckService()
{
timervar++;
calendar = Calendar.getInstance();
//ak sa uvolni servicevariables tak aby sa nacitala zo suboru
if(serviceVariables==null)
{
if(new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+calendar.get(Calendar.DAY_OF_YEAR)+".dat").exists())
serviceVariables = (ServiceVariables) classSaver.LoadClassFromSpecificFile(serviceVariables.getClass(),new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat"));
else
serviceVariables = new ServiceVariables();
}
if(specialVariables==null)
{
if(classSaver.FileExist("MySpy","Special.dat",tcontext))
specialVariables = (SpecialVariables) classSaver.LoadClassFromFile(specialVariables.getClass(), "MySpy", "Special.dat", tcontext);
else
specialVariables = new SpecialVariables();
}
//ak zacne novy den tak restartujeme hodnoty
if(calendar.get(Calendar.DAY_OF_MONTH)!=day)
{
day = calendar.get(Calendar.DAY_OF_MONTH);
serviceVariables = new ServiceVariables();
}
if(timervar>2) {
if(serviceSettings.MonitorPosition) {
try {
if(getLocation!=null)
getLocation.StopGetLocation();
getLocation = new GetLocation(this);
} catch (Exception ex) {
Log.w("Error", "" + ex);
}
}
specialVariables.ResetAverage();
timervar=0;
}
}
public void SaveAll()
{
calendar = Calendar.getInstance();
//ulozime premenne do suboru
if(!classSaver.SaveClassToSpecificFile(serviceVariables,new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat")))
{
Log.w("SaveAll","Failed save variables!");
}
if(!classSaver.SaveClassToSpecificFile(specialVariables,classSaver.GetFile("MySpy","Special.dat",tcontext)))
{
Log.w("SaveAll","Failed save special variables!");
}
}
@Override
public void onDestroy() {
Log.d("Destroy","Destroyed service");
SaveAll();
unregisterReceiver(serviceReceiver);
//startService(new Intent(this, MySpyService.class));
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
void PostDataToWeb()
{
try {
URL url = new URL("http://myspy.diodegames.eu/Connection/ANReport.php");
HttpURLConnection client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setDoOutput(true);
Calendar calendar = Calendar.getInstance();
StringBuilder builder = new StringBuilder("");
File dirn = new File( this.getDir("MySpy", Context.MODE_PRIVATE).getPath()+"/Monitoring");
StringBuilder text = new StringBuilder();
if(new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat").exists()) {
BufferedReader br = new BufferedReader(new FileReader( new File(dirn+"/Day_"+calendar.get(Calendar.YEAR)+"_"+(calendar.get(Calendar.MONTH)+1)+"_"+calendar.get(Calendar.DAY_OF_MONTH)+".dat") ));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}else{
Log.w("File","Not Found");
}
builder.append ("Token=blZEHudX&ID="+MySpyService.serviceSettings.ID+"&Alias="+MySpyService.serviceSettings.Alias);
builder.append ("&Data="+text.toString());
builder.append("&Device="+ Build.MANUFACTURER+" "+Build.MODEL);
OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
outputPost.write(builder.toString().getBytes());
outputPost.flush();
outputPost.close();
String response = "";
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("WEB",response);
client.disconnect();
}catch (Exception ex)
{
Log.w("WebError",""+ex.toString());
}
}
/*
void SetLastKnowLocation(){
LocationManager locationManager
= (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(c, true);
Location location = locationManager.getLastKnownLocation(provider);
}
*/
}
| 18,092 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ChangePasswordActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/ChangePasswordActivity.java | package com.myspy.myspyandroid;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.Encryption;
public class ChangePasswordActivity extends AppCompatActivity {
Encryption encryption = Encryption.getDefault("0GzyZdjKFMINl5vtC6rNjz5n9s", "vAlYXMwnrAJYlit5", new byte[16]);
String decrypted = encryption.decryptOrNull(MySpyService.serviceSettings.EncodedPassword);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}catch (Exception e)
{
Log.w("Error",""+e);
}
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
public void ChangePassword(View view)
{
EditText oldpassword = (EditText) findViewById(R.id.editTextoldpassword);
EditText password = (EditText) findViewById(R.id.editTextnewpassword);
EditText passwordrepeat = (EditText) findViewById(R.id.editTextnewpasswordrepeat);
if(oldpassword.getText().toString() != null && !oldpassword.getText().toString().isEmpty()) {
if(oldpassword.getText().toString().equals(decrypted)) {
Log.d("LoginActivity", "OK");
//GOOD OLD PASSWORD
if(password.getText().toString() != null && !password.getText().toString().isEmpty()) {
if (password.getText().toString().equals(passwordrepeat.getText().toString())) {
//No problem with new passwords
String encrypted = encryption.encryptOrNull(password.getText().toString());
MySpyService.serviceSettings.EncodedPassword = encrypted;
ClassSaver classSaver = new ClassSaver();
classSaver.SaveClassToFile(MySpyService.serviceSettings,"MySpy","Settings.dat",this);
Log.d("ClassSaver","Saved");
Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(this, getResources().getString(R.string.NotEquals), Toast.LENGTH_LONG).show();
Log.d("StartActivity", "Passwords not equals");
}
}else{
Toast.makeText(this, getResources().getString(R.string.EmptyPassword), Toast.LENGTH_LONG).show();
Log.d("StartActivity", "Passwords is empty");
}
}else{
Toast.makeText(this, getResources().getString(R.string.BadPassword), Toast.LENGTH_LONG).show();
Log.d("ChangePassword", "Passwords is bad");
}
}else{
Toast.makeText(this, getResources().getString(R.string.EmptyPassword), Toast.LENGTH_LONG).show();
Log.d("ChangePassword", "Passwords is empty");
}
//Toast.makeText(this,getResources().getString(R.string.PasswordChanged),Toast.LENGTH_LONG).show();
}
}
| 3,390 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WebLogin.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/WebLogin.java | package com.myspy.myspyandroid;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.Encryption;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class WebLogin extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_login);
final EditText email = (EditText)findViewById(R.id.editTextEmailWeb);
final EditText password = (EditText)findViewById(R.id.editTextPasswordWeb);
Button button = (Button)findViewById(R.id.buttonLoginWeb);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!password.getText().toString().isEmpty() && !email.getText().toString().isEmpty()) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Login(email.getText().toString(),password.getText().toString());
} catch (Exception ex) {
Log.w("ThreadError", "" + ex);
}
}
});
thread.start();
}else{
Toast.makeText(WebLogin.this, getResources().getString(R.string.EmptyForm), Toast.LENGTH_LONG).show();
Log.d("LoginActivity", "Passwords is empty or email is empty");
}
}
});
}
void Login(String Email, String Password)
{
try {
URL url = new URL("http://myspy.diodegames.eu/Connection/ANCLogin.php");
HttpURLConnection client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setDoOutput(true);
StringBuilder builder = new StringBuilder("");
builder.append ("Token=blZEHudX");
builder.append ("&Email="+Email);
builder.append("&Pass="+ Password);
OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
outputPost.write(builder.toString().getBytes());
outputPost.flush();
outputPost.close();
String response = "";
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("WEB",response);
if(!response.equals("Error")) {
response = response.replace("<tr>","");
Log.d("WEBReplace",response);
MySpyService.serviceSettings.ID = response;
ClassSaver classSaver = new ClassSaver();
classSaver.SaveClassToFile(MySpyService.serviceSettings,"MySpy","Settings.dat",this);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WebLogin.this, getResources().getString(R.string.Success), Toast.LENGTH_LONG).show();
finish();
}
});
}else{
runOnUiThread(new Runnable(){
@Override
public void run(){
Toast.makeText(WebLogin.this, getResources().getString(R.string.NoSuccess), Toast.LENGTH_LONG).show();
}
});
}
client.disconnect();
}catch (Exception ex)
{
Log.w("WebError",""+ex.toString());
runOnUiThread(new Runnable(){
@Override
public void run(){
Toast.makeText(WebLogin.this, getResources().getString(R.string.NoSuccess), Toast.LENGTH_LONG).show();
}
});
}
}
}
| 4,893 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
MainActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/MainActivity.java | package com.myspy.myspyandroid;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.myspy.myspyandroid.Weather.Weather;
import com.myspy.myspyandroid.Weather.WeatherInfo;
import com.myspy.myspyandroid.Weather.WeatherLocationByLocation;
import com.myspy.myspyandroid.Weather.WeatherUnit;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.variables.CallInfo;
import com.myspy.myspyandroid.variables.LocationPoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Permission;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class MainActivity extends Activity {
ClassSaver classSaver = new ClassSaver();
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
Activity activity = this;
Context context = this;
LocationManager mLocationManager;
private boolean addPermission(List<String> permissionsList, String permission) {
if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,permission))
return false;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("GPS");
if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("Read Contacts");
if (!addPermission(permissionsList, Manifest.permission.WRITE_CONTACTS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("Read External");
if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.RECEIVE_SMS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.SEND_SMS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.READ_CALL_LOG))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.PROCESS_OUTGOING_CALLS))
permissionsNeeded.add("Write Contacts");
if (!addPermission(permissionsList, Manifest.permission.KILL_BACKGROUND_PROCESSES))
permissionsNeeded.add("Write Contacts");
if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions(this,permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
try {
if (!isAccessGranted()) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
}catch (Exception ex)
{
Log.e("USAGE ACCESS SETTINGS","API 21 Required");
}
if(!isMyServiceRunning(MySpyService.class))
startService(new Intent(this, MySpyService.class));
Log.d("POINT", "1");
Typeface type = Typeface.createFromAsset(getAssets(),"jockeyone.ttf");
((TextView)findViewById(R.id.textViewMySpy)).setTypeface(type);
File dir = this.getDir("MySpy", Context.MODE_PRIVATE);
File dirn = new File(dir.getPath()+"/Monitoring");
dirn.mkdir();
if(classSaver.FileExist("MySpy","Settings.dat",this)) {
Log.d("Settings","Settings Loaded");
}else{
Log.d("Settings","Not exists. Starting Start Activity");
Intent myIntent = new Intent(MainActivity.this, StartActivity.class);
MainActivity.this.startActivity(myIntent);
}
final Activity activity = this;
final Context context = this;
Log.d("POINT", "2");
UpdateInformations();
if(MySpyService.serviceSettings.ShowWeather) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
if (classSaver.FileExist("MySpy", "Weatherdata.dat", context)) {
Log.d("CurrentWeather", "Weather exist checking");
//Log.d("GetWeather", "Location Name: " + MySpyService.serviceSettings.WeatherLocationName + " Location Position: LAT: " + MySpyService.serviceSettings.WeatherLocation.Latitude + " LON: " + MySpyService.serviceSettings.WeatherLocation.Longitude);
final WeatherInfo weatherInfo = (WeatherInfo) classSaver.LoadClassFromSpecificFile(WeatherInfo.class, classSaver.GetFile("MySpy", "Weatherdata.dat", context)); // classSaver.LoadClassFromFile(WeatherInfo.class,"MySpy","Weatherdata.dat",context);
Calendar calendar = Calendar.getInstance();
if (weatherInfo != null && weatherInfo.day == (calendar.get(Calendar.DAY_OF_MONTH)) && weatherInfo.hour < (calendar.get(Calendar.HOUR_OF_DAY) + 3)) {
Log.d("CurrentWeather", "Weather exist and still valid: Hour: " + weatherInfo.hour + " Day: " + weatherInfo.day);
final LinearLayout weatherlayout = (LinearLayout) findViewById(R.id.WeatherLayout);
FileInputStream is = new FileInputStream(classSaver.GetFile("MySpy", "Weatherimage.dat", context));
//activity.openFileInput(classSaver.GetFile("MySpy","Weatherimage.dat",context).getAbsolutePath());
final Bitmap weatherbitmap = BitmapFactory.decodeStream(is);
Log.d("Weather temp:",""+weatherInfo.temperature.GetTemperature(MySpyService.serviceSettings.weatherUnit));
if (weatherInfo.temperature.GetTemperature(WeatherUnit.Celsius) > -272) {
activity.runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.textViewlocationweather)).setText(MySpyService.serviceSettings.WeatherLocationName);
((TextView) findViewById(R.id.textViewtemperature)).setText((int) weatherInfo.temperature.GetTemperature(MySpyService.serviceSettings.weatherUnit) + " " + weatherInfo.temperature.GetUnitSymbol(MySpyService.serviceSettings.weatherUnit));
((TextView) findViewById(R.id.textViewhumidity)).setText(FloatStringToInt(weatherInfo.humidity) + " %");
((TextView) findViewById(R.id.textViewprecipitation)).setText(weatherInfo.precipitation + " " + weatherInfo.precipitationunit);
((TextView) findViewById(R.id.textViewcloudiness)).setText(FloatStringToInt(weatherInfo.cloudiness) + " %");
((TextView) findViewById(R.id.textViewDate)).setText(weatherInfo.Date);
((ImageView) findViewById(R.id.imageViewWeather)).setImageBitmap(weatherbitmap);
weatherlayout.setVisibility(View.VISIBLE);
}
});
} else {
weatherlayout.setVisibility(View.GONE);
}
Log.d("CurrentWeather", "Weather loaded from file");
} else {
Log.d("New WEATHER", "New Weather 1");
NewWeather();
}
} else {
Log.d("New WEATHER","New Weather 2");
NewWeather();
}
} catch (Exception ex) {
Log.w("Error", "Weather: " + ex);
try {
File file = classSaver.GetFile("MySpy", "Weatherdata.dat", context);
if (file.exists())
file.delete();
} catch (Exception exe) {
Log.w("Error", "Weather Remove file: " + exe);
}
}
}
});
thread.start();
}//showweather
}
private boolean isAccessGranted() {
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = 0;
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.KITKAT) {
mode = appOpsManager.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
applicationInfo.uid, applicationInfo.packageName);
}
return (mode == AppOpsManager.MODE_ALLOWED);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
void NewWeather()
{
final Activity activity = this;
Log.d("Weather","***** New Weather *****");
if (MySpyService.serviceSettings.WeatherLocation != null && MySpyService.serviceSettings.WeatherLocationName != null && !MySpyService.serviceSettings.WeatherLocationName.isEmpty()) {
final Weather weather = new Weather();
boolean weathersuccess = weather.GetWeather(MySpyService.serviceSettings.WeatherLocation);
Log.d("Temperature", weather.weatherInfo.temperature.GetTemperatureWithUnit(WeatherUnit.Celsius));
final LinearLayout weatherlayout = (LinearLayout) findViewById(R.id.WeatherLayout);
final Bitmap weatherbitmap;
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) > 21 && calendar.get(Calendar.HOUR_OF_DAY) < 6)
weatherbitmap = weather.GetWeatherIcon(weather.weatherInfo.symbolNumber, 1);
else
weatherbitmap = weather.GetWeatherIcon(weather.weatherInfo.symbolNumber, 0);
weather.weatherInfo.day = calendar.get(Calendar.DAY_OF_MONTH);
weather.weatherInfo.hour = calendar.get(Calendar.HOUR_OF_DAY);
NumberFormat nf = new DecimalFormat("00");
weather.weatherInfo.Date = (nf.format(calendar.get(Calendar.DAY_OF_MONTH)))+"."+ nf.format((calendar.get(Calendar.MONTH)+1))+" "+nf.format(calendar.get(Calendar.HOUR_OF_DAY))+":00";
final WeatherInfo weatherInfo = weather.weatherInfo;
Log.d("Weather temperature",""+weatherInfo.temperature.GetTemperature(WeatherUnit.Celsius)+" Success: "+weathersuccess);
if(weathersuccess && weatherInfo.temperature.GetTemperature(WeatherUnit.Celsius)>-272) {
activity.runOnUiThread(new Runnable() {
public void run() {
((TextView) findViewById(R.id.textViewlocationweather)).setText(MySpyService.serviceSettings.WeatherLocationName);
((TextView) findViewById(R.id.textViewtemperature)).setText((int) weatherInfo.temperature.GetTemperature(MySpyService.serviceSettings.weatherUnit) + " " + weatherInfo.temperature.GetUnitSymbol(MySpyService.serviceSettings.weatherUnit));
((TextView) findViewById(R.id.textViewhumidity)).setText(FloatStringToInt(weatherInfo.humidity) + " %");
((TextView) findViewById(R.id.textViewprecipitation)).setText(weatherInfo.precipitation + " " + weatherInfo.precipitationunit);
((TextView) findViewById(R.id.textViewcloudiness)).setText(FloatStringToInt(weatherInfo.cloudiness) + " %");
((TextView) findViewById(R.id.textViewDate)).setText(weatherInfo.Date);
((ImageView) findViewById(R.id.imageViewWeather)).setImageBitmap(weatherbitmap);
weatherlayout.setVisibility(View.VISIBLE);
}
});
}else{
weatherlayout.setVisibility(View.GONE);
}
try {
FileOutputStream fos = new FileOutputStream(classSaver.GetFile("MySpy","Weatherimage.dat",this));
weatherbitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
}catch (Exception ex)
{
Log.d("Error",""+ex);
}
classSaver.SaveClassToSpecificFile(weatherInfo,classSaver.GetFile("MySpy","Weatherdata.dat",this));
Log.d("Weather","Saved weather data");
}else{
Log.d("Weather GET","Location data not exist");
}
}
private String FloatStringToInt(String text)
{
try{
return ((int)Float.parseFloat(text))+"";
}catch (Exception ex)
{
Log.w("FloatStringToInt",""+ex);
return text;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int FLoc = 0;
int i=0;
for (String t: permissions) {
if(t.equals(Manifest.permission.ACCESS_FINE_LOCATION))
{
FLoc = i;
Log.d("Find Location","FLOC: "+FLoc+" Sp: "+permissions[FLoc]+" IR: "+grantResults[FLoc]);
stopService(new Intent(this, MySpyService.class));
startService(new Intent(this, MySpyService.class));
break;
}
i++;
}
}
private void UpdateInformations()
{
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
int inlength = 0,in = 0;
int outlength =0, out = 0;
for (CallInfo info : MySpyService.serviceVariables.CallList) {
if(!info.Missed) {
if(info.OutGoingCall) {
outlength += info.CallLength;
out++;
}
else {
inlength += info.CallLength;
in++;
}
}
}
final int inlengthf = inlength,inf = in;
final int outlengthf = outlength, outf = out;
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
((TextView) findViewById(R.id.textViewsmsreceivedcount)).setText(MySpyService.serviceVariables.SMSList.size()+"");
((TextView) findViewById(R.id.textViewsmssentcount)).setText(MySpyService.serviceVariables.SMSOutList.size()+"");
((TextView) findViewById(R.id.textViewmadecallscount)).setText(outf + "");
((TextView) findViewById(R.id.textViewreceivedcallscount)).setText(inf + "");
((TextView) findViewById(R.id.textViewmadecallslength)).setText(IntToTime(outlengthf));
((TextView) findViewById(R.id.textViewreceivedcallslength)).setText(IntToTime(inlengthf));
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
});
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
});
thread.start();
}
private String IntToTime(int Time)
{
int Minutes = (int) Math.floor(Time/60);
int Seconds = (Time-(Minutes*60));
return String.format("%02d", Minutes)+":"+String.format("%02d", Seconds);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void ToAdminLogin(View view)
{
Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
MainActivity.this.startActivity(myIntent);
}
}
| 19,108 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
LoginActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/LoginActivity.java | package com.myspy.myspyandroid;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.myspy.myspyandroid.functions.Encryption;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class LoginActivity extends Activity {
Encryption encryption = Encryption.getDefault("0GzyZdjKFMINl5vtC6rNjz5n9s", "vAlYXMwnrAJYlit5", new byte[16]);
String decrypted = encryption.decryptOrNull(MySpyService.serviceSettings.EncodedPassword);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText password = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(password.getText().toString() != null && !password.getText().toString().isEmpty()) {
if(password.getText().toString().equals(decrypted)) {
Log.d("LoginActivity", "OK");
Intent myIntent = new Intent(LoginActivity.this, AdministratorActivity.class);
Calendar calendar = Calendar.getInstance();
myIntent.putExtra("Token", calendar.get(Calendar.DAY_OF_YEAR)+"-"+calendar.get(Calendar.HOUR));
LoginActivity.this.startActivity(myIntent);
finish();
}else{
Toast.makeText(LoginActivity.this, getResources().getString(R.string.BadPassword), Toast.LENGTH_LONG).show();
Log.d("LoginActivity", "Passwords is bad");
}
}else{
Toast.makeText(LoginActivity.this, getResources().getString(R.string.EmptyPassword), Toast.LENGTH_LONG).show();
Log.d("LoginActivity", "Passwords is empty");
}
}
});
}
}
| 2,482 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
BlockAppsActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/BlockAppsActivity.java | package com.myspy.myspyandroid;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.myspy.myspyandroid.variables.ApplicationPackage;
import java.util.ArrayList;
import java.util.List;
//Miroslav Murin
public class BlockAppsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block_apps);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}catch (Exception e)
{
Log.w("Error",""+e);
}
final PackageManager pm = getPackageManager();
ListView listViewapp = (ListView) findViewById(R.id.ListApps);
final ListView listViewblockedapp = (ListView) findViewById(R.id.ListBlockApps);
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
final ArrayList<ApplicationPackage> installedapps = new ArrayList<ApplicationPackage>();
for (ApplicationInfo packageInfo : packages) {
if(!packageInfo.packageName.equals(getApplicationContext().getPackageName())) {
installedapps.add(new ApplicationPackage( packageInfo.packageName+"",packageInfo.loadLabel(pm)+""));
}
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, ApplicationPackage.ApplicationName(installedapps));
listViewapp.setAdapter(arrayAdapter);
final ArrayAdapter<String> arraybAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, ApplicationPackage.ApplicationName(MySpyService.specialVariables.Blockedapps));
listViewblockedapp.setAdapter(arraybAdapter);
final Context context = this;
listViewapp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ClickedOn",installedapps.get(position).PackageName);
if(!MySpyService.specialVariables.Blockedapps.contains(new ApplicationPackage(installedapps.get(position).PackageName,installedapps.get(position).ApplicationName)))
MySpyService.specialVariables.Blockedapps.add(new ApplicationPackage(installedapps.get(position).PackageName,installedapps.get(position).ApplicationName));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(context, android.R.layout.simple_list_item_1, ApplicationPackage.ApplicationName(MySpyService.specialVariables.Blockedapps));
listViewblockedapp.setAdapter(arrayAdapter);
}
});
listViewblockedapp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ClickedOn",MySpyService.specialVariables.Blockedapps.get(position).PackageName);
MySpyService.specialVariables.Blockedapps.remove(position);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(context, android.R.layout.simple_list_item_1, ApplicationPackage.ApplicationName(MySpyService.specialVariables.Blockedapps));
listViewblockedapp.setAdapter(arrayAdapter);
}
});
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
}
| 3,942 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ServiceObserver.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/ServiceObserver.java | package com.myspy.myspyandroid;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import com.myspy.myspyandroid.variables.SMSInfo;
import java.util.Calendar;
/**
* Created by Miroslav Murin on 16.12.2016.
*/
public class ServiceObserver extends ContentObserver {
String LastSMS = "";
public ContentResolver contentResolver;
public ServiceObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
try {
Uri uriSMSURI = Uri.parse("content://sms/sent");
Cursor cur = contentResolver.query(uriSMSURI, null, null, null, null);
cur.moveToNext();
String content = cur.getString(cur.getColumnIndex("body"));
String smsNumber = cur.getString(cur.getColumnIndex("address"));
Calendar calendar = Calendar.getInstance();
try {
calendar.setTimeInMillis(Long.parseLong(cur.getString(cur.getColumnIndex("date"))));
} catch (Exception ex) {
Log.w("Observer Error", "" + ex);
}
Log.d("Observer", "" + calendar.getTime());
if (smsNumber == null || smsNumber.length() <= 0) {
smsNumber = "Unknown";
}
cur.close();
if (CheckSMS("OutgoingSMS to " + smsNumber + ": " + content)) {
Log.d("OBSERVERSMS", "OutgoingSMS to " + smsNumber + ": " + content);
if (calendar.get(Calendar.DAY_OF_MONTH) == Calendar.getInstance().get(calendar.DAY_OF_MONTH)) {
if (MySpyService.serviceSettings.MonitorSMS)
MySpyService.serviceVariables.SMSOutList.add(new SMSInfo(smsNumber, content, SMSInfo.GetCurrentTime()));
MySpyService.specialVariables.SMSSentAvg++;
} else {
Log.d("Observer", "SMS from yesterday");
}
}
}catch (Exception ex)
{
Log.d("ErrorObserver",""+ex);
}
}
public boolean CheckSMS(String SMS) {
if (SMS.equals(LastSMS) || SMS.equals(MySpyService.specialVariables.LastSentSMS)) {
return false;
}
else {
LastSMS = SMS;
}
return true;
}
}
| 2,481 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ServiceReceiver.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/ServiceReceiver.java | package com.myspy.myspyandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.myspy.myspyandroid.variables.CallInfo;
import com.myspy.myspyandroid.variables.SMSInfo;
/**
* Created by Miroslav Murin on 28.11.2016.
*/
public class ServiceReceiver extends BroadcastReceiver {
private boolean ringing = true,start = false, outgoing = false;
private long Stime = 0,Etime;
private String number = "";
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.d("Service", "Broadcast received something: " + intent.getAction());
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Log.d("BROADCAST", "Received");
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage;
if (Build.VERSION.SDK_INT >= 19) { //KITKAT
SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
smsMessage = msgs[0];
} else {
Object pdus[] = (Object[]) intentExtras.get("pdus");
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);
}
String phone = smsMessage.getOriginatingAddress();
String message = smsMessage.getMessageBody().toString();
if (MySpyService.serviceSettings.MonitorSMS)
MySpyService.serviceVariables.SMSList.add(new SMSInfo(phone, message, SMSInfo.GetCurrentTime()));
MySpyService.specialVariables.SMSReceivedAvg++;
//Toast.makeText(context, phone + ": " + message, Toast.LENGTH_SHORT).show();
Log.d("SMSBROADCAST", "Phone: " + phone + " Message: " + message);
}
}
} else if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
Log.d("BROADCAST", "Outgoing call to: " + intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
start = true;
outgoing = true;
Stime = System.currentTimeMillis();
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
} else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
//OFFHOOK IDLE RINGING
if (state.equals("OFFHOOK")) {
if (!start) {
start = true;
outgoing = false;
Stime = System.currentTimeMillis();
}
} else if (state.equals("RINGING")) {
ringing = true;
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d("Ringing", "" + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
} else if (state.equals("IDLE")) { //OFFHOOK IDLE
if (start) {
Etime = System.currentTimeMillis();
if (MySpyService.serviceSettings.MonitorCalls)
MySpyService.serviceVariables.CallList.add(new CallInfo(number, outgoing, (int) ((Etime - Stime) / 1000), CallInfo.GetCurrentTime()));
start = false;
ringing = false;
if (outgoing)
MySpyService.specialVariables.CallTimeWeekOUT += (int) ((Etime - Stime) / 1000);
else
MySpyService.specialVariables.CallTimeWeekIN += (int) ((Etime - Stime) / 1000);
Log.d("New Call added", "Number: " + number + " Outgoing: " + outgoing + " Time: " + (int) ((Etime - Stime) / 1000));
} else {
if (ringing) {
if (MySpyService.serviceSettings.MonitorCalls)
MySpyService.serviceVariables.CallList.add(new CallInfo(number, CallInfo.GetCurrentTime()));
Log.d("New Missed Call added", "MISSED Number: " + number);
ringing = false;
}
}
}
Log.d("BROADCAST", "call state changed....: " + state);
}
}catch (Exception ex)
{
Log.d("ErrorServiceReceiver",""+ex);
}
}
}
| 5,114 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
TabFragment3.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/TabFragment3.java | package com.myspy.myspyandroid;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.myspy.myspyandroid.Weather.WeatherLocationByLocation;
import com.myspy.myspyandroid.Weather.WeatherLocationByName;
import com.myspy.myspyandroid.Weather.WeatherUnit;
public class TabFragment3 extends Fragment {
boolean Loaded = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_tab_fragment3, container, false);
if(!Loaded) {
((CheckBox) view.findViewById(R.id.checkBoxcalls)).setChecked(MySpyService.serviceSettings.MonitorCalls);
((CheckBox) view.findViewById(R.id.checkBoxsms)).setChecked(MySpyService.serviceSettings.MonitorSMS);
((CheckBox) view.findViewById(R.id.checkBoxlocation)).setChecked(MySpyService.serviceSettings.MonitorPosition);
((CheckBox) view.findViewById(R.id.checkBoxshoweather)).setChecked(MySpyService.serviceSettings.ShowWeather);
((CheckBox) view.findViewById(R.id.checkBoxmonitorapps)).setChecked(MySpyService.serviceSettings.MonitorApplications);
((CheckBox) view.findViewById(R.id.checkBoxblocksettings)).setChecked(MySpyService.serviceSettings.BlockSettings);
((CheckBox) view.findViewById(R.id.checkBoxWebSend)).setChecked(MySpyService.serviceSettings.WebData);
((TextView) view.findViewById(R.id.textViewWeatherNameSett)).setText(MySpyService.serviceSettings.WeatherLocationName);
((TextView) view.findViewById(R.id.editTextAlias)).setText(MySpyService.serviceSettings.Alias);
if(!MySpyService.serviceSettings.ID.isEmpty() && !MySpyService.serviceSettings.ID.equals(""))
((CheckBox) view.findViewById(R.id.checkBoxWebLoggedin)).setChecked(true);
else
((CheckBox) view.findViewById(R.id.checkBoxWebLoggedin)).setChecked(false);
if(MySpyService.serviceSettings.weatherUnit == WeatherUnit.Celsius)
((RadioButton)view.findViewById(R.id.radioButtonCelsius)).setChecked(true);
else
((RadioButton)view.findViewById(R.id.radioButtonFahrenheit)).setChecked(true);
Log.d("Fragment 3", "Loaded");
Loaded = true;
}
final TextView textaccuracy = (TextView) view.findViewById(R.id.textViewaccuracy) ;
SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekBarAccuracy);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.d("SeekBar",""+progress);
if(progress==0) {
textaccuracy.setText(getResources().getString(R.string.Low));
MySpyService.serviceSettings.PositionTime = 100000; //100 sekund
}
else if(progress==1) {
textaccuracy.setText(getResources().getString(R.string.Medium));
MySpyService.serviceSettings.PositionTime = 50000; //50 sekund
}
else {
textaccuracy.setText(getResources().getString(R.string.High));
MySpyService.serviceSettings.PositionTime = 30000; //30 sekund
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final Activity activity = getActivity();
(view.findViewById(R.id.buttongetbynameweat)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
WeatherLocationByName weatherLocationByName = new WeatherLocationByName();
weatherLocationByName.GetLocation(((EditText) view.findViewById(R.id.editTextLocationWeather)).getText().toString(), "[email protected]");
MySpyService.serviceSettings.WeatherLocationName = weatherLocationByName.GetLocationName();
MySpyService.serviceSettings.WeatherLocation = weatherLocationByName.GetLocationPoint();
final String textl = weatherLocationByName.GetLocationName();
activity.runOnUiThread(new Runnable() {
public void run() {
((TextView)view.findViewById(R.id.textViewWeatherNameSett)).setText(textl);
}
});
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
});
thread.start();
}
});
(view.findViewById(R.id.buttongetautomaticallyweat)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
WeatherLocationByLocation weatherLocationByLocation = new WeatherLocationByLocation();
LocationManager locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
weatherLocationByLocation.GetLocation((float)location.getLatitude(),(float)location.getLongitude(),"[email protected]");
MySpyService.serviceSettings.WeatherLocationName = weatherLocationByLocation.GetLocationName();
MySpyService.serviceSettings.WeatherLocation = weatherLocationByLocation.GetLocationPoint();
final String textl = weatherLocationByLocation.GetLocationName();
activity.runOnUiThread(new Runnable() {
public void run() {
((TextView)view.findViewById(R.id.textViewWeatherNameSett)).setText(textl);
}
});
}catch (Exception ex)
{
Log.w("Error",""+ex);
}
}
});
thread.start();
}
});
/*
if( android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
if (Build.VERSION.SDK_INT >= 21) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) getActivity().getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats == null || stats.isEmpty()) {
Intent intentr = new Intent();
intent.setAction(Settings.ACTION_USAGE_ACCESS_SETTINGS);
getActivity().startActivity(intent);
}
}
}
*/
return view;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 8,645 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ChartMarker.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/ChartMarker.java | package com.myspy.myspyandroid.functions;
import android.content.Context;
import android.widget.TextView;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.MPPointF;
import com.myspy.myspyandroid.R;
/**
* Created by Miroslav Murin on 17.12.2016.
*/
public class ChartMarker extends MarkerView {
private TextView textchart;
final private String Number = getResources().getString(R.string.Number),
SMS = getResources().getString(R.string.OverallSMS);
public ChartMarker (Context context, int layoutResource) {
super(context, layoutResource);
textchart = (TextView) findViewById(R.id.MarkerText);
}
@Override
public void refreshContent(Entry e, Highlight highlight) {
textchart.setText(Number+": " + e.getData()+" "+SMS+": "+(int)e.getY());
super.refreshContent(e, highlight);
}
@Override
public MPPointF getOffset() {
return new MPPointF(-(getWidth() / 2), -getHeight());
}
} | 1,131 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
Encryption.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/Encryption.java | package com.myspy.myspyandroid.functions;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* A class to make more easy and simple the encrypt routines, this is the core of Encryption library
*/
public class Encryption {
/**
* The Builder used to create the Encryption instance and that contains the information about
* encryption specifications, this instance need to be private and careful managed
*/
private final Builder mBuilder;
/**
* The private and unique constructor, you should use the Encryption.Builder to build your own
* instance or get the default proving just the sensible information about encryption
*/
private Encryption(Builder builder) {
mBuilder = builder;
}
/**
* @return an default encryption instance or {@code null} if occur some Exception, you can
* create yur own Encryption instance using the Encryption.Builder
*/
public static Encryption getDefault(String key, String salt, byte[] iv) {
try {
return Builder.getDefaultBuilder(key, salt, iv).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* Encrypt a String
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
}
/**
* This is a sugar method that calls encrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be encrypted
*
* @return the encrypted String or {@code null} if you send the data as {@code null}
*/
public String encryptOrNull(String data) {
try {
return encrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls encrypt method in background, it is a good idea to use this
* one instead the default method because encryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be encrypted
* @param callback the Callback to handle the results
*/
public void encryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String encrypt = encrypt(data);
if (encrypt == null) {
callback.onError(new Exception("Encrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(encrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* Decrypt a String
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported or if
* the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* or if this has no installed provider that can
* provide the requested by the Builder secret key
* type or it is {@code null}, empty or in an invalid
* format
* @throws NoSuchPaddingException if no installed provider can provide the padding
* scheme in the Builder digest algorithm
* @throws InvalidAlgorithmParameterException if the specified parameters are inappropriate for
* the cipher
* @throws InvalidKeyException if the specified key can not be used to initialize
* the cipher instance
* @throws InvalidKeySpecException if the specified key specification cannot be used
* to generate a secret key
* @throws BadPaddingException if the padding of the data does not match the
* padding scheme
* @throws IllegalBlockSizeException if the size of the resulting bytes is not a
* multiple of the cipher block size
* @throws NullPointerException if the Builder digest algorithm is {@code null} or
* if the specified Builder secret key type is
* {@code null}
* @throws IllegalStateException if the cipher instance is not initialized for
* encryption or decryption
*/
public String decrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
if (data == null) return null;
byte[] dataBytes = Base64.decode(data, mBuilder.getBase64Mode());
SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
return new String(dataBytesDecrypted);
}
/**
* This is a sugar method that calls decrypt method and catch the exceptions returning
* {@code null} when it occurs and logging the error
*
* @param data the String to be decrypted
*
* @return the decrypted String or {@code null} if you send the data as {@code null}
*/
public String decryptOrNull(String data) {
try {
return decrypt(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* This is a sugar method that calls decrypt method in background, it is a good idea to use this
* one instead the default method because decryption can take several time and with this method
* the process occurs in a AsyncTask, other advantage is the Callback with separated methods,
* one for success and other for the exception
*
* @param data the String to be decrypted
* @param callback the Callback to handle the results
*/
public void decryptAsync(final String data, final Callback callback) {
if (callback == null) return;
new Thread(new Runnable() {
@Override
public void run() {
try {
String decrypt = decrypt(data);
if (decrypt == null) {
callback.onError(new Exception("Decrypt return null, it normally occurs when you send a null data"));
}
callback.onSuccess(decrypt);
} catch (Exception e) {
callback.onError(e);
}
}
}).start();
}
/**
* creates a 128bit salted aes key
*
* @param key encoded input key
*
* @return aes 128 bit salted key
*
* @throws NoSuchAlgorithmException if no installed provider that can provide the requested
* by the Builder secret key type
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws InvalidKeySpecException if the specified key specification cannot be used to
* generate a secret key
* @throws NullPointerException if the specified Builder secret key type is {@code null}
*/
private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
}
/**
* takes in a simple string and performs an sha1 hash
* that is 128 bits long...we then base64 encode it
* and return the char array
*
* @param key simple inputted string
*
* @return sha1 base64 encoded representation
*
* @throws UnsupportedEncodingException if the Builder charset name is not supported
* @throws NoSuchAlgorithmException if the Builder digest algorithm is not available
* @throws NullPointerException if the Builder digest algorithm is {@code null}
*/
private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
}
/**
* When you encrypt or decrypt in callback mode you get noticed of result using this interface
*/
public interface Callback {
/**
* Called when encrypt or decrypt job ends and the process was a success
*
* @param result the encrypted or decrypted String
*/
void onSuccess(String result);
/**
* Called when encrypt or decrypt job ends and has occurred an error in the process
*
* @param exception the Exception related to the error
*/
void onError(Exception exception);
}
/**
* This class is used to create an Encryption instance, you should provide ALL data or start
* with the Default Builder provided by the getDefaultBuilder method
*/
public static class Builder {
private byte[] mIv;
private int mKeyLength;
private int mBase64Mode;
private int mIterationCount;
private String mSalt;
private String mKey;
private String mAlgorithm;
private String mKeyAlgorithm;
private String mCharsetName;
private String mSecretKeyType;
private String mDigestAlgorithm;
private String mSecureRandomAlgorithm;
private SecureRandom mSecureRandom;
private IvParameterSpec mIvParameterSpec;
/**
* @return an default builder with the follow defaults:
* the default char set is UTF-8
* the default base mode is Base64
* the Secret Key Type is the PBKDF2WithHmacSHA1
* the default salt is "some_salt" but can be anything
* the default length of key is 128
* the default iteration count is 65536
* the default algorithm is AES in CBC mode and PKCS 5 Padding
* the default secure random algorithm is SHA1PRNG
* the default message digest algorithm SHA1
*/
public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
return new Builder()
.setIv(iv)
.setKey(key)
.setSalt(salt)
.setKeyLength(128)
.setKeyAlgorithm("AES")
.setCharsetName("UTF8")
.setIterationCount(1)
.setDigestAlgorithm("SHA1")
.setBase64Mode(Base64.DEFAULT)
.setAlgorithm("AES/CBC/PKCS5Padding")
.setSecureRandomAlgorithm("SHA1PRNG")
.setSecretKeyType("PBKDF2WithHmacSHA1");
}
/**
* Build the Encryption with the provided information
*
* @return a new Encryption instance with provided information
*
* @throws NoSuchAlgorithmException if the specified SecureRandomAlgorithm is not available
* @throws NullPointerException if the SecureRandomAlgorithm is {@code null} or if the
* IV byte array is null
*/
public Encryption build() throws NoSuchAlgorithmException {
setSecureRandom(SecureRandom.getInstance(getSecureRandomAlgorithm()));
setIvParameterSpec(new IvParameterSpec(getIv()));
return new Encryption(this);
}
/**
* @return the charset name
*/
private String getCharsetName() {
return mCharsetName;
}
/**
* @param charsetName the new charset name
*
* @return this instance to follow the Builder patter
*/
public Builder setCharsetName(String charsetName) {
mCharsetName = charsetName;
return this;
}
/**
* @return the algorithm
*/
private String getAlgorithm() {
return mAlgorithm;
}
/**
* @param algorithm the algorithm to be used
*
* @return this instance to follow the Builder patter
*/
public Builder setAlgorithm(String algorithm) {
mAlgorithm = algorithm;
return this;
}
/**
* @return the key algorithm
*/
private String getKeyAlgorithm() {
return mKeyAlgorithm;
}
/**
* @param keyAlgorithm the keyAlgorithm to be used in keys
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyAlgorithm(String keyAlgorithm) {
mKeyAlgorithm = keyAlgorithm;
return this;
}
/**
* @return the Base 64 mode
*/
private int getBase64Mode() {
return mBase64Mode;
}
/**
* @param base64Mode set the base 64 mode
*
* @return this instance to follow the Builder patter
*/
public Builder setBase64Mode(int base64Mode) {
mBase64Mode = base64Mode;
return this;
}
/**
* @return the type of aes key that will be created, on KITKAT+ the API has changed, if you
* are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*/
private String getSecretKeyType() {
return mSecretKeyType;
}
/**
* @param secretKeyType the type of AES key that will be created, on KITKAT+ the API has
* changed, if you are getting problems please @see <a href="http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html">http://android-developers.blogspot.com.br/2013/12/changes-to-secretkeyfactory-api-in.html</a>
*
* @return this instance to follow the Builder patter
*/
public Builder setSecretKeyType(String secretKeyType) {
mSecretKeyType = secretKeyType;
return this;
}
/**
* @return the value used for salting
*/
private String getSalt() {
return mSalt;
}
/**
* @param salt the value used for salting
*
* @return this instance to follow the Builder patter
*/
public Builder setSalt(String salt) {
mSalt = salt;
return this;
}
/**
* @return the key
*/
private String getKey() {
return mKey;
}
/**
* @param key the key.
*
* @return this instance to follow the Builder patter
*/
public Builder setKey(String key) {
mKey = key;
return this;
}
/**
* @return the length of key
*/
private int getKeyLength() {
return mKeyLength;
}
/**
* @param keyLength the length of key
*
* @return this instance to follow the Builder patter
*/
public Builder setKeyLength(int keyLength) {
mKeyLength = keyLength;
return this;
}
/**
* @return the number of times the password is hashed
*/
private int getIterationCount() {
return mIterationCount;
}
/**
* @param iterationCount the number of times the password is hashed
*
* @return this instance to follow the Builder patter
*/
public Builder setIterationCount(int iterationCount) {
mIterationCount = iterationCount;
return this;
}
/**
* @return the algorithm used to generate the secure random
*/
private String getSecureRandomAlgorithm() {
return mSecureRandomAlgorithm;
}
/**
* @param secureRandomAlgorithm the algorithm to generate the secure random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandomAlgorithm(String secureRandomAlgorithm) {
mSecureRandomAlgorithm = secureRandomAlgorithm;
return this;
}
/**
* @return the IvParameterSpec bytes array
*/
private byte[] getIv() {
return mIv;
}
/**
* @param iv the byte array to create a new IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIv(byte[] iv) {
mIv = iv;
return this;
}
/**
* @return the SecureRandom
*/
private SecureRandom getSecureRandom() {
return mSecureRandom;
}
/**
* @param secureRandom the Secure Random
*
* @return this instance to follow the Builder patter
*/
public Builder setSecureRandom(SecureRandom secureRandom) {
mSecureRandom = secureRandom;
return this;
}
/**
* @return the IvParameterSpec
*/
private IvParameterSpec getIvParameterSpec() {
return mIvParameterSpec;
}
/**
* @param ivParameterSpec the IvParameterSpec
*
* @return this instance to follow the Builder patter
*/
public Builder setIvParameterSpec(IvParameterSpec ivParameterSpec) {
mIvParameterSpec = ivParameterSpec;
return this;
}
/**
* @return the message digest algorithm
*/
private String getDigestAlgorithm() {
return mDigestAlgorithm;
}
/**
* @param digestAlgorithm the algorithm to be used to get message digest instance
*
* @return this instance to follow the Builder patter
*/
public Builder setDigestAlgorithm(String digestAlgorithm) {
mDigestAlgorithm = digestAlgorithm;
return this;
}
}
} | 23,525 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ContactName.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/ContactName.java | package com.myspy.myspyandroid.functions;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
/**
* Created by Miroslav Murin on 17.01.2017.
*/
public final class ContactName {
private ContactName(){}
/**
* Get from number contact name
* @param context Context
* @param phoneNumber Phone number
* @return String name of the contact
*/
public static String GetContactName(Context context, String phoneNumber) {
try {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
if (contactName != null && !contactName.isEmpty() && !contactName.equals("null"))
return contactName;
else
return phoneNumber;
}catch (Exception ex)
{
Log.w("Error",""+ex);
return phoneNumber;
}
}
}
| 1,606 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
GetLocation.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/GetLocation.java | package com.myspy.myspyandroid.functions;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.myspy.myspyandroid.MySpyService;
import com.myspy.myspyandroid.variables.LocationPoint;
import java.util.List;
import static android.content.Context.LOCATION_SERVICE;
/**
* Created by Miroslav Murin on 29.12.2016.
*/
public class GetLocation {
String provider = "";
LocationManager mLocationManager;
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Log.d("ProviderDisabled", "" + provider);
}
@Override
public void onLocationChanged(Location location) {
Log.d("LocationListener", "Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude());
MySpyService.serviceVariables.Path.add(new LocationPoint(location));
}
};
LocationManager locationManager;
public GetLocation(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
Log.d("provider", provider);
if (MySpyService.serviceSettings.PositionTime < 30000)
MySpyService.serviceSettings.PositionTime = 30000;
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d("GetLocation", "Requesting Start");
locationManager.requestLocationUpdates(provider, MySpyService.serviceSettings.PositionTime, 30, locationListener);
}
}
public LocationPoint GetLastKnownLocation(Context tcontext)
{
try {
mLocationManager = (LocationManager)tcontext.getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(tcontext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return new LocationPoint(bestLocation);
}catch (Exception ex)
{
return null;
}
}
public void StopGetLocation()
{
locationManager.removeUpdates(locationListener);
}
}
| 3,715 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
SaveFile.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/SaveFile.java | package com.myspy.myspyandroid.functions;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Miroslav Murin on 28.11.2016.
*/
public class SaveFile {
private File dir, file;
private Map<String,String> values = new HashMap<String, String>();
/**
*
* @param DirName Directory name
* @param context context
*/
public SaveFile(String DirName, Context context)
{
values.clear();
dir = context.getDir(DirName, Context.MODE_PRIVATE);
}
/**
*
* @param DirName Directory name
* @param Filename File name
* @param context context
*/
public SaveFile(String DirName, String Filename, Context context)
{
values.clear();
dir = context.getDir(DirName, Context.MODE_PRIVATE);
OpenFile(Filename);
}
/**
* Open file
* @param FileName filename
* @return boolean, true if successful
*/
public boolean OpenFile(String FileName)
{
try {
values.clear();
file = new File(dir, FileName);
return true;
}catch (Exception ex)
{
Log.w("SaveFile",ex);
return false;
}
}
/**
* Delete file if exist
* @return boolean, true if successful
*/
public boolean DeleteFile()
{
try {
if (file.exists())
{
file.delete();
return true;
}else{
return false;
}
}catch (Exception ex)
{
Log.w("SaveFile",ex);
return false;
}
}
/**
* Add item to file
* @param Tag Tag
* @param Value Value
*/
public void AddItem(String Tag, Object Value)
{
values.put(Tag,""+Value);
}
/**
* Get item you want to receive
* @param Tag Tag
* @return Object
*/
public Object GetItem(String Tag)
{
try {
return values.get(Tag);
}catch (Exception exc)
{
Log.w("SaveFile",exc);
return null;
}
}
/**
* Item exist?
* @param Tag Tag
* @return boolean
*/
public boolean ItemExist(String Tag)
{
return values.containsKey(Tag);
}
public void RemoveItem(String Tag)
{
values.remove(Tag);
}
public void Clear()
{
values.clear();
}
private String ToSafeString(String string)
{
string = string.replace("=","<EQL>");
string = string.replace("[","<LFT>");
string = string.replace("]","<RGT>");
return string;
}
private String FromSafeString(String string)
{
string = string.replace("<EQL>","=");
string = string.replace("<LFT>","[");
string = string.replace("<RGT>","]");
return string;
}
/**
* Save to file
* @return boolean , true if successful
*/
public boolean Save()
{
try {
FileOutputStream outStream = new FileOutputStream(file);
StringBuilder stringBuilder = new StringBuilder();
for(Map.Entry<String, String> entry : values.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
value = ToSafeString(value);
stringBuilder.append("["+key+"]="+value);
}
byte[] bytes = stringBuilder.toString().getBytes();
outStream.write(bytes);
outStream.flush();
outStream.close();
return true;
}catch (Exception ex)
{
return false;
}
}
/**
* Load file
* @return boolean , true if successful
*/
public boolean Load()
{
try {
values.clear();
FileInputStream inStream = new FileInputStream(file);
int n;
StringBuffer text = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = inStream.read(buffer)) != -1)
{
text.append(new String(buffer, 0, n));
}
String[] strings = (text.toString()).split("[=\\[\\]]");
int i=0;
boolean tag = true;
String Tag = "";
for(String str : strings)
{
if(!str.isEmpty()) {
if(tag)
{
Tag=str;
tag=false;
}else{
tag=true;
values.put(Tag,FromSafeString(str));
}
i++;
}
}
for(Map.Entry<String, String> entry : values.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Log.d("LOADED", key+" : "+value);
}
return true;
}catch (Exception ex)
{
return false;
}
}
}
| 5,246 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ClassSaver.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/ClassSaver.java | package com.myspy.myspyandroid.functions;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Type;
/**
* Created by Miroslav Murin on 30.11.2016.
*/
public class ClassSaver {
private Gson gson = new Gson();
/**
* Save Class to JSON String
* @param Class Class you want to save
* @return String in JSON Format
*/
public String SaveClass(Object Class)
{
try{
return gson.toJson(Class);
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return null;
}
}
/**
* Load Class from String
* @param Json String
* @param type Type of class
* @return Object
*/
public Object LoadClass(String Json, Type type)
{
try{
return gson.fromJson(Json,type);
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return null;
}
}
/**
* Save class to file
* @param ClassToSave Class you want to save
* @param Dirname Directory name
* @param Filename File name
* @param context context
* @return boolean, true if successful
*/
public boolean SaveClassToFile(Object ClassToSave, String Dirname, String Filename, Context context)
{
try{
File dir = context.getDir(Dirname, Context.MODE_PRIVATE);
File file = new File(dir, Filename);
FileOutputStream outStream = new FileOutputStream(file);
byte[] bytes = gson.toJson(ClassToSave).getBytes();
outStream.write(bytes);
outStream.flush();
outStream.close();
return true;
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return false;
}
}
/**
* Save class to file
* @param ClassToSave Class you want to save
* @param file File to save
* @return boolean, true if successful
*/
public boolean SaveClassToSpecificFile(Object ClassToSave, File file)
{
try{
FileOutputStream outStream = new FileOutputStream(file);
byte[] bytes = gson.toJson(ClassToSave).getBytes();
outStream.write(bytes);
outStream.flush();
outStream.close();
return true;
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return false;
}
}
/**
* File exists?
* @param Dirname Directory name
* @param Filename File name
* @param context context
* @return boolean, true if exists
*/
public boolean FileExist(String Dirname, String Filename, Context context)
{
File dir = context.getDir(Dirname, Context.MODE_PRIVATE);
Log.d("Path",dir.getPath());
dir.mkdirs();
File file = new File(dir, Filename);
return file.exists();
}
/**
* Return internal storage file
* @param Dirname Directory name
* @param Filename File name
* @param context Context
* @return File
*/
public File GetFile(String Dirname, String Filename, Context context)
{
File dir = context.getDir(Dirname, Context.MODE_PRIVATE);
File file = new File(dir, Filename);
return file;
}
/**
* Load class from file
* @param type Class type
* @param Dirname Directory name
* @param Filename File name
* @param context context
* @return Object
*/
public Object LoadClassFromFile(Type type, String Dirname, String Filename, Context context)
{
try{
File dir = context.getDir(Dirname, Context.MODE_PRIVATE);
File file = new File(dir, Filename);
FileInputStream inStream = new FileInputStream(file);
int n;
StringBuffer text = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = inStream.read(buffer)) != -1)
{
text.append(new String(buffer, 0, n));
}
return gson.fromJson(text.toString(),type);
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return null;
}
}
/**
* Load class from file
* @param type Type of class
* @param file File to load
* @return Object
*/
public Object LoadClassFromSpecificFile(Type type, File file)
{
try{
FileInputStream inStream = new FileInputStream(file);
int n;
StringBuffer text = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = inStream.read(buffer)) != -1)
{
text.append(new String(buffer, 0, n));
}
return gson.fromJson(text.toString(),type);
}catch (Exception ex)
{
Log.w("ClassSaver",ex);
return null;
}
}
}
| 5,085 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
HTTPWork.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/functions/HTTPWork.java | package com.myspy.myspyandroid.functions;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Miroslav Murin on 04.01.2017.
*/
public final class HTTPWork {
private HTTPWork()
{
}
/**
* Convert string to URL format
* @param url not formated url
* @return String url formated url
*/
public static String ConvertString(String url)
{
url = url.replace(" ","%20");
url = url.replace("!","%21");
url = url.replace("\"","%22");
url = url.replace("#","%23");
url = url.replace("$","%24");
url = url.replace("'","%27");
url = url.replace("(","%28");
url = url.replace(")","%29");
return url;
}
/**
* Get from url
* @param Url URL from you want to receive
* @return String
*/
public static String GET(String Url) {
HttpURLConnection urlConnection = null;
try {
Url = ConvertString(Url);
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
}catch (Exception ex)
{
ex.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
return total.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return null;
}
/**
* Get from url
* @param Url URL from you want to receive
* @param LineSize (Int) Count of lines you want to read
* @return String
*/
public static String GET(String Url, int LineSize) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
}catch (Exception ex)
{
ex.printStackTrace();
}
try {
int linec = 0;
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null && linec <LineSize) {
total.append(line).append('\n');
linec++;
}
return total.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return null;
}
/**
* Get from url
* @param Url URL from you want to receive
* @param WhileWord Read from URL, while text will be equals to word
* @return String
*/
public static String GET(String Url, String WhileWord) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
}catch (Exception ex)
{
ex.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
if(line.replace(" ","").equals(WhileWord))
break;
}
return total.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return null;
}
/**
* Get from url
* @param Url URL from you want to receive
* @param WhileWord Read from URL, while text will be equals to word
* @param count Count of words to break cycle
* @return String
*/
public static String GET(String Url, String WhileWord, int count) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
}catch (Exception ex)
{
ex.printStackTrace();
}
try {
int wordsfound = 0;
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
if(line.replace(" ","").equals(WhileWord)) {
wordsfound++;
if(wordsfound>=count)
break;
}
}
return total.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return null;
}
}
| 5,553 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ApplicationReportActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/ApplicationReportActivity.java |
package com.myspy.myspyandroid.Reports;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.myspy.myspyandroid.R;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.variables.ApplicationInformation;
import com.myspy.myspyandroid.variables.CallInfo;
import com.myspy.myspyandroid.variables.ServiceVariables;
import org.w3c.dom.Text;
import java.io.File;
import java.util.Calendar;
public class ApplicationReportActivity extends Activity {
ServiceVariables srcvrb;
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_application_report);
Intent intent = getIntent();
String fileloc = intent.getStringExtra("File");
ClassSaver classSaver = new ClassSaver();
srcvrb = (ServiceVariables) classSaver.LoadClassFromSpecificFile(ServiceVariables.class,new File(fileloc));
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbarappreport);
toolbar.setSubtitle(""+srcvrb.calendar.get(Calendar.DAY_OF_MONTH)+"."+(srcvrb.calendar.get(Calendar.MONTH)+1)+"."+srcvrb.calendar.get(Calendar.YEAR));
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
drawTable();
}
void drawTable()
{
TableLayout table = (TableLayout) findViewById(R.id.tablelayoutApps);
table.removeAllViewsInLayout();
Log.d("APPCOUNT","Size: "+srcvrb.Appinfo.size());
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT);
params.setMargins(10,5,10,5);
TableRow rowinfo = new TableRow(this);
rowinfo.setBackgroundColor(getResources().getColor(R.color.colorBox2));
rowinfo.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
TextView textViewhinticon = new TextView(this);
textViewhinticon.setText("");
textViewhinticon.setTextSize(20f);
rowinfo.addView(textViewhinticon);
TextView textViewhint = new TextView(this);
textViewhint.setText(getResources().getString(R.string.ApplicationName));
textViewhint.setGravity(Gravity.CENTER);
textViewhint.setLayoutParams(params);
textViewhint.setTextColor(Color.WHITE);
textViewhint.setTextSize(15f);
rowinfo.addView(textViewhint);
TextView textViewhint2 = new TextView(this);
textViewhint2.setText(getResources().getString(R.string.RunningTime));
textViewhint2.setGravity(Gravity.CENTER);
textViewhint2.setLayoutParams(params);
textViewhint2.setTextColor(Color.WHITE);
textViewhint2.setTextSize(15f);
rowinfo.addView(textViewhint2);
TextView textViewhint3 = new TextView(this);
textViewhint3.setText(getResources().getString(R.string.LastTimeRunning));
textViewhint3.setGravity(Gravity.CENTER);
textViewhint3.setLayoutParams(params);
textViewhint3.setTextColor(Color.WHITE);
textViewhint3.setTextSize(15f);
rowinfo.addView(textViewhint3);
table.addView(rowinfo);
for (ApplicationInformation info : srcvrb.Appinfo) {
TableRow row = new TableRow(this);
try {
ImageView imageView = new ImageView(this);
Drawable icon = null;
icon = getPackageManager().getApplicationIcon(info.PackageName);
imageView.setImageDrawable(icon);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(64, 64);
layoutParams.setMargins(8,5,3,5);
layoutParams.gravity = Gravity.LEFT;
imageView.setLayoutParams(layoutParams);
row.addView(imageView);
} catch (Exception ex) {
Log.w("Error",""+ex);
Space space = new Space(this);
row.addView(space);
}
TextView textView = new TextView(this);
textView.setText(info.ApplicationName);
textView.setGravity(Gravity.CENTER);
textView.setLayoutParams(params);
textView.setTextColor(Color.BLACK);
textView.setTextSize(16f);
row.addView(textView);
TextView textView2 = new TextView(this);
textView2.setText(info.TimeFormat());
textView2.setGravity(Gravity.CENTER);
textView2.setTextColor( getResources().getColor(R.color.colorMarker));
textView2.setLayoutParams(params);
row.addView(textView2);
TextView textView3 = new TextView(this);
textView3.setText(info.LastTimeRunning);
textView3.setGravity(Gravity.CENTER);
textView3.setLayoutParams(params);
row.addView(textView3);
table.addView(row);
}
}
}
| 6,011 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
MapPathReportActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/MapPathReportActivity.java | package com.myspy.myspyandroid.Reports;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.myspy.myspyandroid.BuildConfig;
import com.myspy.myspyandroid.R;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.variables.LocationPoint;
import com.myspy.myspyandroid.variables.ServiceVariables;
import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Polyline;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
public class MapPathReportActivity extends Activity {
ServiceVariables srcvrb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_path_report);
Intent intent = getIntent();
String fileloc = intent.getStringExtra("File");
ClassSaver classSaver = new ClassSaver();
srcvrb = (ServiceVariables) classSaver.LoadClassFromSpecificFile(ServiceVariables.class,new File(fileloc));
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbarmap);
toolbar.setSubtitle(""+srcvrb.calendar.get(Calendar.DAY_OF_MONTH)+"."+(srcvrb.calendar.get(Calendar.MONTH)+1)+"."+srcvrb.calendar.get(Calendar.YEAR));
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants.setUserAgentValue(BuildConfig.APPLICATION_ID);
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
IMapController mapController = map.getController();
mapController.setZoom(9);
ArrayList<GeoPoint> points = new ArrayList<>();
for (LocationPoint locationPoint : srcvrb.Path)
{
points.add(locationPoint.ToGeoPoint());
}
if(!points.isEmpty())
mapController.setCenter(points.get(0));
else
mapController.setCenter(new GeoPoint(0.0,0.0));
Log.d("Points",""+points.size());
Polyline polyline = new Polyline();
polyline.setColor(Color.rgb(192, 57, 43));
polyline.setPoints(points);
map.getOverlays().add(polyline);
map.invalidate();
}
}
| 2,794 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ChooseReportActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/ChooseReportActivity.java | package com.myspy.myspyandroid.Reports;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.myspy.myspyandroid.R;
import java.io.File;
public class ChooseReportActivity extends AppCompatActivity {
int ReportCode = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_report);
LinearLayout reports = (LinearLayout) findViewById(R.id.DayReports);
Intent intent = getIntent();
ReportCode = intent.getIntExtra("Report",0);
try {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}catch (Exception e)
{
Log.w("Error",""+e);
}
File dirn = new File( this.getDir("MySpy", Context.MODE_PRIVATE).getPath()+"/Monitoring");
File[] files = dirn.listFiles();
int k=1;
Log.d("Files",""+files.length);
for(File f : files)
{
Log.d("SMS FILE",""+f.getPath());
Button button = new Button(this);
button.setText(f.getName().replace(".dat","").replace("_",".").replace("Day.",""));
button.setTag(f.getPath());
button.setOnClickListener(onClickListener);
button.setTextColor(Color.WHITE);
if((k%2)==0)
button.setBackgroundResource(R.drawable.buttonstyle);
else
button.setBackgroundResource(R.drawable.buttonstylelight);
reports.addView(button);
k++;
}
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
Log.d("Report",""+v.getTag());
Intent intent = null;
boolean newActivity = true;
if (ReportCode==1)
intent = new Intent(ChooseReportActivity.this, SMSReportActivity.class);
else if (ReportCode==2)
intent = new Intent(ChooseReportActivity.this, CallsReportActivity.class);
else if (ReportCode==3)
intent = new Intent(ChooseReportActivity.this, MapPathReportActivity.class);
else if (ReportCode==4) {
newActivity = false;
Remove(v.getTag().toString(),((Button)v).getText().toString());
}
else if (ReportCode==5) {
intent = new Intent(ChooseReportActivity.this, ApplicationReportActivity.class);
}
else
intent = new Intent(ChooseReportActivity.this, SMSReportActivity.class);
if(newActivity) {
intent.putExtra("File", "" + v.getTag());
ChooseReportActivity.this.startActivity(intent);
}
};
};
void Remove(String filelocation, final String name)
{
final File file = new File(filelocation);
final Context cont = this;
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.Removereport))
.setMessage(getResources().getString(R.string.Removereporttext)+ " "+ name+" ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(file.delete())
{
Log.d("FileDeleted","Deleted "+file.getAbsolutePath());
Toast.makeText(cont,getResources().getString(R.string.Removed),Toast.LENGTH_SHORT).show();
finish();
}else{
Log.d("FailedDeleting","Failed "+file.getAbsolutePath());
Toast.makeText(cont,getResources().getString(R.string.FailedRemoveReport),Toast.LENGTH_LONG).show();
finish();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
| 4,852 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
CallsReportActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/CallsReportActivity.java | package com.myspy.myspyandroid.Reports;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Space;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.myspy.myspyandroid.R;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.ContactName;
import com.myspy.myspyandroid.variables.CallInfo;
import com.myspy.myspyandroid.variables.ServiceVariables;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Calendar;
public class CallsReportActivity extends Activity {
ServiceVariables srcvrb;
TableLayout table;
int out=0,in=0,missed=0;
long inlength = 0, outlength = 0;
DecimalFormat decimalFormat = new DecimalFormat("00");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calls_report);
Intent intent = getIntent();
String fileloc = intent.getStringExtra("File");
ClassSaver classSaver = new ClassSaver();
srcvrb = (ServiceVariables) classSaver.LoadClassFromSpecificFile(ServiceVariables.class,new File(fileloc));
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbarcalls);
toolbar.setSubtitle(""+srcvrb.calendar.get(Calendar.DAY_OF_MONTH)+"."+(srcvrb.calendar.get(Calendar.MONTH)+1)+"."+srcvrb.calendar.get(Calendar.YEAR));
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
table = (TableLayout) findViewById(R.id.tablelayoutCall);
DrawLayout();
MakeGraph();
MakeGraphLength();
}
void DrawLayout()
{
table.removeAllViewsInLayout();
missed=0;
out=0;
in=0;
outlength = 0;
inlength = 0;
TableRow rowinfo = new TableRow(this);
rowinfo.addView(new Space(this));
TextView textViewa = new TextView(this);
textViewa.setText(getResources().getString(R.string.Number));
textViewa.setTextSize(15);
textViewa.setTextColor(Color.BLACK);
rowinfo.addView(textViewa);
TextView textViewa2 = new TextView(this);
textViewa2.setText(getResources().getString(R.string.Length));
textViewa2.setTextSize(15);
textViewa2.setTextColor(Color.rgb(22, 160, 133));
textViewa2.setPadding(30,0,0,0);
rowinfo.addView(textViewa2);
TextView textViewa3 = new TextView(this);
textViewa3.setText(getResources().getString(R.string.Time));
textViewa3.setTextSize(15);
textViewa3.setTextColor(Color.GRAY);
textViewa3.setPadding(25,0,0,0);
rowinfo.addView(textViewa3);
rowinfo.setBackgroundColor(Color.rgb(189, 195, 199));
table.addView(rowinfo);
for (CallInfo info : srcvrb.CallList) {
TableRow row = new TableRow(this);
ImageView imageView = new ImageView(this);
if(info.Missed) {
imageView.setImageResource(R.drawable.callmissed);
missed++;
}
else{
if(info.OutGoingCall) {
imageView.setImageResource(R.drawable.callmade);
out++;
outlength += info.CallLength;
}
else {
imageView.setImageResource(R.drawable.callreceived);
in++;
inlength += info.CallLength;
}
}
imageView.setPadding(6,10,10,0);
row.addView(imageView);
imageView.getLayoutParams().width = 42;
imageView.getLayoutParams().height = 42;
int Minutes = (int) Math.floor(info.CallLength/60);
int Seconds = (info.CallLength-(Minutes*60));
TextView textView = new TextView(this);
textView.setText(ContactName.GetContactName(this ,info.Number));
textView.setPadding(0,5,0,0);
textView.setTextSize(20);
textView.setTextColor(Color.BLACK);
row.addView(textView);
TextView textViewt = new TextView(this);
if(!info.Missed)
textViewt.setText(decimalFormat.format( Minutes)+":"+decimalFormat.format( Seconds));
else
textViewt.setText("---");
textViewt.setPadding(30,0,0,0);
textViewt.setTextSize(18);
textViewt.setTextColor(Color.rgb(22, 160, 133));
row.addView(textViewt);
TextView textView2 = new TextView(this);
textView2.setText(info.DateTimeOnly);
textView2.setPadding(20,0,0,0);
textView2.setTextSize(12);
textView2.setTextColor(Color.GRAY);
row.addView(textView2);
table.addView(row);
}
}
void MakeGraph()
{
PieChart pieChart = (PieChart) findViewById(R.id.chartcall);
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.95f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleColor(Color.WHITE);
pieChart.setTransparentCircleAlpha(110);
pieChart.setHoleRadius(58f);
pieChart.setTransparentCircleRadius(62f);
pieChart.setDrawCenterText(true);
pieChart.setRotationAngle(0);
pieChart.setRotationEnabled(true);
pieChart.setHighlightPerTapEnabled(true);
PieDataSet dataSet = new PieDataSet(null,getResources().getString(R.string.CallsCountStatistics));
dataSet.addEntry(new PieEntry(in,getResources().getString(R.string.CallReceived)));
dataSet.addEntry(new PieEntry(out,getResources().getString(R.string.CallMade)));
dataSet.addEntry(new PieEntry(missed,getResources().getString(R.string.CallMissed)));
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new OnlyValueFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
pieChart.setData(data);
pieChart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
Legend l = pieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
pieChart.setEntryLabelColor(Color.BLACK);
pieChart.setEntryLabelTextSize(10f);
}
void MakeGraphLength()
{
PieChart pieChart = (PieChart) findViewById(R.id.chartcalllength);
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5, 10, 5, 5);
pieChart.setDragDecelerationFrictionCoef(0.95f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(Color.WHITE);
pieChart.setTransparentCircleColor(Color.WHITE);
pieChart.setTransparentCircleAlpha(110);
pieChart.setHoleRadius(58f);
pieChart.setTransparentCircleRadius(62f);
pieChart.setDrawCenterText(true);
pieChart.setRotationAngle(0);
pieChart.setRotationEnabled(true);
pieChart.setHighlightPerTapEnabled(true);
PieDataSet dataSet = new PieDataSet(null,getResources().getString(R.string.CallsLength));
dataSet.addEntry(new PieEntry(outlength,getResources().getString(R.string.MadeLength)));
dataSet.addEntry(new PieEntry(inlength,getResources().getString(R.string.ReceivedLength)));
dataSet.setColors(ColorTemplate.PASTEL_COLORS);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new TimeValueFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
pieChart.setData(data);
pieChart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
Legend l = pieChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
pieChart.setEntryLabelColor(Color.BLACK);
pieChart.setEntryLabelTextSize(10f);
}
public class OnlyValueFormatter implements IValueFormatter {
private DecimalFormat mFormat;
OnlyValueFormatter() {
mFormat = new DecimalFormat("###,###,##0.0");
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return (int)entry.getY()+" ( "+mFormat.format(value)+" % )";
}
}
public class TimeValueFormatter implements IValueFormatter {
private DecimalFormat mFormat;
TimeValueFormatter() {
mFormat = new DecimalFormat("###,###,##0.0");
}
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
int Minutes = (int) Math.floor(entry.getY()/60);
int Seconds = ((int)entry.getY()-(Minutes*60));
return decimalFormat.format(Minutes)+":"+decimalFormat.format(Seconds)+" ( "+mFormat.format(value)+" % )";
}
}
}
| 10,812 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ReadSMSActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/ReadSMSActivity.java | package com.myspy.myspyandroid.Reports;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.gson.Gson;
import com.myspy.myspyandroid.R;
import com.myspy.myspyandroid.functions.ContactName;
import com.myspy.myspyandroid.variables.SMSInfo;
import com.myspy.myspyandroid.variables.SMSInfoRead;
import com.myspy.myspyandroid.variables.ServiceVariables;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class ReadSMSActivity extends Activity {
final float Bodysize = 16;
final float Timesize = 12;
final int DateColor = Color.rgb(127, 140, 141);
Spinner spinner,spinnerfilter;
List<String> categories = new ArrayList<String>();
ServiceVariables srcvrb;
LinearLayout smslayout;
List<SMSInfoRead> SMSinfolist = new ArrayList<SMSInfoRead>();
int lastf = -5 , last = -5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_sms);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbarreadsms);
Intent intent = getIntent();
String var = intent.getStringExtra("Variables");
Gson gson = new Gson();
srcvrb = gson.fromJson(var,ServiceVariables.class);
categories.add(getResources().getString(R.string.All));
for(SMSInfo info : srcvrb.SMSList)
{
if(!categories.contains(info.From))
{
categories.add(info.From);
}
SMSinfolist.add(new SMSInfoRead(info,false));
}
for(SMSInfo info : srcvrb.SMSOutList)
{
if(!categories.contains(info.From))
{
categories.add(info.From);
}
SMSinfolist.add(new SMSInfoRead(info,true));
}
for (int i=0;i< SMSinfolist.size();i++)
{
for (int j=i+1;j< SMSinfolist.size();j++)
{
if(SMSinfolist.get(i).TimeVar>SMSinfolist.get(j).TimeVar)
{
SMSInfoRead temp = SMSinfolist.get(i);
SMSinfolist.set(i,SMSinfolist.get(j));
SMSinfolist.set(j,temp);
}
}
}
spinner = (Spinner) findViewById(R.id.spinnerSMS);
spinnerfilter = (Spinner) findViewById(R.id.spinnerFilter);
smslayout = (LinearLayout) findViewById(R.id.SMSReadLayout);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("Selected",""+position+" "+categories.get(position));
AddSMSToView();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
List<String> filters = new ArrayList<String>();
filters.add(getResources().getString(R.string.All));
filters.add(getResources().getString(R.string.Received));
filters.add(getResources().getString(R.string.Sent));
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,filters);
dataAdapter2.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerfilter.setAdapter(dataAdapter2);
spinnerfilter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
AddSMSToView();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toolbar.setSubtitle(getResources().getString(R.string.SMSList)+": "+srcvrb.calendar.get(Calendar.DAY_OF_MONTH)+"."+(srcvrb.calendar.get(Calendar.MONTH)+1)+"."+srcvrb.calendar.get(Calendar.YEAR));
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
AddSMSToView();
}
void AddSMSToView()
{
Log.d("SPINNER",""+spinner.getSelectedItem()+" POS:"+spinner.getSelectedItemPosition());
if(last != spinner.getSelectedItemPosition() || lastf != spinnerfilter.getSelectedItemPosition()) {
lastf = spinnerfilter.getSelectedItemPosition();
last = spinner.getSelectedItemPosition();
smslayout.removeAllViewsInLayout();
for (SMSInfoRead info : SMSinfolist) {
if(spinner.getSelectedItemPosition() == 0 || spinner.getSelectedItem().toString().equals(info.From)) {
short FilterI = (short) ((info.Sent) ? 2 : 1);
if(FilterI == spinnerfilter.getSelectedItemPosition() || spinnerfilter.getSelectedItemPosition()==0) {
TextView txt = new TextView(this);
txt.setText(info.Body);
txt.setTextSize(Bodysize);
if (!info.Sent)
txt.setTextColor(Color.BLACK);
else
txt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
TextView txt2 = new TextView(this);
txt2.setText(ContactName.GetContactName(this ,info.From) + " " + info.TimeAction);
txt2.setTextSize(Timesize);
txt2.setTextColor(DateColor);
smslayout.addView(txt);
smslayout.addView(txt2);
}
}
}
}
}
}
| 6,559 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
SMSReportActivity.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Reports/SMSReportActivity.java | package com.myspy.myspyandroid.Reports;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.myspy.myspyandroid.R;
import com.myspy.myspyandroid.functions.ChartMarker;
import com.myspy.myspyandroid.functions.ClassSaver;
import com.myspy.myspyandroid.functions.ContactName;
import com.myspy.myspyandroid.variables.SMSInfo;
import com.myspy.myspyandroid.variables.ServiceVariables;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class SMSReportActivity extends Activity {
ServiceVariables srcvrb;
private Map<String,Integer> smsmap = new HashMap<String, Integer>();
private Map<String,Integer> smsoutmap = new HashMap<String, Integer>();
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smsreport);
Intent intent = getIntent();
String fileloc = intent.getStringExtra("File");
ClassSaver classSaver = new ClassSaver();
srcvrb = (ServiceVariables) classSaver.LoadClassFromSpecificFile(ServiceVariables.class,new File(fileloc));
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar)findViewById(R.id.toolbardate);
((TextView)findViewById(R.id.smsreceived)).setText(getResources().getString(R.string.SMSReceived)+": "+srcvrb.SMSList.size());
((TextView)findViewById(R.id.smssended)).setText(getResources().getString(R.string.SMSSended)+": "+srcvrb.SMSOutList.size());
toolbar.setSubtitle(""+srcvrb.calendar.get(Calendar.DAY_OF_MONTH)+"."+(srcvrb.calendar.get(Calendar.MONTH)+1)+"."+srcvrb.calendar.get(Calendar.YEAR));
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
int count = 0;
for(SMSInfo inf : srcvrb.SMSList)
{
if(smsmap.containsKey(inf.From))
{
count = smsmap.get(inf.From);
smsmap.remove(inf.From);
smsmap.put(inf.From,count+1);
}else
{
smsmap.put(inf.From,1);
}
}
for(SMSInfo inf : srcvrb.SMSOutList)
{
if(smsoutmap.containsKey(inf.From))
{
count = smsoutmap.get(inf.From);
smsoutmap.remove(inf.From);
smsoutmap.put(inf.From,count+1);
}else
{
smsoutmap.put(inf.From,1);
}
}
SetSMSStatsChart();
SetNumbersInfoChart();
}
void SetSMSStatsChart()
{
PieChart SMSStatschart = (PieChart) findViewById(R.id.chartSMSStats);
SMSStatschart.setUsePercentValues(true);
SMSStatschart.getDescription().setEnabled(false);
SMSStatschart.setExtraOffsets(5, 10, 5, 5);
SMSStatschart.setDragDecelerationFrictionCoef(0.95f);
SMSStatschart.setDrawHoleEnabled(true);
SMSStatschart.setHoleColor(Color.WHITE);
SMSStatschart.setTransparentCircleColor(Color.WHITE);
SMSStatschart.setTransparentCircleAlpha(110);
SMSStatschart.setHoleRadius(58f);
SMSStatschart.setTransparentCircleRadius(62f);
SMSStatschart.setDrawCenterText(true);
SMSStatschart.setRotationAngle(0);
SMSStatschart.setRotationEnabled(true);
SMSStatschart.setHighlightPerTapEnabled(true);
PieDataSet dataSet = new PieDataSet(null,getResources().getString(R.string.SMSStatistics));
dataSet.addEntry(new PieEntry(srcvrb.SMSList.size(),getResources().getString(R.string.SMSReceived)));
dataSet.addEntry(new PieEntry(srcvrb.SMSOutList.size(),getResources().getString(R.string.SMSSended)));
dataSet.setColors(ColorTemplate.JOYFUL_COLORS);
dataSet.setSliceSpace(3f);
dataSet.setSelectionShift(5f);
PieData data = new PieData(dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.BLACK);
SMSStatschart.setData(data);
SMSStatschart.animateY(1500, Easing.EasingOption.EaseInOutQuad);
Legend l = SMSStatschart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.VERTICAL);
l.setDrawInside(false);
l.setXEntrySpace(7f);
l.setYEntrySpace(0f);
l.setYOffset(0f);
SMSStatschart.setEntryLabelColor(Color.BLACK);
SMSStatschart.setEntryLabelTextSize(10f);
}
void SetNumbersInfoChart()
{
BarChart mChart = (BarChart) findViewById(R.id.SMSInfochart);
mChart.setDrawGridBackground(false);
mChart.getDescription().setEnabled(false);
ChartMarker mv = new ChartMarker(this, R.layout.chartmarkerlayout);
mv.setChartView(mChart); // For bounds control
mChart.setMarker(mv); // Set the marker to the chart
// scaling can now only be done on x- and y-axis separately
mChart.setPinchZoom(false);
mChart.setDrawBarShadow(false);
mChart.setDrawValueAboveBar(true);
mChart.setHighlightFullBarEnabled(false);
mChart.getAxisLeft().setEnabled(false);
// mChart.getAxisRight().setAxisMaximum(25f);
mChart.getAxisRight().setAxisMinimum(0f);
mChart.getAxisRight().setDrawGridLines(false);
mChart.getAxisRight().setDrawZeroLine(true);
mChart.getAxisRight().setLabelCount(7, false);
mChart.getAxisRight().setValueFormatter(new CustomFormatter());
mChart.getAxisRight().setTextSize(9f);
mChart.animateY(1500);
XAxis xAxis = mChart.getXAxis();
xAxis.setEnabled(false);
Legend l = mChart.getLegend();
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
l.setFormSize(8f);
l.setFormToTextSpace(4f);
l.setXEntrySpace(6f);
ArrayList<BarEntry> yValues = new ArrayList<BarEntry>();
int kl=1;
for(Map.Entry<String, Integer> entry : smsmap.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
int valueout = 0;
if(smsoutmap.containsKey(key))
{
valueout = smsoutmap.get(key);
smsoutmap.remove(key);
}
Log.d("ENTRY",key+": "+value+" "+valueout);
yValues.add(new BarEntry(kl, new float[]{ value,valueout },key));
kl++;
}
for(Map.Entry<String, Integer> entry : smsoutmap.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
Log.d("ENTRY",key+": "+value);
yValues.add(new BarEntry(kl, new float[]{ 0,value },key));
kl++;
}
BarDataSet set = new BarDataSet(yValues, getResources().getString(R.string.SMSMessaging));
set.setValueFormatter(new CustomFormatter());
set.setValueTextSize(7f);
set.setAxisDependency(YAxis.AxisDependency.RIGHT);
set.setColors(new int[] {Color.rgb(67,67,72), Color.rgb(124,181,236)});
set.setStackLabels(new String[]{
getResources().getString(R.string.Received),getResources().getString(R.string.Sent)
});
BarData data = new BarData(set);
mChart.setData(data);
mChart.invalidate();
}
private class CustomFormatter implements IValueFormatter, IAxisValueFormatter
{
private DecimalFormat mFormat;
public CustomFormatter() {
mFormat = new DecimalFormat("###");
}
// data
@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
return mFormat.format(Math.abs(value)) + " "+getResources().getString(R.string.SMS_Info_Number)+" "+ ContactName.GetContactName(context,entry.getData().toString());
}
// YAxis
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mFormat.format(Math.abs(value));
}
}
public void ReadSMS(View view)
{
Intent intent = new Intent(SMSReportActivity.this, ReadSMSActivity.class);
Gson gson = new Gson();
intent.putExtra("Variables",""+gson.toJson(srcvrb));
SMSReportActivity.this.startActivity(intent);
}
}
| 10,233 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ApplicationInformation.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/ApplicationInformation.java | package com.myspy.myspyandroid.variables;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
/**
* Created by Miroslav Murin on 03.02.2017.
*/
public class ApplicationInformation extends ApplicationPackage {
public int Time = 0;
public String LastTimeRunning = "";
public ApplicationInformation(String packageName, String applicationName) {
super(packageName, applicationName);
Time = 0;
}
public ApplicationInformation(String packageName, String applicationName,int time)
{
super(packageName,applicationName);
Time = time;
}
/**
* Add time in seconds and automatically set Last Time Running
* @param time seconds
*/
public void AddTime(int time)
{
Time += time;
LastTimeRunning = GetCurrentTime();
}
/**
* Returns HH:MM:SS string of app running time
* @return String HH:MM:SS
*/
public String TimeFormat()
{
int Hours = (int) Math.floor(Time/3600);
int Minutes = (int) Math.floor((Time-(Hours*3600))/60);
DecimalFormat decimalFormat = new DecimalFormat("00");
return decimalFormat.format(Hours)+":"+decimalFormat.format(Minutes);
}
/**
* Get current time in HH:mm:ss format
* @return String time in HH:mm:ss format
*/
public static String GetCurrentTime()
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
return format.format(Calendar.getInstance().getTime());
}
/**
* Check if arraylist contains package name
* @param Applications ApplicationInformation ArrayList
* @param PackageName PackageName to check
* @return Boolean - true if contains
*/
public static boolean ContainsPackageName(List<ApplicationInformation> Applications, String PackageName)
{
for(ApplicationInformation app : Applications){
if(PackageName.equals(app.PackageName))
return true;
}
return false;
}
/**
* Get position in arraylist containing specific package name
* @param Applications ApplicationInformation ArrayList
* @param PackageName PackageName to check
* @return int position
*/
public static int GetPosition(List<ApplicationInformation> Applications, String PackageName)
{
for(int i=0;i<Applications.size();i++)
{
if(PackageName.equals(Applications.get(i).PackageName))
return i;
}
return -1;
}
}
| 2,636 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
LocationPoint.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/LocationPoint.java | package com.myspy.myspyandroid.variables;
import android.location.Location;
import org.osmdroid.util.GeoPoint;
/**
* Created by Miroslav Murin on 29.12.2016.
*/
public class LocationPoint {
public float Latitude = 0; //sirka
public float Longitude = 0; //dlzka
/**
* New LocationPoint from latitude, longitude
* @param latitude Latitude
* @param longitude Longitude
*/
public LocationPoint(float latitude, float longitude)
{
Latitude = latitude;
Longitude = longitude;
}
/**
* New LocationPoint from Location
* @param location Location
*/
public LocationPoint(Location location)
{
Latitude = (float)location.getLatitude();
Longitude = (float)location.getLongitude();
}
/**
* LocationPoint to GeoPoint
* @return GeoPoint
*/
public GeoPoint ToGeoPoint()
{
return new GeoPoint(Latitude,Longitude);
}
}
| 956 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ApplicationPackage.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/ApplicationPackage.java | package com.myspy.myspyandroid.variables;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Miroslav Murin on 02.02.2017.
*/
public class ApplicationPackage implements Comparable<ApplicationPackage>{
public String PackageName = "";
public String ApplicationName = "";
public ApplicationPackage(String packageName, String applicationName)
{
PackageName = packageName;
ApplicationName = applicationName;
}
/**
* Return String ArrayList (Application name) from ApplicationPackage ArrayList
* @param Applications ApplicationPackage ArrayList
* @return ApplicationPackage ArrayList - Application Name
*/
public static ArrayList<String> ApplicationName(ArrayList<ApplicationPackage> Applications)
{
ArrayList<String> name = new ArrayList<String>();
for(ApplicationPackage app : Applications){
name.add(app.ApplicationName);
}
return name;
}
/**
* Return String ArrayList (Package name) from ApplicationPackage ArrayList
* @param Applications ApplicationPackage ArrayList
* @return ApplicationPackage ArrayList - Package name
*/
public static ArrayList<String>PackageName(ArrayList<ApplicationPackage> Applications)
{
ArrayList<String> name = new ArrayList<String>();
for(ApplicationPackage app : Applications){
name.add(app.PackageName);
}
return name;
}
@Override
public int compareTo(ApplicationPackage another) {
if(another.PackageName.equals(PackageName))
return 1;
else
return 0;
}
@Override
public boolean equals(Object object)
{
if(object.getClass() == ApplicationPackage.class) {
if (((ApplicationPackage) object).PackageName.equals(PackageName))
return true;
else
return false;
}else
return false;
}
}
| 1,994 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
SpecialVariables.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/SpecialVariables.java | package com.myspy.myspyandroid.variables;
import java.util.ArrayList;
import java.util.Calendar;
/**
* Created by Miroslav Murin on 20.01.2017.
*/
public class SpecialVariables {
public int SMSSentAvg = 0, SMSReceivedAvg = 0,CallTimeWeekIN = 0,CallTimeWeekOUT = 0;
private boolean Reset = false;
public String LastSentSMS = "";
public ArrayList<ApplicationPackage> Blockedapps= new ArrayList<ApplicationPackage>();
public void ResetAverage()
{
Calendar calendar = Calendar.getInstance();
if(calendar.get(Calendar.DAY_OF_WEEK)== Calendar.MONDAY && !Reset) {
SMSSentAvg = 0;
SMSReceivedAvg = 0;
CallTimeWeekIN = 0;
CallTimeWeekOUT = 0;
Reset = true;
}
if(calendar.get(Calendar.DAY_OF_WEEK)!= Calendar.MONDAY) {
Reset = false;
}
}
}
| 880 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ServiceVariables.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/ServiceVariables.java | package com.myspy.myspyandroid.variables;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by Miroslav Murin on 30.11.2016.
*/
public class ServiceVariables {
public Calendar calendar;
public List<SMSInfo> SMSList = new ArrayList<SMSInfo>();
public List<SMSInfo> SMSOutList = new ArrayList<SMSInfo>();
public List<CallInfo> CallList = new ArrayList<CallInfo>();
public List<LocationPoint> Path = new ArrayList<LocationPoint>();
public List<ApplicationInformation> Appinfo = new ArrayList<ApplicationInformation>();
public ServiceVariables()
{
calendar = GetCurrentTime();
}
private Calendar GetCurrentTime()
{
return Calendar.getInstance();
}
}
| 765 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
SMSInfoRead.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/SMSInfoRead.java | package com.myspy.myspyandroid.variables;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Created by Miroslav Murin on 21.12.2016.
*/
public class SMSInfoRead extends SMSInfo{
public int TimeVar = 0;
public boolean Sent = false;
public String TimeAction = "";
/**
*
* @param info SMSInfo. Your SMS you want to read
* @param sent Sent or received
*/
public SMSInfoRead(SMSInfo info,boolean sent) {
super(info.From,info.Body);
Sent = sent;
Time = info.Time;
Calendar time = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
try {
time.setTime(sdf.parse(info.Time));
} catch (Exception ex) {
Log.w("SMSinforead",""+ex);
}
TimeVar = (time.get(Calendar.HOUR_OF_DAY)*3600)+(time.get(Calendar.MINUTE)*60)+time.get(Calendar.SECOND);
TimeAction = String.format(Locale.getDefault(),"%02d", time.get(Calendar.HOUR_OF_DAY))+":"+String.format(Locale.getDefault(),"%02d", time.get(Calendar.MINUTE))+":"+String.format(Locale.getDefault(),"%02d", time.get(Calendar.SECOND));
}
}
| 1,260 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ServiceSettings.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/ServiceSettings.java | package com.myspy.myspyandroid.variables;
import com.myspy.myspyandroid.Weather.WeatherUnit;
/**
* Created by Miroslav Murin on 03.12.2016.
*/
public class ServiceSettings {
public String EncodedPassword = "";
public boolean MonitorSMS = true;
public boolean MonitorCalls = true;
public boolean MonitorApplications = true;
public boolean BlockSettings = false;
public boolean MonitorPosition = true;
public boolean ShowWeather = true;
public boolean WebData = false;
public String Alias = "";
public WeatherUnit weatherUnit = WeatherUnit.Celsius;
public int PositionTime = 50000;
public LocationPoint WeatherLocation;
public String WeatherLocationName = "";
public String ID = "";
}
| 745 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
CallInfo.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/CallInfo.java | package com.myspy.myspyandroid.variables;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Created by Miroslav Murin on 23.12.2016.
*/
public class CallInfo {
public String Number = "";
public String DateTime = "", DateTimeOnly = "";
public boolean OutGoingCall = false;
public int CallLength = 0;
public boolean Missed = false;
/**
* New CallInfo
* @param number Number of call
* @param outGoingCall Out going call?
* @param length Length of call in seconds
* @param time Time when call started
*/
public CallInfo(String number, boolean outGoingCall,int length, String time)
{
Number = number;
OutGoingCall = outGoingCall;
CallLength = length;
DateTime = time;
Missed = false;
DateTimeOnly = GetCurrentTimeOnly();
}
/**
* New CallInfo
* @param number Number of call
* @param outGoingCall Out going call?
* @param length Length of call in seconds
*/
public CallInfo(String number, boolean outGoingCall,int length)
{
Number = number;
OutGoingCall = outGoingCall;
CallLength = length;
Missed = false;
DateTimeOnly = GetCurrentTimeOnly();
}
/**
* New CallInfo
* @param number Number of Call
* @param time Time of Call
*/
public CallInfo(String number, String time)
{
Number = number;
OutGoingCall = false;
CallLength = 0;
DateTime = time;
Missed = true;
DateTimeOnly = GetCurrentTimeOnly();
}
/**
* Return current time in specific format : HH:mm:ss
* @return String
*/
public static String GetCurrentTimeOnly()
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
return format.format(Calendar.getInstance().getTime());
}
/**
* Return current time in specific format : EEE MMM dd HH:mm:ss z yyyy
* @return String
*/
public static String GetCurrentTime()
{
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
return format.format(Calendar.getInstance().getTime());
}
}
| 2,263 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
SMSInfo.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/variables/SMSInfo.java | package com.myspy.myspyandroid.variables;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Created by Miroslav Murin on 30.11.2016.
*/
public class SMSInfo {
public String Body = "";
public String From = "";
public String Time = "";
/**
*
* @param from Number from you received SMS
* @param body Body of SMS
* @param time Time of received SMS
*/
public SMSInfo(String from, String body, String time)
{
Body = body;
From = from;
Time = time;
}
/**
*
* @param from Number from you received SMS
* @param body Body of SMS
*/
public SMSInfo(String from, String body)
{
Body = body;
From = from;
}
/**
* Return current time in specific format : EEE MMM dd HH:mm:ss z yyyy
* @return String
*/
public static String GetCurrentTime()
{
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
return format.format(Calendar.getInstance().getTime());
}
}
| 1,113 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
Temperature.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/Temperature.java | package com.myspy.myspyandroid.Weather;
/**
* Created by Miroslav Murin on 11.01.2017.
*/
//Class for receive temperature in specific units... Celsius, Fahrenheit, Kelvin
public class Temperature {
private float temperature = 0;
/**
* Set temperature value
* @param Temperature Your temperature value (float)
* @param Unit Your Temperature Unit (WeatherUnit)
*/
public void SetTemperature(float Temperature, WeatherUnit Unit)
{
if(Unit == WeatherUnit.Kelvin)
temperature = Temperature;
else if(Unit == WeatherUnit.Fahrenheit)
temperature = ConvertFromFahrenheit(Temperature);
else
temperature = ConvertFromCelsius(Temperature);
}
/**
* Get temperature value
* This function will convert value to your unit.
* @param Unit Your Temperature Unit (WeatherUnit)
* @return value (Float)
*/
public float GetTemperature(WeatherUnit Unit)
{
if(Unit == WeatherUnit.Kelvin)
return temperature;
else if(Unit == WeatherUnit.Fahrenheit)
return ConvertToFahrenheit(temperature);
else
return ConvertToCelsius(temperature);
}
/**
* Get temperature value with symbol
* @param Unit Temperature Unit in you want to get your value(WeatherUnit)
* @return [Value] [Unit] - 280 K (String)
*/
public String GetTemperatureWithUnit(WeatherUnit Unit)
{
if(Unit == WeatherUnit.Kelvin)
return temperature + " "+ GetUnitSymbol(Unit);
else if(Unit == WeatherUnit.Fahrenheit)
return ConvertToFahrenheit(temperature) + " "+ GetUnitSymbol(Unit);
else
return ConvertToCelsius(temperature) + " "+ GetUnitSymbol(Unit);
}
private float ConvertFromFahrenheit(float far)
{
float kel = (5/9 * (far - 32) + 273.15f);
return kel;
}
private float ConvertFromCelsius(float cel)
{
return (cel+273.15f);
}
private float ConvertToFahrenheit(float kel)
{
return ((kel - 273.15f) * 9/5) + 32;
}
private float ConvertToCelsius(float kel)
{
return kel - 273.15f;
}
/**
* Get unit symbol
* @param UNIT Unit for your symbol
* @return symbol char (String)
*/
public String GetUnitSymbol(WeatherUnit UNIT)
{
if(UNIT == WeatherUnit.Celsius)
return "°C";
if(UNIT == WeatherUnit.Fahrenheit)
return "°F";
else
return "K";
}
}
| 2,571 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WeatherInfo.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/WeatherInfo.java | package com.myspy.myspyandroid.Weather;
/**
* Created by Miroslav Murin on 11.01.2017.
*/
public class WeatherInfo {
public Temperature temperature = new Temperature();
public String humidity = "";
public String pressure = "";
public String cloudiness = "";
public String windSpeed = "";
public String windDirectionDeg = "";
public String windDirectionName = "";
public String precipitation = "";
public String precipitationunit = "";
public String symbolID = "";
public String symbolNumber = "";
public int day = 0, hour = 0;
public String Date = "";
}
| 612 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
PlaceInfo.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/PlaceInfo.java | package com.myspy.myspyandroid.Weather;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by Miroslav Murin on 05.01.2017.
*/
public class PlaceInfo {
@SerializedName("place_id")
@Expose
public String placeId;
@SerializedName("licence")
@Expose
public String licence;
@SerializedName("osm_type")
@Expose
public String osmType;
@SerializedName("osm_id")
@Expose
public String osmId;
@SerializedName("boundingbox")
@Expose
public List<String> boundingbox = null;
@SerializedName("lat")
@Expose
public String lat;
@SerializedName("lon")
@Expose
public String lon;
@SerializedName("display_name")
@Expose
public String displayName;
@SerializedName("class")
@Expose
public String _class;
@SerializedName("type")
@Expose
public String type;
@SerializedName("importance")
@Expose
public Float importance;
@SerializedName("icon")
@Expose
public String icon;
}
| 1,084 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WeatherLocationByName.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/WeatherLocationByName.java | package com.myspy.myspyandroid.Weather;
import android.util.Log;
import com.google.gson.Gson;
import com.myspy.myspyandroid.functions.HTTPWork;
import com.myspy.myspyandroid.variables.LocationPoint;
/**
* Created by Miroslav Murin on 05.01.2017.
*/
public class WeatherLocationByName implements WeatherLocation{
private final String UrlGet = "http://nominatim.openstreetmap.org/search?city=";
public PlaceInfo placeinfo;
private LocationPoint locationPoint = new LocationPoint(0,0);
private String locationname;
private boolean Dataavaible = false;
/**
* Get location. Add this function to another thread than main thread
* @param Cityname Location name
* @param Email Your email for security reason ( Nominatim )
*/
public void GetLocation(final String Cityname, final String Email) {
try {
WorkWithData(HTTPWork.GET(UrlGet+Cityname+"&addressdetails=0&format=json&email=" + Email));
}catch (Exception ex){
Log.w("Error","GetLocationByName: "+ex);
}
}
/**
* Is prepared? Return true if contains values
* @return Boolean
*/
@Override
public boolean IsPrepared() {
return Dataavaible;
}
/**
* Get location point
* @return LocationPoint
*/
@Override
public LocationPoint GetLocationPoint() {
return locationPoint;
}
/**
* Return location name
* @return String
*/
@Override
public String GetLocationName() {
return locationname;
}
private void WorkWithData(String data)
{
Gson gson = new Gson();
PlaceInfo[] placeInfos = gson.fromJson(data,PlaceInfo[].class);
placeinfo = placeInfos[0];
locationPoint.Longitude = Float.parseFloat( placeinfo.lon);
locationPoint.Latitude = Float.parseFloat(placeinfo.lat);
locationname = placeinfo.displayName;
Dataavaible = true;
Log.d("WeatherLocationByName","Successful acquired data");
}
}
| 2,034 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WeatherUnit.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/WeatherUnit.java | package com.myspy.myspyandroid.Weather;
/**
* Created by Miroslav Murin on 11.01.2017.
*/
public enum WeatherUnit {
Kelvin,Celsius,Fahrenheit
}
| 152 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
Weather.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/Weather.java | package com.myspy.myspyandroid.Weather;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.myspy.myspyandroid.functions.HTTPWork;
import com.myspy.myspyandroid.variables.LocationPoint;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Created by Miroslav Murin on 11.01.2017.
*/
public class Weather {
public WeatherInfo weatherInfo = new WeatherInfo();
/**
* Receive weather info
* @param Latitude Latitude for weather info
* @param Longitude Longitude for weather info
* @return Boolean - true if successful
*/
public boolean GetWeather(float Latitude, float Longitude)
{
try {
GetData(Latitude, Longitude);
return true;
}catch (Exception ex){
Log.w("Error","GetLocationByName: "+ex);
return false;
}
}
/**
* Receive weather info
* @param locationPoint Location for weather info
* @return Boolean - true if successful
*/
public boolean GetWeather(LocationPoint locationPoint)
{
try {
GetData(locationPoint.Latitude, locationPoint.Longitude);
return true;
}catch (Exception ex){
Log.w("Error","GetLocationByName: "+ex);
return false;
}
}
private void GetData(float lat, float lon)
{
Log.d("SendData","https://api.met.no/weatherapi/locationforecastlts/1.3/?lat="+lat+";lon="+lon);
WorkWithData(HTTPWork.GET("https://api.met.no/weatherapi/locationforecastlts/1.3/?lat="+lat+";lon="+lon,"</time>",2));
}
private void WorkWithData(String data)
{
Log.d("Data","Size: "+data.length());
data+="</product></weatherdata>";
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(data));
Document doc = dBuilder.parse(is);
weatherInfo.temperature.SetTemperature( Float.parseFloat( ((Element)doc.getElementsByTagName("temperature").item(0)).getAttribute("value")),WeatherUnit.Celsius);
weatherInfo.humidity = ((Element)doc.getElementsByTagName("humidity").item(0)).getAttribute("value");
weatherInfo.pressure = ((Element)doc.getElementsByTagName("pressure").item(0)).getAttribute("value");
weatherInfo.cloudiness = ((Element)doc.getElementsByTagName("cloudiness").item(0)).getAttribute("percent");
weatherInfo.windSpeed = ((Element)doc.getElementsByTagName("windSpeed").item(0)).getAttribute("mps");
weatherInfo.windDirectionDeg = ((Element)doc.getElementsByTagName("windDirection").item(0)).getAttribute("deg");
weatherInfo.windDirectionName =((Element)doc.getElementsByTagName("windDirection").item(0)).getAttribute("name");
weatherInfo.precipitation = ((Element)doc.getElementsByTagName("precipitation").item(0)).getAttribute("value");
weatherInfo.precipitationunit = ((Element)doc.getElementsByTagName("precipitation").item(0)).getAttribute("unit");
weatherInfo.symbolID = ((Element)doc.getElementsByTagName("symbol").item(0)).getAttribute("id");
weatherInfo.symbolNumber = ((Element)doc.getElementsByTagName("symbol").item(0)).getAttribute("number");
weatherInfo.day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
weatherInfo.hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}catch (Exception ex)
{
Log.w("WeatherError","1-Weather: "+ex);
}
}
/**
* Returns weather icon
* @param symbol Symbol code ( SymbolNumber in WeatherInfo )
* @param night 1 - night | 0 - Day
* @return Bitmap
*/
public Bitmap GetWeatherIcon(String symbol, int night)
{
try {
URL url = new URL("https://api.met.no/weatherapi/weathericon/1.1/?symbol="+symbol+";is_night="+night+";content_type=image/png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception ex) {
Log.w("WeatherError","2-WERR: "+ex);
return null;
}
}
}
| 4,796 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WeatherLocationByLocation.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/WeatherLocationByLocation.java | package com.myspy.myspyandroid.Weather;
import android.util.Log;
import com.google.gson.Gson;
import com.myspy.myspyandroid.functions.HTTPWork;
import com.myspy.myspyandroid.variables.LocationPoint;
/**
* Created by Miroslav Murin on 06.01.2017.
*/
public class WeatherLocationByLocation implements WeatherLocation {
private final String UrlGet = "http://nominatim.openstreetmap.org/reverse?format=json&zoom=10&addressdetails=0&lat=";
public PlaceInfo placeinfo;
private LocationPoint locationPoint = new LocationPoint(0,0);
private String locationname;
private boolean Dataavaible = false;
/**
* Get location. Add this function to another thread than main thread
* @param Latitude Your Latitude
* @param Longitude Your Longitude
* @param Email Your email for security reason ( Nominatim )
*/
public void GetLocation(float Latitude, float Longitude, String Email)
{
try {
WorkWithData(HTTPWork.GET(UrlGet+Latitude+"&lon="+Longitude+"&email=" + Email));
}catch (Exception ex){
Log.w("Error","GetLocationByName: "+ex);
}
}
/**
* Is prepared? Return true if contains values
* @return Boolean
*/
@Override
public boolean IsPrepared() {
return Dataavaible;
}
/**
* Get location point
* @return LocationPoint
*/
@Override
public LocationPoint GetLocationPoint() {
return locationPoint;
}
/**
* Return location name
* @return String
*/
@Override
public String GetLocationName() {
return locationname;
}
private void WorkWithData(String data)
{
Gson gson = new Gson();
placeinfo = gson.fromJson(data,PlaceInfo.class);
locationPoint.Longitude = Float.parseFloat( placeinfo.lon);
locationPoint.Latitude = Float.parseFloat(placeinfo.lat);
locationname = placeinfo.displayName;
Dataavaible = true;
Log.d("WeatherLocationByLocat","Successful acquired data");
}
}
| 2,064 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
WeatherLocation.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/main/java/com/myspy/myspyandroid/Weather/WeatherLocation.java | package com.myspy.myspyandroid.Weather;
import com.myspy.myspyandroid.variables.LocationPoint;
/**
* Created by Miroslav Murin on 05.01.2017.
*/
public interface WeatherLocation {
boolean IsPrepared();
LocationPoint GetLocationPoint();
String GetLocationName();
}
| 282 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/Miro382_My-Spy-Android/MySpyAndroid/app/src/androidTest/java/com/myspy/myspyandroid/ExampleInstrumentedTest.java | package com.myspy.myspyandroid;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.myspy.myspyandroid", appContext.getPackageName());
}
}
| 748 | Java | .java | Miro382/My-Spy-Android | 20 | 12 | 1 | 2019-09-01T10:30:08Z | 2019-09-01T10:41:30Z |
RandomTest.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/test/java/com/afkanerd/deku/RandomTest.java | package com.afkanerd.deku;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import android.util.Log;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class RandomTest {
class RandomClass {
public int value;
}
public void randomClassUpdate(RandomClass randomClass) {
randomClass.value = 1;
}
@Test
public void ObjectBehaviourTest() {
RandomClass randomClass = new RandomClass();
randomClass.value = 0;
randomClassUpdate(randomClass);
assertEquals(1, randomClass.value);
}
List<Integer> output =new ArrayList<>();
public void sum(int i) {
output.add(i);
}
public void runSum(int i) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
sum(i);
try {
Thread.sleep(1000L - (i*100L));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
@Test
public void SyncingThreadsTest() {
for(int i=0;i<5;++i)
runSum(i);
List<Integer> expected = new ArrayList<>();
expected.add(0);
expected.add(1);
expected.add(2);
expected.add(3);
expected.add(4);
assertEquals(expected, output);
}
}
| 1,512 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
JavaMethodsTest.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/test/java/com/afkanerd/deku/DefaultSMS/Commons/JavaMethodsTest.java | package com.afkanerd.deku.DefaultSMS.Commons;
import static org.junit.Assert.assertArrayEquals;
import android.database.Cursor;
import com.google.common.primitives.Bytes;
import org.junit.Test;
public class JavaMethodsTest {
@Test
public void byteConcatTest(){
byte[] byte1 = new byte[]{0x01};
byte[] byte2 = new byte[]{0x02};
byte[] expected = new byte[]{byte1[0], byte2[0]};
byte[] output = Bytes.concat(byte1, byte2);
assertArrayEquals(expected, output);
}
}
| 524 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
PhonenumberParsingTest.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/test/java/com/afkanerd/deku/DefaultSMS/Commons/PhonenumberParsingTest.java | package com.afkanerd.deku.DefaultSMS.Commons;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.google.i18n.phonenumbers.NumberParseException;
import org.junit.Test;
public class PhonenumberParsingTest {
@Test
public void checkForValidPhonenumber(){
String wrongNumber = "https://example.com/02fkmb";
}
@Test
public void formatPhoneNumbersNoPlus(){
String nationalNumber = "612345678";
String defaultRegion = "237";
String phoneNumber = defaultRegion + nationalNumber;
String formattedOutput = Helpers.getFormatNationalNumber(phoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersNoCountryCode(){
String nationalNumber = "612345678";
String defaultRegion = "237";
String formattedOutput = Helpers.getFormatNationalNumber(nationalNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersWithCountryCode(){
String fullPhoneNumber = "+237612345678";
String defaultRegion = "237";
String nationalNumber = "612345678";
String formattedOutput = Helpers.getFormatNationalNumber(fullPhoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersWithShared_sms(){
String fullPhoneNumber = "sms:+237612345678";
String defaultRegion = "237";
String nationalNumber = "612345678";
String formattedOutput = Helpers.getFormatNationalNumber(fullPhoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersWithShared_smsto(){
String fullPhoneNumber = "smsto:612345678";
String defaultRegion = "237";
String nationalNumber = "612345678";
String formattedOutput = Helpers.getFormatNationalNumber(fullPhoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersWithShared_smsto_wrongCountryCode(){
String fullPhoneNumber = "smsto:612345678";
String defaultRegion = "1";
String nationalNumber = "612345678";
String formattedOutput = Helpers.getFormatNationalNumber(fullPhoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersWithShared_smsto_wrongCountryCode1(){
String fullPhoneNumber = "6505551212";
String defaultRegion = "1";
String nationalNumber = "6505551212";
String formattedOutput = Helpers.getFormatNationalNumber(fullPhoneNumber, defaultRegion);
assertEquals(nationalNumber, formattedOutput);
}
@Test
public void formatPhoneNumbersComplete(){
String fullPhoneNumber = "smsto:+237612345678";
String defaultRegion = "1";
String nationalNumber = "612345678";
String formattedOutput = Helpers.getFormatCompleteNumber(fullPhoneNumber, defaultRegion);
assertEquals(("+" + "237" + nationalNumber), formattedOutput);
}
@Test
public void formatPhoneNumbersComplete1(){
String fullPhoneNumber = "smsto:6505551212";
String defaultRegion = "0";
String nationalNumber = "6505551212";
String formattedOutput = Helpers.getFormatCompleteNumber(fullPhoneNumber, defaultRegion);
assertEquals(("+" + defaultRegion + nationalNumber), formattedOutput);
}
@Test
public void formatPhoneNumbersCompleteSharedContacts(){
String fullPhoneNumber = "smsto:1%20(234)%20567-04";
String defaultRegion = "1";
String nationalNumber = "(234)567-04";
String formattedOutput = Helpers.getFormatCompleteNumber(fullPhoneNumber, defaultRegion);
assertEquals(("+" + defaultRegion + nationalNumber), formattedOutput);
}
@Test
public void formatPhoneNumbersCompleteToStandards(){
String fullPhoneNumber = "smsto:1%20(234)%20567-04";
String defaultRegion = "1";
String nationalNumber = "123456704";
String formattedOutput = Helpers.getFormatForTransmission(fullPhoneNumber, defaultRegion);
assertEquals(("+" + defaultRegion + nationalNumber), formattedOutput);
}
@Test
public void formatPhoneNumbersAndCountryCodeTest() throws NumberParseException {
String fullPhoneNumber = "+237612345678";
String defaultRegion = "237";
String nationalNumber = "612345678";
String[] formattedOutput = Helpers.getCountryNationalAndCountryCode(fullPhoneNumber);
assertArrayEquals(new String[]{defaultRegion, nationalNumber}, formattedOutput);
}
@Test
public void formatPhoneNumbersAndCountryCodeSpecialCharacterTest() throws NumberParseException {
String fullPhoneNumber = "123-456-789";
String defaultRegion = "237";
String nationalNumber = "123456789";
String formattedOutput = Helpers.getFormatCompleteNumber(fullPhoneNumber, defaultRegion);
assertEquals(("+" + defaultRegion + nationalNumber), formattedOutput);
}
}
| 5,286 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjectListingActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjectListingActivity.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_ID;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.R;
import java.util.List;
public class GatewayClientProjectListingActivity extends AppCompatActivity {
long id;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gateway_client_project_listing);
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
Toolbar toolbar = findViewById(R.id.gateway_client_project_listing_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String username = getIntent().getStringExtra(GatewayClientListingActivity.GATEWAY_CLIENT_USERNAME);
String host = getIntent().getStringExtra(GatewayClientListingActivity.GATEWAY_CLIENT_HOST);
id = getIntent().getLongExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, -1);
sharedPreferences = getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
getSupportActionBar().setTitle(username);
getSupportActionBar().setSubtitle(host);
GatewayClientProjectListingRecyclerAdapter gatewayClientProjectListingRecyclerAdapter =
new GatewayClientProjectListingRecyclerAdapter();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
RecyclerView recyclerView = findViewById(R.id.gateway_client_project_listing_recycler_view);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(gatewayClientProjectListingRecyclerAdapter);
GatewayClientProjectListingViewModel gatewayClientProjectListingViewModel =
new ViewModelProvider(this).get(GatewayClientProjectListingViewModel.class);
gatewayClientProjectListingViewModel.get(Datastore.datastore, id).observe(this,
new Observer<List<GatewayClientProjects>>() {
@Override
public void onChanged(List<GatewayClientProjects> gatewayClients) {
gatewayClientProjectListingRecyclerAdapter.mDiffer.submitList(gatewayClients);
if(gatewayClients == null || gatewayClients.isEmpty())
findViewById(R.id.gateway_client_project_listing_no_projects).setVisibility(View.VISIBLE);
else
findViewById(R.id.gateway_client_project_listing_no_projects).setVisibility(View.GONE);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gateway_client_project_listing_menu, menu);
boolean connected = sharedPreferences.contains(String.valueOf(id));
menu.findItem(R.id.gateway_client_project_connect).setVisible(!connected);
menu.findItem(R.id.gateway_client_project_disconnect).setVisible(connected);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.gateway_client_project_add) {
Intent intent = new Intent(getApplicationContext(), GatewayClientProjectAddActivity.class);
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, id);
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID_NEW, true);
startActivity(intent);
return true;
}
if(item.getItemId() == R.id.gateway_client_edit ) {
Intent intent = new Intent(this, GatewayClientAddActivity.class);
intent.putExtra(GATEWAY_CLIENT_ID, id);
startActivity(intent);
return true;
}
if(item.getItemId() == R.id.gateway_client_project_connect) {
GatewayClientHandler gatewayClientHandler =
new GatewayClientHandler(getApplicationContext());
new Thread(new Runnable() {
@Override
public void run() {
GatewayClient gatewayClient =
gatewayClientHandler.databaseConnector.gatewayClientDAO().fetch(id);
try {
GatewayClientHandler.startListening(getApplicationContext(), gatewayClient);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return true;
}
if(item.getItemId() == R.id.gateway_client_project_disconnect) {
sharedPreferences.edit().remove(String.valueOf(id))
.apply();
finish();
return true;
}
return false;
}
} | 5,855 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientHandler.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientHandler.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.SubscriptionInfo;
import androidx.room.Room;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.ExistingWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.Models.Database.SemaphoreManager;
import com.afkanerd.deku.DefaultSMS.ThreadedConversationsActivity;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations;
import com.afkanerd.deku.QueueListener.RMQ.RMQConnectionService;
import com.afkanerd.deku.QueueListener.RMQ.RMQWorkManager;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class GatewayClientHandler {
public Datastore databaseConnector;
public GatewayClientHandler(Context context) {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context, Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
databaseConnector = Datastore.datastore;
}
public long add(GatewayClient gatewayClient) throws InterruptedException {
gatewayClient.setDate(System.currentTimeMillis());
final long[] id = {-1};
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
id[0] = gatewayClientDAO.insert(gatewayClient);
}
});
thread.start();
thread.join();
return id[0];
}
public void delete(GatewayClient gatewayClient) throws InterruptedException {
gatewayClient.setDate(System.currentTimeMillis());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
gatewayClientDAO.delete(gatewayClient);
}
});
thread.start();
thread.join();
}
public void update(GatewayClient gatewayClient) throws InterruptedException {
gatewayClient.setDate(System.currentTimeMillis());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
gatewayClientDAO.update(gatewayClient);
}
});
thread.start();
thread.join();
}
public GatewayClient fetch(long id) throws InterruptedException {
final GatewayClient[] gatewayClient = {new GatewayClient()};
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
gatewayClient[0] = gatewayClientDAO.fetch(id);
}
});
thread.start();
thread.join();
return gatewayClient[0];
}
public List<GatewayClient> fetchAll() throws InterruptedException {
final List<GatewayClient>[] gatewayClientList = new List[]{new ArrayList<>()};
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
gatewayClientList[0] = gatewayClientDAO.getAll();
}
});
thread.start();
thread.join();
return gatewayClientList[0];
}
private void setMigrationsTo11() {
try {
SemaphoreManager.acquireSemaphore();
GatewayClientDAO gatewayClientDAO = databaseConnector.gatewayClientDAO();
Map<Long, Set<GatewayClientProjects>> gatewayClientMaps = new HashMap<>();
List<GatewayClient> gatewayClientList = new ArrayList<>();
for(GatewayClient gatewayClient : gatewayClientDAO.getAll()) {
GatewayClientProjects gatewayClientProjects1 = new GatewayClientProjects();
gatewayClientProjects1.name = gatewayClient.getProjectName();
gatewayClientProjects1.binding1Name = gatewayClient.getProjectBinding();
gatewayClientProjects1.binding2Name = gatewayClient.getProjectBinding2();
gatewayClientProjects1.gatewayClientId = gatewayClient.getHashcode()[0];
if(!gatewayClientMaps.containsKey(gatewayClient.getHashcode()[0]) ||
gatewayClientMaps.get(gatewayClient.getHashcode()[0]) == null) {
gatewayClientMaps.put(gatewayClient.getHashcode()[0], new HashSet<>());
gatewayClient.setId(gatewayClient.getHashcode()[0]);
gatewayClientList.add(gatewayClient);
}
gatewayClientMaps.get(gatewayClient.getHashcode()[0]).add(gatewayClientProjects1);
}
gatewayClientDAO.deleteAll();
gatewayClientDAO.insert(gatewayClientList);
List<GatewayClientProjects> projectsList = new ArrayList<>();
for(Set<GatewayClientProjects> gatewayClientProjects : gatewayClientMaps.values())
projectsList.addAll(gatewayClientProjects);
databaseConnector.gatewayClientProjectDao().insert(projectsList);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
SemaphoreManager.releaseSemaphore();
} catch (InterruptedException e ) {
e.printStackTrace();
}
}
}
public final static String MIGRATIONS = "MIGRATIONS";
public final static String MIGRATIONS_TO_11 = "MIGRATIONS_TO_11";
public void startServices(Context context) throws InterruptedException {
SharedPreferences sharedPreferences = context.getSharedPreferences(MIGRATIONS, Context.MODE_PRIVATE);
if(sharedPreferences.getBoolean(MIGRATIONS_TO_11, false)) {
setMigrationsTo11();
sharedPreferences.edit().putBoolean(MIGRATIONS_TO_11, false).apply();
}
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build();
try {
OneTimeWorkRequest gatewayClientListenerWorker = new OneTimeWorkRequest.Builder(RMQWorkManager.class)
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS
)
.addTag(GatewayClient.class.getName())
.build();
WorkManager workManager = WorkManager.getInstance(context);
workManager.enqueueUniqueWork(ThreadedConversationsActivity.UNIQUE_WORK_MANAGER_NAME,
ExistingWorkPolicy.KEEP,
gatewayClientListenerWorker);
} catch(Exception e) {
e.printStackTrace();
}
}
public static String getConnectionStatus(Context context, String gatewayClientId) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
if(sharedPreferences.contains(gatewayClientId)) {
if(sharedPreferences.getBoolean(gatewayClientId, false)) {
return context.getString(R.string.gateway_client_customization_connected);
} else {
return context.getString(R.string.gateway_client_customization_reconnecting);
}
}
return context.getString(R.string.gateway_client_customization_deactivated);
}
public static List<String> getPublisherDetails(Context context, String projectName) {
List<SubscriptionInfo> simcards = SIMHandler.getSimCardInformation(context);
final String operatorCountry = Helpers.getUserCountry(context);
List<String> operatorDetails = new ArrayList<>();
for(int i=0;i<simcards.size(); ++i) {
String mcc = String.valueOf(simcards.get(i).getMcc());
int _mnc = simcards.get(i).getMnc();
String mnc = _mnc < 10 ? "0" + _mnc : String.valueOf(_mnc);
String carrierId = mcc + mnc;
String publisherName = projectName + "." + operatorCountry + "." + carrierId;
operatorDetails.add(publisherName);
}
return operatorDetails;
}
public static void setListening(Context context, GatewayClient gatewayClient) throws InterruptedException {
SharedPreferences sharedPreferences = context.getSharedPreferences(GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS,
Context.MODE_PRIVATE);
sharedPreferences.edit()
.putBoolean(String.valueOf(gatewayClient.getId()), false)
.apply();
}
public static void startListening(Context context, GatewayClient gatewayClient) throws InterruptedException {
GatewayClientHandler.setListening(context, gatewayClient);
new GatewayClientHandler(context).startServices(context);
}
}
| 9,972 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClient.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClient.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import com.afkanerd.deku.DefaultSMS.R;
import org.apache.commons.codec.digest.MurmurHash3;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
@Entity
public class GatewayClient {
public GatewayClient() {}
@Ignore
private String connectionStatus;
public String getConnectionStatus() {
return connectionStatus;
}
public void setConnectionStatus(String connectionStatus) {
this.connectionStatus = connectionStatus;
}
@PrimaryKey(autoGenerate = true)
private long id;
private long date;
private String hostUrl;
private String username;
private String password;
private int port;
private String friendlyConnectionName;
private String virtualHost;
private int connectionTimeout = 10000;
private int prefetch_count = 1;
private int heartbeat = 30;
private String protocol = "amqp";
private String projectName;
private String projectBinding;
public String getProjectBinding2() {
return projectBinding2;
}
public void setProjectBinding2(String projectBinding2) {
this.projectBinding2 = projectBinding2;
}
private String projectBinding2;
public String getProjectName() {
return projectName;
}
public String getProjectBinding() {
return projectBinding;
}
public void setProjectBinding(String projectBinding) {
this.projectBinding = projectBinding;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVirtualHost() {
return virtualHost;
}
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getHostUrl() {
return hostUrl;
}
public void setHostUrl(String hostUrl) {
this.hostUrl = hostUrl;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFriendlyConnectionName() {
return friendlyConnectionName;
}
public void setFriendlyConnectionName(String friendlyConnectionName) {
this.friendlyConnectionName = friendlyConnectionName;
}
public int getPrefetch_count() {
return prefetch_count;
}
public void setPrefetch_count(int prefetch_count) {
this.prefetch_count = prefetch_count;
}
public int getHeartbeat() {
return heartbeat;
}
public void setHeartbeat(int heartbeat) {
this.heartbeat = heartbeat;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public long[] getHashcode() {
String hashValues = protocol + hostUrl + port + virtualHost + username + password;
return MurmurHash3.hash128(hashValues.getBytes(StandardCharsets.UTF_8));
}
public boolean same(@Nullable Object obj) {
if(obj instanceof GatewayClient) {
GatewayClient gatewayClient = (GatewayClient) obj;
return Objects.equals(gatewayClient.hostUrl, this.hostUrl) &&
Objects.equals(gatewayClient.protocol, this.protocol) &&
Objects.equals(gatewayClient.virtualHost, this.virtualHost) &&
gatewayClient.port == this.port;
}
return false;
}
public boolean equals(@Nullable Object obj) {
// return super.equals(obj);
if(obj instanceof GatewayClient) {
GatewayClient gatewayClient = (GatewayClient) obj;
// return gatewayClient.id == this.id &&
// Objects.equals(gatewayClient.hostUrl, this.hostUrl) &&
// Objects.equals(gatewayClient.protocol, this.protocol) &&
// gatewayClient.port == this.port &&
// Objects.equals(gatewayClient.projectBinding, this.projectBinding) &&
// Objects.equals(gatewayClient.projectName, this.projectName) &&
// Objects.equals(gatewayClient.connectionStatus, this.connectionStatus) &&
// gatewayClient.date == this.date;
return Objects.equals(gatewayClient.hostUrl, this.hostUrl) &&
Objects.equals(gatewayClient.protocol, this.protocol) &&
Objects.equals(gatewayClient.virtualHost, this.virtualHost) &&
gatewayClient.port == this.port;
}
return false;
}
public static final DiffUtil.ItemCallback<GatewayClient> DIFF_CALLBACK =
new DiffUtil.ItemCallback<GatewayClient>() {
@Override
public boolean areItemsTheSame(@NonNull GatewayClient oldItem, @NonNull GatewayClient newItem) {
return oldItem.id == newItem.id;
}
@Override
public boolean areContentsTheSame(@NonNull GatewayClient oldItem, @NonNull GatewayClient newItem) {
return oldItem.equals(newItem);
}
};
}
| 6,140 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientAddActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientAddActivity.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioGroup;
import com.afkanerd.deku.DefaultSMS.R;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
public class GatewayClientAddActivity extends AppCompatActivity {
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gateway_client_add);
toolbar = findViewById(R.id.gateway_client_add_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.add_new_gateway_server_toolbar_title));
if(getIntent().hasExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID)) {
try {
editGatewayClient();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
MaterialButton materialButton = findViewById(R.id.gateway_client_customization_save_btn);
materialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
onSaveGatewayClient(v);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
long id = -1;
public void editGatewayClient() throws InterruptedException {
id = getIntent().getLongExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, -1);
if(id != -1 ) {
TextInputEditText url = findViewById(R.id.new_gateway_client_url_input);
TextInputEditText username = findViewById(R.id.new_gateway_client_username);
TextInputEditText password = findViewById(R.id.new_gateway_password);
TextInputEditText friendlyName = findViewById(R.id.new_gateway_client_friendly_name);
TextInputEditText virtualHost = findViewById(R.id.new_gateway_client_virtualhost);
TextInputEditText port = findViewById(R.id.new_gateway_client_port);
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
GatewayClient gatewayClient = gatewayClientHandler.fetch(id);
url.setText(gatewayClient.getHostUrl());
username.setText(gatewayClient.getUsername());
password.setText(gatewayClient.getPassword());
friendlyName.setText(gatewayClient.getFriendlyConnectionName());
virtualHost.setText(gatewayClient.getVirtualHost());
port.setText(String.valueOf(gatewayClient.getPort()));
}
}
public void onSaveGatewayClient(View view) throws InterruptedException {
TextInputEditText url = findViewById(R.id.new_gateway_client_url_input);
TextInputEditText username = findViewById(R.id.new_gateway_client_username);
TextInputEditText password = findViewById(R.id.new_gateway_password);
TextInputEditText friendlyName = findViewById(R.id.new_gateway_client_friendly_name);
TextInputEditText virtualHost = findViewById(R.id.new_gateway_client_virtualhost);
TextInputEditText port = findViewById(R.id.new_gateway_client_port);
if(url.getText().toString().isEmpty()) {
url.setError(getResources().getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(username.getText().toString().isEmpty()) {
username.setError(getResources().getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(password.getText().toString().isEmpty()) {
password.setError(getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(virtualHost.getText().toString().isEmpty()) {
virtualHost.setText(getResources().getString(R.string.settings_gateway_client_default_virtualhost));
}
if(port.getText().toString().isEmpty()) {
port.setText(getResources().getString(R.string.settings_gateway_client_default_port));
}
GatewayClient gatewayClient = new GatewayClient();
gatewayClient.setHostUrl(url.getText().toString());
gatewayClient.setUsername(username.getText().toString());
gatewayClient.setPassword(password.getText().toString());
gatewayClient.setVirtualHost(virtualHost.getText().toString());
gatewayClient.setPort(Integer.parseInt(port.getText().toString()));
gatewayClient.setDate(System.currentTimeMillis());
if(!friendlyName.getText().toString().isEmpty()) {
gatewayClient.setFriendlyConnectionName(friendlyName.getText().toString());
}
RadioGroup radioGroup = findViewById(R.id.add_gateway_client_protocol_group);
int checkedRadioId = radioGroup.getCheckedRadioButtonId();
if(checkedRadioId == R.id.add_gateway_client_protocol_amqp)
gatewayClient.setProtocol(getString(R.string.settings_gateway_client_amqp_protocol).toLowerCase());
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
if(getIntent().hasExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID)) {
long gatewayClientId = getIntent().getLongExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, -1);
GatewayClient gatewayClient1 = gatewayClientHandler.fetch(gatewayClientId);
gatewayClient.setId(gatewayClient1.getId());
gatewayClient.setProjectName(gatewayClient1.getProjectName());
gatewayClient.setProjectBinding(gatewayClient1.getProjectBinding());
gatewayClientHandler.update(gatewayClient);
}
else {
gatewayClientHandler.add(gatewayClient);
}
Intent intent = new Intent(this, GatewayClientListingActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(id != -1)
getMenuInflater().inflate(R.menu.gateway_server_add_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.gateway_client_delete) {
SharedPreferences sharedPreferences = getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
sharedPreferences.edit().remove(String.valueOf(id))
.apply();
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
// GatewayClient gatewayClient = gatewayClientHandler.fetch(id);
// gatewayClientHandler.delete(gatewayClient);
new Thread(new Runnable() {
@Override
public void run() {
GatewayClient gatewayClient = gatewayClientHandler.databaseConnector
.gatewayClientDAO().fetch(id);
gatewayClientHandler.databaseConnector.gatewayClientDAO()
.delete(gatewayClient);
gatewayClientHandler.databaseConnector.gatewayClientProjectDao()
.deleteGatewayClientId(id);
}
}).start();
startActivity(new Intent(this, GatewayClientListingActivity.class));
finish();
return true;
}
return false;
}
} | 8,140 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjectListingViewModel.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjectListingViewModel.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import android.content.Context;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class GatewayClientProjectListingViewModel extends ViewModel {
long id;
public LiveData<List<GatewayClientProjects>> get(Datastore databaseConnector, long id) {
this.id = id;
GatewayClientProjectDao gatewayClientProjectDao = databaseConnector.gatewayClientProjectDao();
return gatewayClientProjectDao.fetchGatewayClientId(id);
}
}
| 799 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjects.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjects.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.Objects;
@Entity
public class GatewayClientProjects {
@PrimaryKey(autoGenerate = true)
public long id;
public long gatewayClientId;
public String name;
public String binding1Name;
public String binding2Name;
@Override
public boolean equals(@Nullable Object obj) {
if(obj instanceof GatewayClientProjects) {
GatewayClientProjects gatewayClientProjects = (GatewayClientProjects) obj;
return gatewayClientProjects.id == this.id &&
Objects.equals(gatewayClientProjects.name, this.name) &&
Objects.equals(gatewayClientProjects.binding1Name, this.binding1Name) &&
Objects.equals(gatewayClientProjects.binding2Name, this.binding2Name) &&
gatewayClientProjects.gatewayClientId == this.gatewayClientId;
}
return false;
}
public static final DiffUtil.ItemCallback<GatewayClientProjects> DIFF_CALLBACK =
new DiffUtil.ItemCallback<GatewayClientProjects>() {
@Override
public boolean areItemsTheSame(@NonNull GatewayClientProjects oldItem,
@NonNull GatewayClientProjects newItem) {
return oldItem.id == newItem.id;
}
@Override
public boolean areContentsTheSame(@NonNull GatewayClientProjects oldItem,
@NonNull GatewayClientProjects newItem) {
return oldItem.equals(newItem);
}
};
}
| 1,858 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjectListingRecyclerAdapter.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjectListingRecyclerAdapter.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.RecyclerView;
import com.afkanerd.deku.DefaultSMS.R;
import org.jetbrains.annotations.NotNull;
public class GatewayClientProjectListingRecyclerAdapter extends RecyclerView.Adapter<GatewayClientProjectListingRecyclerAdapter.ViewHolder>{
public final AsyncListDiffer<GatewayClientProjects> mDiffer =
new AsyncListDiffer<>(this, GatewayClientProjects.DIFF_CALLBACK);
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.gateway_client_project_listing_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
GatewayClientProjects gatewayClientProjects = mDiffer.getCurrentList().get(position);
Log.d(getClass().getName(), "Binding object: " + gatewayClientProjects.name);
holder.projectNameTextView.setText(gatewayClientProjects.name);
holder.projectBinding1TextView.setText(gatewayClientProjects.binding1Name);
holder.projectBinding2TextView.setText(gatewayClientProjects.binding2Name);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(holder.itemView.getContext(), GatewayClientProjectAddActivity.class);
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID,
gatewayClientProjects.gatewayClientId);
intent.putExtra(GatewayClientProjectAddActivity.GATEWAY_CLIENT_PROJECT_ID,
gatewayClientProjects.id);
holder.itemView.getContext().startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mDiffer.getCurrentList().size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView projectNameTextView;
TextView projectBinding1TextView, projectBinding2TextView;
public ViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.gateway_client_project_listing_card );
projectNameTextView =
itemView.findViewById(R.id.gateway_client_project_listing_project_name);
projectBinding1TextView =
itemView.findViewById(R.id.gateway_client_project_listing_project_binding1);
projectBinding2TextView =
itemView.findViewById(R.id.gateway_client_project_listing_project_binding2);
}
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
}
| 3,284 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientDAO.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientDAO.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
@Dao
public interface GatewayClientDAO {
@Query("SELECT * FROM GatewayClient")
List<GatewayClient> getAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(GatewayClient gatewayClient);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<GatewayClient> gatewayClients);
@Delete
int delete(GatewayClient gatewayClient);
@Delete
void delete(List<GatewayClient> gatewayClients);
@Query("DELETE FROM GatewayClient")
void deleteAll();
@Query("SELECT * FROM GatewayClient WHERE id=:id")
GatewayClient fetch(long id);
// @Query("UPDATE GatewayClient SET projectName=:projectName, projectBinding=:projectBinding WHERE id=:id")
// void updateProjectNameAndProjectBinding(String projectName, String projectBinding, int id);
@Update
void update(GatewayClient gatewayClient);
// @Transaction
// default void repentance(List<GatewayClient> sinFulGatewayClients, List<GatewayClient> afreshGatewayClient) {
// delete(sinFulGatewayClients);
// insert(afreshGatewayClient);
// }
}
| 1,393 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjectAddActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjectAddActivity.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_ID;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.room.Room;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.SubscriptionInfo;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversationsHandler;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.R;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class GatewayClientProjectAddActivity extends AppCompatActivity {
public static final String GATEWAY_CLIENT_PROJECT_ID = "GATEWAY_CLIENT_PROJECT_ID";
GatewayClient gatewayClient;
GatewayClientHandler gatewayClientHandler;
SharedPreferences sharedPreferences;
SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener;
Toolbar toolbar;
Datastore databaseConnector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gateway_client_customization);
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
databaseConnector = Datastore.datastore;
toolbar = findViewById(R.id.gateway_client_customization_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try {
getGatewayClient();
getSupportActionBar().setTitle(gatewayClient == null ?
getString(R.string.add_new_gateway_server_toolbar_title) :
gatewayClient.getHostUrl());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
invalidateOptionsMenu();
}
};
sharedPreferences = getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
// checkForBatteryOptimization();
MaterialButton materialButton = findViewById(R.id.gateway_client_customization_save_btn);
materialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
onSaveGatewayClientConfiguration(v);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public void checkForBatteryOptimization() {
Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
startActivity(intent);
}
long id = -1;
private void getGatewayClient() throws InterruptedException {
TextInputEditText projectName = findViewById(R.id.new_gateway_client_project_name);
TextInputEditText projectBinding = findViewById(R.id.new_gateway_client_project_binding_sim_1);
TextInputEditText projectBinding2 = findViewById(R.id.new_gateway_client_project_binding_sim_2);
gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
long gatewayId = getIntent().getLongExtra(GATEWAY_CLIENT_ID, -1);
gatewayClient = gatewayClientHandler.fetch(gatewayId);
final boolean isDualSim = SIMHandler.isDualSim(getApplicationContext());
if(isDualSim) {
findViewById(R.id.new_gateway_client_project_binding_sim_2_constraint)
.setVisibility(View.VISIBLE);
}
if(getIntent().hasExtra(GATEWAY_CLIENT_PROJECT_ID)) {
id = getIntent().getLongExtra(GATEWAY_CLIENT_PROJECT_ID, -1);
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
GatewayClientProjects gatewayClientProjects =
databaseConnector.gatewayClientProjectDao().fetch(id);
runOnUiThread(new Runnable() {
@Override
public void run() {
projectName.setText(gatewayClientProjects.name);
projectBinding.setText(gatewayClientProjects.binding1Name);
}
});
if (isDualSim) {
runOnUiThread(new Runnable() {
@Override
public void run() {
projectBinding2.setText(gatewayClientProjects.binding2Name);
}
});
}
}
});
}
projectName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
List<String> projectBindings = GatewayClientHandler.getPublisherDetails(getApplicationContext(),
s.toString());
projectBinding.setText(projectBindings.get(0));
if(projectBindings.size() > 1) {
projectBinding2.setText(projectBindings.get(1));
}
}
});
}
public void onSaveGatewayClientConfiguration(View view) throws InterruptedException {
TextInputEditText projectName = findViewById(R.id.new_gateway_client_project_name);
TextInputEditText projectBinding = findViewById(R.id.new_gateway_client_project_binding_sim_1);
TextInputEditText projectBinding2 = findViewById(R.id.new_gateway_client_project_binding_sim_2);
ConstraintLayout projectBindingConstraint = findViewById(R.id.new_gateway_client_project_binding_sim_2_constraint);
if(projectName.getText() == null || projectName.getText().toString().isEmpty()) {
projectName.setError(getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(projectBinding.getText() == null || projectBinding.getText().toString().isEmpty()) {
projectBinding.setError(getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(projectBindingConstraint.getVisibility() == View.VISIBLE &&
(projectBinding2.getText() == null || projectBinding2.getText().toString().isEmpty())) {
projectBinding2.setError(getString(R.string.settings_gateway_client_cannot_be_empty));
return;
}
if(id == -1) {
GatewayClientProjects gatewayClientProjects = new GatewayClientProjects();
gatewayClientProjects.name = projectName.getText().toString();
gatewayClientProjects.binding1Name = projectBinding.getText().toString();
gatewayClientProjects.binding2Name = projectBinding2.getText().toString();
gatewayClientProjects.gatewayClientId = gatewayClient.getId();
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
databaseConnector.gatewayClientProjectDao().insert(gatewayClientProjects);
}
});
}
else {
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
GatewayClientProjects gatewayClientProjects =
databaseConnector.gatewayClientProjectDao().fetch(id);
gatewayClientProjects.name = projectName.getText().toString();
gatewayClientProjects.binding1Name = projectBinding.getText().toString();
gatewayClientProjects.binding2Name = projectBinding2.getText().toString();
gatewayClientProjects.gatewayClientId = gatewayClient.getId();
databaseConnector.gatewayClientProjectDao().update(gatewayClientProjects);
}
});
}
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(getIntent().hasExtra(GATEWAY_CLIENT_PROJECT_ID))
getMenuInflater().inflate(R.menu.gateway_client_customization_menu, menu);
return super.onCreateOptionsMenu(menu);
}
ExecutorService consumerExecutorService = Executors.newFixedThreadPool(2); // Create a pool of 5 worker threads
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (R.id.gateway_client_project_delete == item.getItemId()) {
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
databaseConnector.gatewayClientProjectDao().delete(id);
finish();
}
});
return true;
}
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
}
} | 10,615 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientListingActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientListingActivity.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.afkanerd.deku.DefaultSMS.LinkedDevicesQRActivity;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.R;
import java.util.List;
public class GatewayClientListingActivity extends AppCompatActivity {
public static String GATEWAY_CLIENT_ID = "GATEWAY_CLIENT_ID";
public static String GATEWAY_CLIENT_ID_NEW = "GATEWAY_CLIENT_ID_NEW";
public static String GATEWAY_CLIENT_USERNAME = "GATEWAY_CLIENT_USERNAME";
public static String GATEWAY_CLIENT_PASSWORD = "GATEWAY_CLIENT_PASSWORD";
public static String GATEWAY_CLIENT_VIRTUAL_HOST = "GATEWAY_CLIENT_VIRTUAL_HOST";
public static String GATEWAY_CLIENT_HOST = "GATEWAY_CLIENT_HOST";
public static String GATEWAY_CLIENT_PORT = "GATEWAY_CLIENT_PORT";
public static String GATEWAY_CLIENT_FRIENDLY_NAME = "GATEWAY_CLIENT_FRIENDLY_NAME";
public static String GATEWAY_CLIENT_LISTENERS = "GATEWAY_CLIENT_LISTENERS";
public static String GATEWAY_CLIENT_STOP_LISTENERS = "GATEWAY_CLIENT_STOP_LISTENERS";
SharedPreferences sharedPreferences;
Datastore databaseConnector;
GatewayClientDAO gatewayClientDAO;
Handler mHandler = new Handler();
GatewayClientRecyclerAdapter gatewayClientRecyclerAdapter;
GatewayClientViewModel gatewayClientViewModel;
SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gateway_client_listing);
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(getApplicationContext(), Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
databaseConnector = Datastore.datastore;
sharedPreferences = getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
toolbar = findViewById(R.id.gateway_client_listing_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.gateway_client_listing_toolbar_title));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
RecyclerView recyclerView = findViewById(R.id.gateway_client_listing_recycler_view);
recyclerView.setLayoutManager(linearLayoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getApplicationContext(),
linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
gatewayClientRecyclerAdapter = new GatewayClientRecyclerAdapter(this);
recyclerView.setAdapter(gatewayClientRecyclerAdapter);
gatewayClientViewModel = new ViewModelProvider(this).get(
GatewayClientViewModel.class);
gatewayClientDAO = databaseConnector.gatewayClientDAO();
gatewayClientViewModel.getGatewayClientList(
getApplicationContext(), gatewayClientDAO).observe(this,
new Observer<List<GatewayClient>>() {
@Override
public void onChanged(List<GatewayClient> gatewayServerList) {
if(gatewayServerList.size() < 1 )
findViewById(R.id.gateway_client_no_gateway_client_label).setVisibility(View.VISIBLE);
gatewayClientRecyclerAdapter.submitList(gatewayServerList);
}
});
registerListeners();
setRefreshTimer(gatewayClientRecyclerAdapter);
}
private void registerListeners() {
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
gatewayClientViewModel.refresh(getApplicationContext());
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
}
private void setRefreshTimer(GatewayClientRecyclerAdapter adapter) {
final int recyclerViewTimeUpdateLimit = 60 * 1000;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
mHandler.postDelayed(this, recyclerViewTimeUpdateLimit);
}
}, recyclerViewTimeUpdateLimit);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gateway_client_listing_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gateway_client_add_manually) {
Intent addGatewayIntent = new Intent(getApplicationContext(), GatewayClientAddActivity.class);
startActivity(addGatewayIntent);
return true;
}
else if (item.getItemId() == R.id.gateway_client_linked_device_add) {
Intent addGatewayIntent = new Intent(getApplicationContext(), LinkedDevicesQRActivity.class);
startActivity(addGatewayIntent);
return true;
}
return false;
}
private boolean saveListenerConfiguration(int id) {
SharedPreferences.Editor editor = sharedPreferences.edit();
return editor.putLong(String.valueOf(id), System.currentTimeMillis())
.commit();
}
private boolean removeListenerConfiguration(int id) {
SharedPreferences.Editor editor = sharedPreferences.edit();
return editor.remove(String.valueOf(id))
.commit();
}
} | 6,651 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientProjectDao.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientProjectDao.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface GatewayClientProjectDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<GatewayClientProjects> gatewayClientProjectsList);
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(GatewayClientProjects gatewayClientProjects);
@Query("SELECT * FROM GatewayClientProjects WHERE id = :id")
GatewayClientProjects fetch(long id);
@Query("SELECT * FROM GatewayClientProjects WHERE gatewayClientId = :gatewayClientId")
LiveData<List<GatewayClientProjects>> fetchGatewayClientId(long gatewayClientId);
@Query("SELECT * FROM GatewayClientProjects WHERE gatewayClientId = :gatewayClientId")
List<GatewayClientProjects> fetchGatewayClientIdList(long gatewayClientId);
@Update
void update(GatewayClientProjects gatewayClientProjects);
@Query("DELETE FROM GatewayClientProjects WHERE gatewayClientId = :id")
void deleteGatewayClientId(long id);
@Query("DELETE FROM GatewayClientProjects WHERE id = :id")
void delete(long id);
}
| 1,333 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientViewModel.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientViewModel.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import android.content.Context;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.util.ArrayList;
import java.util.List;
public class GatewayClientViewModel extends ViewModel {
private MutableLiveData<List<GatewayClient>> gatewayClientList;
GatewayClientDAO gatewayClientDAO;
public MutableLiveData<List<GatewayClient>> getGatewayClientList(Context context, GatewayClientDAO gatewayClientDAO) {
if(gatewayClientList == null) {
this.gatewayClientDAO = gatewayClientDAO;
gatewayClientList = new MutableLiveData<>();
loadGatewayClients(context);
}
return gatewayClientList;
}
public void refresh(Context context) {
loadGatewayClients(context);
}
private void loadGatewayClients(Context context) {
new Thread(new Runnable() {
@Override
public void run() {
List<GatewayClient> gatewayClients = normalizeGatewayClients(gatewayClientDAO.getAll());
for(GatewayClient gatewayClient : gatewayClients)
gatewayClient.setConnectionStatus(
GatewayClientHandler.getConnectionStatus(context,
String.valueOf(gatewayClient.getId())));
gatewayClientList.postValue(gatewayClients);
}
}).start();
}
private List<GatewayClient> normalizeGatewayClients(List<GatewayClient> gatewayClients) {
List<GatewayClient> filteredGatewayClients = new ArrayList<>();
for(GatewayClient gatewayClient : gatewayClients) {
boolean contained = false;
for(GatewayClient gatewayClient1 : filteredGatewayClients) {
if(gatewayClient1.same(gatewayClient)) {
contained = true;
break;
}
}
if(!contained) {
filteredGatewayClients.add(gatewayClient);
}
}
return filteredGatewayClients;
}
}
| 2,148 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
GatewayClientRecyclerAdapter.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/GatewayClients/GatewayClientRecyclerAdapter.java | package com.afkanerd.deku.QueueListener.GatewayClients;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClient.DIFF_CALLBACK;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.AsyncListDiffer;
import androidx.recyclerview.widget.RecyclerView;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.Models.ServiceHandler;
import com.afkanerd.deku.DefaultSMS.R;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class GatewayClientRecyclerAdapter extends RecyclerView.Adapter<GatewayClientRecyclerAdapter.ViewHolder>{
private final AsyncListDiffer<GatewayClient> mDiffer = new AsyncListDiffer(this, DIFF_CALLBACK);
List<ActivityManager.RunningServiceInfo> runningServiceInfoList = new ArrayList<>();
public static final String ADAPTER_POSITION = "ADAPTER_POSITION";
SharedPreferences sharedPreferences;
public GatewayClientRecyclerAdapter(Context context) {
runningServiceInfoList = ServiceHandler.getRunningService(context);
sharedPreferences = context.getSharedPreferences(
GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.gateway_client_listing_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
GatewayClient gatewayClient = mDiffer.getCurrentList().get(position);
String urlBuilder = gatewayClient.getProtocol() + "://" +
gatewayClient.getHostUrl() + ":" +
gatewayClient.getPort();
holder.url.setText(urlBuilder);
holder.virtualHost.setText(gatewayClient.getVirtualHost());
holder.friendlyName.setText(gatewayClient.getFriendlyConnectionName());
holder.username.setText(gatewayClient.getUsername());
holder.connectionStatus.setText(gatewayClient.getConnectionStatus());
String date = Helpers.formatDate(holder.itemView.getContext(), gatewayClient.getDate());
holder.date.setText(date);
if(gatewayClient.getFriendlyConnectionName() == null ||
gatewayClient.getFriendlyConnectionName().isEmpty())
holder.friendlyName.setVisibility(View.GONE);
else
holder.friendlyName.setText(gatewayClient.getFriendlyConnectionName());
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(holder.itemView.getContext(), GatewayClientProjectListingActivity.class);
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, gatewayClient.getId());
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_USERNAME,
gatewayClient.getUsername());
intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_HOST,
gatewayClient.getHostUrl());
holder.itemView.getContext().startActivity(intent);
}
});
}
public void submitList(List<GatewayClient> gatewayClientList) {
mDiffer.submitList(gatewayClientList);
}
@Override
public int getItemCount() {
return mDiffer.getCurrentList().size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView url, virtualHost, friendlyName, date, username, connectionStatus;
CardView cardView;
public ViewHolder(@NonNull @NotNull View itemView) {
super(itemView);
url = itemView.findViewById(R.id.gateway_client_url);
virtualHost = itemView.findViewById(R.id.gateway_client_virtual_host);
friendlyName = itemView.findViewById(R.id.gateway_client_friendly_name_text);
date = itemView.findViewById(R.id.gateway_client_date);
cardView = itemView.findViewById(R.id.gateway_client_card);
username = itemView.findViewById(R.id.gateway_client_username);
username = itemView.findViewById(R.id.gateway_client_username);
connectionStatus = itemView.findViewById(R.id.gateway_client_connection_status);
}
}
}
| 4,830 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
RMQConnectionService.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/RMQ/RMQConnectionService.java | package com.afkanerd.deku.QueueListener.RMQ;
import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.SMS_DELIVERED_BROADCAST_INTENT;
import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.SMS_SENT_BROADCAST_INTENT;
import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.SMS_UPDATED_BROADCAST_INTENT;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS;
import static org.junit.Assert.assertTrue;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ServiceInfo;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ConversationHandler;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.SemaphoreManager;
import com.afkanerd.deku.DefaultSMS.Models.NativeSMSDB;
import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientProjectDao;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientProjects;
import com.afkanerd.deku.Router.GatewayServers.GatewayServerHandler;
import com.afkanerd.deku.Router.Router.RouterHandler;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSReplyActionBroadcastReceiver;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClient;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientHandler;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.R;
import com.afkanerd.deku.Router.Router.RouterItem;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Command;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerShutdownSignalCallback;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;
import com.rabbitmq.client.RecoveryDelayHandler;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import com.rabbitmq.client.TrafficListener;
import com.rabbitmq.client.impl.DefaultExceptionHandler;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeoutException;
public class RMQConnectionService extends Service {
final int NOTIFICATION_ID = 1234;
private HashMap<Long, Connection> connectionList = new HashMap<>();
ExecutorService consumerExecutorService = Executors.newFixedThreadPool(10); // Create a pool of 5 worker threads
private BroadcastReceiver messageStateChangedBroadcast;
private SharedPreferences sharedPreferences;
private SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener;
public RMQConnectionService(Context context) {
attachBaseContext(context);
}
// DO NOT DELETE
public RMQConnectionService() { }
Datastore databaseConnector;
@Override
public void onCreate() {
super.onCreate();
if(Datastore.datastore == null || !Datastore.datastore.isOpen())
Datastore.datastore = Room.databaseBuilder(getApplicationContext(), Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
databaseConnector = Datastore.datastore;
handleBroadcast();
sharedPreferences = getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
registerListeners();
}
public int[] getGatewayClientNumbers() {
int running = 0;
int reconnecting = 0;
for(Long keys : connectionList.keySet()) {
Connection connection = connectionList.get(keys);
if(connection != null && connection.isOpen())
++running;
else
++reconnecting;
}
return new int[]{running, reconnecting};
}
private void registerListeners() {
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(getClass().getName(), "Shared preferences changed: " + key);
if(connectionList.containsKey(Long.parseLong(key))) {
if(connectionList.get(Long.parseLong(key)) != null &&
!sharedPreferences.contains(key) ) {
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
try {
stop(Long.parseLong(key));
} catch (Exception e) {
e.printStackTrace();
}
}
});
} else {
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
}
}
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
}
private void handleBroadcast() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SMS_SENT_BROADCAST_INTENT);
// intentFilter.addAction(SMS_DELIVERED_BROADCAST_INTENT);
messageStateChangedBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, @NonNull Intent intent) {
if (intent.getAction() != null && intentFilter.hasAction(intent.getAction())) {
if(intent.hasExtra(RMQConnection.MESSAGE_SID) &&
intent.hasExtra(RMQConnection.RMQ_DELIVERY_TAG)) {
final String sid = intent.getStringExtra(RMQConnection.MESSAGE_SID);
final String messageId = intent.getStringExtra(NativeSMSDB.ID);
final String consumerTag =
intent.getStringExtra(RMQConnection.RMQ_CONSUMER_TAG);
final long deliveryTag =
intent.getLongExtra(RMQConnection.RMQ_DELIVERY_TAG, -1);
assertTrue(deliveryTag != -1);
Channel channel = activeConsumingChannels.get(consumerTag);
if(intentFilter.hasAction(intent.getAction())) {
Log.d(getClass().getName(), "Received an ACK of the message...");
if(getResultCode() == Activity.RESULT_OK) {
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
try {
Log.i(getClass().getName(),
"Confirming message sent");
if(channel == null || !channel.isOpen()) {
return;
}
channel.basicAck(deliveryTag, false);
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
Log.w(getClass().getName(), "Rejecting message sent");
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
try {
if(channel == null || !channel.isOpen()) {
return;
}
channel.basicReject(deliveryTag, true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
}
}
};
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S)
registerReceiver(messageStateChangedBroadcast, intentFilter, Context.RECEIVER_EXPORTED);
else
registerReceiver(messageStateChangedBroadcast, intentFilter);
}
private DeliverCallback getDeliverCallback(final Channel channel, final int subscriptionId) {
return (consumerTag, delivery) -> {
try {
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(message);
final String body = jsonObject.getString(RMQConnection.MESSAGE_BODY_KEY);
final String msisdn = jsonObject.getString(RMQConnection.MESSAGE_MSISDN_KEY);
final String sid = jsonObject.getString(RMQConnection.MESSAGE_SID);
long threadId = Telephony.Threads.getOrCreateThreadId(getApplicationContext(), msisdn);
Bundle bundle = new Bundle();
bundle.putString(RMQConnection.MESSAGE_SID, sid);
bundle.putLong(RMQConnection.RMQ_DELIVERY_TAG,
delivery.getEnvelope().getDeliveryTag());
bundle.putString(RMQConnection.RMQ_CONSUMER_TAG, consumerTag);
SemaphoreManager.acquireSemaphore(subscriptionId);
long messageId = System.currentTimeMillis();
Conversation conversation = new Conversation();
conversation.setMessage_id(String.valueOf(messageId));
conversation.setText(body);
conversation.setSubscription_id(subscriptionId);
conversation.setType(Telephony.Sms.MESSAGE_TYPE_OUTBOX);
conversation.setDate(String.valueOf(System.currentTimeMillis()));
conversation.setAddress(msisdn);
conversation.setThread_id(String.valueOf(threadId));
conversation.setStatus(Telephony.Sms.STATUS_PENDING);
databaseConnector.conversationDao().insert(conversation);
Log.d(getClass().getName(), "Sending RMQ SMS: " + subscriptionId + ":"
+ conversation.getAddress());
SMSDatabaseWrapper.send_text(getApplicationContext(), conversation, bundle);
} catch (JSONException e) {
e.printStackTrace();
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
if(channel != null && channel.isOpen()) {
try {
channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
} catch(Exception e) {
e.printStackTrace();
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
try {
if(channel != null && channel.isOpen())
channel.basicReject(delivery.getEnvelope().getDeliveryTag(),
true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
} finally {
try {
SemaphoreManager.releaseSemaphore(subscriptionId);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
private void startAllGatewayClientConnections() {
Log.d(getClass().getName(), "Starting all connections...");
// connectionList.clear();
Map<String, ?> storedGatewayClients = sharedPreferences.getAll();
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
for (String gatewayClientIds : storedGatewayClients.keySet()) {
if(!connectionList.containsKey(Long.parseLong(gatewayClientIds)) ||
(connectionList.get(Long.parseLong(gatewayClientIds)) != null &&
!connectionList.get(Long.parseLong(gatewayClientIds)).isOpen())) {
try {
GatewayClient gatewayClient =
gatewayClientHandler.fetch(Long.parseLong(gatewayClientIds));
connectGatewayClient(gatewayClient);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startAllGatewayClientConnections();
return START_STICKY;
}
public void startConnection(ConnectionFactory factory, GatewayClient gatewayClient) throws IOException, TimeoutException, InterruptedException {
Log.d(getClass().getName(), "Starting new connection...");
Connection connection = connectionList.get(gatewayClient.getId());
if(connection == null || !connection.isOpen()) {
try {
connection = factory.newConnection(consumerExecutorService,
gatewayClient.getFriendlyConnectionName());
} catch (Exception e) {
e.printStackTrace();
Thread.sleep(5000);
startConnection(factory, gatewayClient);
}
}
RMQConnection rmqConnection = new RMQConnection(connection);
connectionList.put(gatewayClient.getId(), connection);
if(connection != null)
connection.addShutdownListener(new ShutdownListener() {
@Override
public void shutdownCompleted(ShutdownSignalException cause) {
Log.e(getClass().getName(), "Connection shutdown cause: " + cause.toString());
if(sharedPreferences.getBoolean(String.valueOf(gatewayClient.getId()), false)) {
try {
connectionList.remove(gatewayClient.getId());
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
startConnection(factory, gatewayClient);
} catch (IOException | TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}
}
});
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
GatewayClientProjectDao gatewayClientProjectDao =
gatewayClientHandler.databaseConnector.gatewayClientProjectDao();
List<SubscriptionInfo> subscriptionInfoList = SIMHandler
.getSimCardInformation(getApplicationContext());
List<GatewayClientProjects> gatewayClientProjectsList =
gatewayClientProjectDao.fetchGatewayClientIdList(gatewayClient.getId());
Log.d(getClass().getName(), "Subscription number: " + subscriptionInfoList.size());
for(int i=0;i<gatewayClientProjectsList.size(); ++i) {
for(int j=0;j<subscriptionInfoList.size();++j) {
final Channel channel = rmqConnection.createChannel();
GatewayClientProjects gatewayClientProjects = gatewayClientProjectsList.get(i);
String bindingName = j > 0 ? gatewayClientProjects.binding2Name :
gatewayClientProjects.binding1Name;
int subscriptionId = subscriptionInfoList.get(j).getSubscriptionId();
startChannelConsumption(rmqConnection, channel, subscriptionId,
gatewayClientProjects, bindingName);
}
}
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
}
public void startChannelConsumption(RMQConnection rmqConnection, final Channel channel,
final int subscriptionId,
final GatewayClientProjects gatewayClientProjects,
final String bindingName) throws IOException {
channel.basicRecover(true);
final DeliverCallback deliverCallback = getDeliverCallback(channel, subscriptionId);
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
try {
String queueName = rmqConnection.createQueue(gatewayClientProjects.name, bindingName,
channel, null);
long messagesCount = channel.messageCount(queueName);
Log.d(getClass().getName(), "Created Queue: " + queueName
+ " (" + messagesCount + ")");
String consumerTag = channel.basicConsume(queueName, false, deliverCallback,
new ConsumerShutdownSignalCallback() {
@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
Log.e(getClass().getName(), "Consumer error: " + sig.getMessage());
if(rmqConnection.connection != null && rmqConnection.connection.isOpen()) {
try {
activeConsumingChannels.remove(consumerTag);
Channel channel = rmqConnection.createChannel();
startChannelConsumption(rmqConnection, channel, subscriptionId,
gatewayClientProjects, bindingName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
activeConsumingChannels.put(consumerTag, channel);
Log.i(getClass().getName(), "Adding tag: " + consumerTag);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Map<String, Channel> activeConsumingChannels = new HashMap<>();
boolean disconnected = false;
public void connectGatewayClient(GatewayClient gatewayClient) throws InterruptedException {
Log.d(getClass().getName(), "Starting new service connection...");
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername(gatewayClient.getUsername());
factory.setPassword(gatewayClient.getPassword());
factory.setVirtualHost(gatewayClient.getVirtualHost());
factory.setHost(gatewayClient.getHostUrl());
factory.setPort(gatewayClient.getPort());
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(10000);
factory.setExceptionHandler(new DefaultExceptionHandler());
factory.setRecoveryDelayHandler(new RecoveryDelayHandler() {
@Override
public long getDelay(int recoveryAttempts) {
Log.w(getClass().getName(), "Factory recovering...: " + recoveryAttempts);
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
disconnected = true;
return 10000;
}
});
factory.setTrafficListener(new TrafficListener() {
@Override
public void write(Command outboundCommand) {
}
@Override
public void read(Command inboundCommand) {
if(disconnected) {
Objects.requireNonNull(connectionList.get(gatewayClient.getId())).abort();
connectionList.remove(gatewayClient.getId());
startAllGatewayClientConnections();
disconnected = false;
}
}
});
consumerExecutorService.execute(new Runnable() {
@Override
public void run() {
/**
* Avoid risk of :ForegroundServiceDidNotStartInTimeException
* - Put RMQ connection in list before connecting which could take a while
*/
try {
startConnection(factory, gatewayClient);
} catch (IOException | TimeoutException | InterruptedException e) {
e.printStackTrace();
}
}
});
}
private void stop(long gatewayClientId) throws IOException {
if(connectionList.containsKey(gatewayClientId)) {
Connection connection = connectionList.get(gatewayClientId);
if(connection != null)
connection.close();
connectionList.remove(gatewayClientId);
if(connectionList.isEmpty()) {
stopForeground(true);
stopSelf();
}
else {
int[] states = getGatewayClientNumbers();
createForegroundNotification(states[0], states[1]);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getName(), "Ending connection...");
if(messageStateChangedBroadcast != null)
unregisterReceiver(messageStateChangedBroadcast);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void createForegroundNotification(int runningGatewayClientCount, int reconnecting) {
Intent notificationIntent = new Intent(getApplicationContext(), GatewayClientListingActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE);
String description = runningGatewayClientCount + " " +
getString(R.string.gateway_client_running_description);
if(reconnecting > 0)
description += "\n" + reconnecting + " " +
getString(R.string.gateway_client_reconnecting_description);
Notification notification =
new NotificationCompat.Builder(getApplicationContext(),
getString(R.string.running_gateway_clients_channel_id))
.setContentTitle(getApplicationContext()
.getString(R.string.gateway_client_running_title))
.setSmallIcon(R.drawable.ic_stat_name)
.setPriority(NotificationCompat.DEFAULT_ALL)
.setSilent(true)
.setOngoing(true)
.setContentText(description)
.setContentIntent(pendingIntent)
.build();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(NOTIFICATION_ID, notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
}
else
startForeground(NOTIFICATION_ID, notification);
}
}
| 25,880 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
RMQWorkManager.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/RMQ/RMQWorkManager.java | package com.afkanerd.deku.QueueListener.RMQ;
import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS;
import android.app.ForegroundServiceStartNotAllowedException;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.afkanerd.deku.DefaultSMS.ThreadedConversationsActivity;
import com.afkanerd.deku.DefaultSMS.R;
public class RMQWorkManager extends Worker {
final int NOTIFICATION_ID = 12345;
SharedPreferences sharedPreferences;
public RMQWorkManager(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
Intent intent = new Intent(getApplicationContext(), RMQConnectionService.class);
sharedPreferences = getApplicationContext()
.getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE);
if(!sharedPreferences.getAll().isEmpty()) {
try {
getApplicationContext().startForegroundService(intent);
RMQConnectionService rmqConnectionService =
new RMQConnectionService(getApplicationContext());
// rmqConnectionService.createForegroundNotification(0,
// sharedPreferences.getAll().size());
} catch (Exception e) {
e.printStackTrace();
if (e instanceof ForegroundServiceStartNotAllowedException) {
notifyUserToReconnectSMSServices();
}
return Result.failure();
}
}
return Result.success();
}
private void notifyUserToReconnectSMSServices(){
Intent notificationIntent = new Intent(getApplicationContext(), ThreadedConversationsActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_IMMUTABLE);
Notification notification =
new NotificationCompat.Builder(getApplicationContext(),
getApplicationContext().getString(R.string.foreground_service_failed_channel_id))
.setContentTitle(getApplicationContext()
.getString(R.string.foreground_service_failed_channel_name))
.setSmallIcon(R.drawable.ic_stat_name)
.setPriority(NotificationCompat.DEFAULT_ALL)
.setAutoCancel(true)
.setContentText(getApplicationContext()
.getString(R.string.foreground_service_failed_channel_description))
.setContentIntent(pendingIntent)
.build();
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
| 3,354 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
RMQConnection.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/QueueListener/RMQ/RMQConnection.java | package com.afkanerd.deku.QueueListener.RMQ;
import android.util.Log;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import com.rabbitmq.client.impl.ChannelN;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RMQConnection {
final boolean autoDelete = false;
final boolean exclusive = false;
final boolean durable = true;
final boolean autoAck = false;
public static final String MESSAGE_BODY_KEY = "text";
public static final String MESSAGE_MSISDN_KEY = "to";
public static final String MESSAGE_SID = "sid";
public static final String RMQ_DELIVERY_TAG = "RMQ_DELIVERY_TAG";
public static final String RMQ_CONSUMER_TAG = "RMQ_CONSUMER_TAG";
public Connection connection;
// private Channel channel1;
// private Channel channel2;
// public Channel getChannel2() {
// return channel2;
// }
//
// public void setChannel2(Channel channel2) {
// this.channel2 = channel2;
// }
//
private boolean reconnecting = false;
public void setReconnecting(boolean reconnecting) {
this.reconnecting = reconnecting;
}
// private DeliverCallback deliverCallback, deliverCallback2;
public RMQConnection(Connection connection) throws IOException {
this.connection = connection;
}
public RMQConnection(){
}
// public Channel[] getChannels() throws IOException {
// Channel channel1 = this.connection.createChannel();
// Channel channel2 = this.connection.createChannel();
//
// int prefetchCount = 1;
// channel1.basicQos(prefetchCount);
// channel2.basicQos(prefetchCount);
//
// return new Channel[]{channel1, channel2};
// }
// public Channel[] setConnection(Connection connection) throws IOException {
// this.connection = connection;
//
// Channel channel1 = this.connection.createChannel();
// channel1.basicRecover(true);
// Channel channel2 = this.connection.createChannel();
// channel2.basicRecover(true);
//
// int prefetchCount = 1;
// channel1.basicQos(prefetchCount);
// channel2.basicQos(prefetchCount);
//
// return new Channel[]{channel1, channel2};
// }
public List<Channel> channelList = new ArrayList<>();
public void removeChannel(Channel channel) {
channelList.remove(channel);
}
public Channel createChannel() throws IOException {
int prefetchCount = 1;
Channel channel = this.connection.createChannel();
channel.basicQos(prefetchCount);
channelList.add(channel);
return channelList.get(channelList.size() -1);
}
public void close() throws IOException {
if(connection != null)
connection.close();
}
public Connection getConnection() {
return connection;
}
public String createQueue(String exchangeName, String bindingKey, Channel channel,
String queueName) throws IOException {
if(queueName == null)
queueName = bindingKey.replaceAll("\\.", "_");
channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);
channel.queueBind(queueName, exchangeName, bindingKey);
return queueName;
}
// public void createQueue1(String exchangeName, String bindingKey, DeliverCallback deliverCallback) throws IOException {
// this.queueName = bindingKey.replaceAll("\\.", "_");
// this.deliverCallback = deliverCallback;
//
// this.channel1.queueDeclare(queueName, durable, exclusive, autoDelete, null);
// this.channel1.queueBind(queueName, exchangeName, bindingKey);
// this.channel1.addShutdownListener(new ShutdownListener() {
// @Override
// public void shutdownCompleted(ShutdownSignalException cause) {
// Log.d(getClass().getName(), "CHannel shutdown listener called: " + cause.toString());
// }
// });
// }
//
// public void createQueue2(String exchangeName, String bindingKey, DeliverCallback deliverCallback) throws IOException {
// this.queueName2 = bindingKey.replaceAll("\\.", "_");
// this.deliverCallback = deliverCallback;
//
// this.channel2.queueDeclare(queueName2, durable, exclusive, autoDelete, null);
// this.channel2.queueBind(queueName2, exchangeName, bindingKey);
// }
public String consume(Channel channel, String queueName, DeliverCallback deliverCallback) throws IOException {
/**
* - Binding information dumb:
* 1. .usd. = <anything>.usd.</anything>
* 2. *.usd = <single anything>.usd
* 3. #.usd = <many anything>.usd
* 4. Can all be used in combination with each
* 5. We can translate this into managing multiple service providers
*/
// ShutdownListener shutdownListener2 = new ShutdownListener() {
// @Override
// public void shutdownCompleted(ShutdownSignalException cause) {
// Log.d(getClass().getName(), "Channel shutdown listener called: " + cause.toString());
// if(!cause.isInitiatedByApplication() && connection.isOpen()) {
// try {
// channels[1].basicConsume(queueName2, autoAck, deliverCallback, consumerTag -> {});
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// };
return channel.basicConsume(queueName, autoAck, deliverCallback, consumerTag -> {});
}
// public void consume1() throws IOException {
// /**
// * - Binding information dumb:
// * 1. .usd. = <anything>.usd.</anything>
// * 2. *.usd = <single anything>.usd
// * 3. #.usd = <many anything>.usd
// * 4. Can all be used in combination with each
// * 5. We can translate this into managing multiple service providers
// */
// this.channel1.basicConsume(this.queueName, autoAck, deliverCallback, consumerTag -> {});
// }
//
// public void consume2() throws IOException {
// this.channel2.basicConsume(this.queueName2, autoAck, deliverCallback, consumerTag -> {});
// }
}
| 6,461 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ConversationsThreadsEncryption.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/ConversationsThreadsEncryption.java | package com.afkanerd.deku.E2EE;
import android.content.Context;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations;
import com.afkanerd.deku.E2EE.Security.CustomKeyStoreDao;
@Entity(indices = {@Index(value={"keystoreAlias"}, unique=true)})
public class ConversationsThreadsEncryption {
@PrimaryKey(autoGenerate = true)
private long id;
// DHs comes from here
private String keystoreAlias;
// DHr comes from here
private String publicKey;
private String states;
// would most likely use this for backward compatibility
private long exchangeDate;
public void setStates(String states) {
this.states = states;
}
public String getStates() {
return this.states;
}
public String getKeystoreAlias() {
return keystoreAlias;
}
public void setKeystoreAlias(String keystoreAlias) {
this.keystoreAlias = keystoreAlias;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public long getExchangeDate() {
return exchangeDate;
}
public void setExchangeDate(long exchangeDate) {
this.exchangeDate = exchangeDate;
}
}
| 1,592 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ConversationsThreadsEncryptionDao.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/ConversationsThreadsEncryptionDao.java | package com.afkanerd.deku.E2EE;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface ConversationsThreadsEncryptionDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(ConversationsThreadsEncryption conversationsThreadsEncryption);
@Update
int update(ConversationsThreadsEncryption conversationsThreadsEncryption);
@Query("SELECT * FROM ConversationsThreadsEncryption WHERE keystoreAlias = :keystoreAlias")
ConversationsThreadsEncryption findByKeystoreAlias(String keystoreAlias);
@Query("SELECT * FROM ConversationsThreadsEncryption")
List<ConversationsThreadsEncryption> getAll();
@Query("SELECT * FROM ConversationsThreadsEncryption WHERE keystoreAlias = :keystoreAlias")
ConversationsThreadsEncryption fetch(String keystoreAlias);
@Query("DELETE FROM ConversationsThreadsEncryption WHERE keystoreAlias = :keystoreAlias")
int delete(String keystoreAlias);
}
| 1,078 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
E2EEHandler.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/E2EEHandler.java | package com.afkanerd.deku.E2EE;
import android.content.Context;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.E2EE.Security.CustomKeyStore;
import com.afkanerd.deku.E2EE.Security.CustomKeyStoreDao;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.KeystoreHelpers;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityECDH;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Headers;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.Ratchets;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.libsignal.States;
import com.google.common.primitives.Bytes;
import com.google.i18n.phonenumbers.NumberParseException;
import org.json.JSONException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class E2EEHandler {
// DONT_CARE_ENOUGH_MESSAGED_FIRST => Headers information
public final static String DEFAULT_HEADER_START_PREFIX = "HDEKU{";
public final static String DEFAULT_HEADER_END_PREFIX = "}UKEDH";
public final static String DEFAULT_TEXT_START_PREFIX = "TDEKU{";
public final static String DEFAULT_TEXT_END_PREFIX = "}UKEDT";
public final static String DEFAULT_HEADER_START_PREFIX_SHORTER = "H{";
public final static String DEFAULT_HEADER_END_PREFIX_SHORTER = "}H";
public final static String DEFAULT_TEXT_START_PREFIX_SHORTER = "T{";
public final static String DEFAULT_TEXT_END_PREFIX_SHORTER = "}T";
public static String convertToDefaultTextFormat(byte[] data) {
return DEFAULT_TEXT_START_PREFIX_SHORTER
+ Base64.encodeToString(data, Base64.NO_WRAP) +
DEFAULT_TEXT_END_PREFIX_SHORTER;
}
public static byte[] convertPublicKeyToDekuFormat(byte[] data) {
return Bytes.concat(DEFAULT_HEADER_START_PREFIX.getBytes(StandardCharsets.UTF_8),
data, DEFAULT_HEADER_END_PREFIX.getBytes(StandardCharsets.UTF_8));
}
public static String deriveKeystoreAlias(String address, int mode) throws NumberParseException {
String[] addressDetails = Helpers.getCountryNationalAndCountryCode(address);
String keystoreAliasRequirements = addressDetails[0] + addressDetails[1] + "_" + mode;
return Base64.encodeToString(keystoreAliasRequirements.getBytes(), Base64.NO_WRAP);
}
public static String getAddressFromKeystore(String keystoreAlias) {
String decodedAlias = new String(Base64.decode(keystoreAlias, Base64.NO_WRAP),
StandardCharsets.UTF_8);
return "+" + decodedAlias.split("_")[0];
}
public static boolean isAvailableInKeystore(String keystoreAlias) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
/*
* Load the Android KeyStore instance using the
* AndroidKeyStore provider to list the currently stored entries.
*/
return KeystoreHelpers.isAvailableInKeystore(keystoreAlias);
}
public static boolean canCommunicateSecurely(Context context, String keystoreAlias) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context, Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
return isAvailableInKeystore(keystoreAlias) &&
Datastore.datastore.conversationsThreadsEncryptionDao()
.findByKeystoreAlias(keystoreAlias) != null;
}
public static PublicKey createNewKeyPair(Context context, String keystoreAlias)
throws GeneralSecurityException, InterruptedException, IOException {
Pair<KeyPair, byte[]> publicKeyPair = SecurityECDH.generateKeyPair(keystoreAlias);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
storeInCustomKeystore(context, keystoreAlias, publicKeyPair.first, publicKeyPair.second);
}
return publicKeyPair.first.getPublic();
}
private static void storeInCustomKeystore(Context context, String keystoreAlias, KeyPair keyPair,
byte[] encryptedPrivateKey) throws InterruptedException {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
CustomKeyStore customKeyStore = new CustomKeyStore();
customKeyStore.setPrivateKey(Base64.encodeToString(encryptedPrivateKey, Base64.NO_WRAP));
customKeyStore.setPublicKey(Base64.encodeToString(keyPair.getPublic().getEncoded(),
Base64.NO_WRAP));
customKeyStore.setKeystoreAlias(keystoreAlias);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
CustomKeyStoreDao customKeyStoreDao = Datastore.datastore.customKeyStoreDao();
customKeyStoreDao.insert(customKeyStore);
}
});
}
public static void removeFromKeystore(Context context, String keystoreAlias) throws KeyStoreException,
CertificateException, IOException, NoSuchAlgorithmException, InterruptedException {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
KeystoreHelpers.removeFromKeystore(context, keystoreAlias);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
CustomKeyStoreDao customKeyStoreDao = Datastore.datastore.customKeyStoreDao();
customKeyStoreDao.delete(keystoreAlias);
}
});
}
public static boolean isValidDefaultPublicKey(byte[] publicKey) {
// Backward compatibility - should be removed in later versions if can guarantee all users
// migrated.
byte[] start = DEFAULT_HEADER_START_PREFIX.getBytes(StandardCharsets.UTF_8);
byte[] end = DEFAULT_HEADER_END_PREFIX.getBytes(StandardCharsets.UTF_8);
byte[] startShorter = DEFAULT_HEADER_START_PREFIX_SHORTER.getBytes(StandardCharsets.UTF_8);
byte[] endShorter = DEFAULT_HEADER_END_PREFIX_SHORTER.getBytes(StandardCharsets.UTF_8);
int indexStart = Bytes.indexOf(publicKey, start);
int indexEnd = Bytes.indexOf(publicKey, end);
int indexStartShorter = Bytes.indexOf(publicKey, startShorter);
int indexEndShorter = Bytes.indexOf(publicKey, endShorter);
if(indexStart == 0 && indexEnd == ((publicKey.length - end.length))) {
byte[] keyValue = new byte[publicKey.length - (start.length + end.length)];
System.arraycopy(publicKey, start.length, keyValue, 0, keyValue.length);
try {
SecurityECDH.buildPublicKey(keyValue);
} catch(Exception e) {
e.printStackTrace();
return false;
}
return true;
} else if(indexStartShorter == 0 &&
indexEndShorter == ((publicKey.length - endShorter.length))) {
byte[] keyValue = new byte[publicKey.length - (startShorter.length + endShorter.length)];
System.arraycopy(publicKey, startShorter.length, keyValue, 0, keyValue.length);
try {
SecurityECDH.buildPublicKey(keyValue);
} catch(Exception e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
public static boolean isValidDefaultText(String text) {
String encodedText;
if(text == null)
return false;
if(text.length() > (DEFAULT_TEXT_START_PREFIX_SHORTER.length() +
DEFAULT_TEXT_END_PREFIX_SHORTER.length()) &&
text.startsWith(DEFAULT_TEXT_START_PREFIX_SHORTER) &&
text.endsWith(DEFAULT_TEXT_END_PREFIX_SHORTER))
encodedText = text.substring(DEFAULT_TEXT_START_PREFIX_SHORTER.length(),
(text.length() - DEFAULT_TEXT_END_PREFIX_SHORTER.length()));
else if(text.length() > (DEFAULT_TEXT_START_PREFIX.length() +
DEFAULT_TEXT_END_PREFIX.length()) &&
text.startsWith(DEFAULT_TEXT_START_PREFIX) &&
text.endsWith(DEFAULT_TEXT_END_PREFIX))
encodedText = text.substring(DEFAULT_TEXT_START_PREFIX.length(),
(text.length() - DEFAULT_TEXT_END_PREFIX.length()));
else return false;
try {
return Helpers.isBase64Encoded(encodedText);
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
public static byte[] buildDefaultPublicKey(byte[] data) {
return convertPublicKeyToDekuFormat(data);
}
public static byte[] extractTransmissionKey(byte[] data) {
byte[] start = DEFAULT_HEADER_START_PREFIX.getBytes(StandardCharsets.UTF_8);
byte[] end = DEFAULT_HEADER_END_PREFIX.getBytes(StandardCharsets.UTF_8);
byte[] transmissionKey = new byte[data.length - (start.length + end.length)];
System.arraycopy(data, start.length, transmissionKey, 0, transmissionKey.length);
return transmissionKey;
}
/**
* This uses session = 0, which is the default PublicKey values for.
*
* @param context
* @param address
* @return
* @throws NumberParseException
* @throws GeneralSecurityException
* @throws IOException
* @throws InterruptedException
*/
public static Pair<String, byte[]> buildForEncryptionRequest(Context context, String address) throws Exception {
int session = 0;
String keystoreAlias = deriveKeystoreAlias(address, session);
PublicKey publicKey = createNewKeyPair(context, keystoreAlias);
return new Pair<>(keystoreAlias, buildDefaultPublicKey(publicKey.getEncoded()));
}
/**
* Inserts the peer public key which would be used as the primary key for everything this peer.
* @param context
* @param publicKey
* @param keystoreAlias
* @return
* @throws GeneralSecurityException
* @throws IOException
* @throws InterruptedException
* @throws NumberParseException
*/
public static long insertNewAgreementKeyDefault(Context context, byte[] publicKey, String keystoreAlias) throws GeneralSecurityException, IOException, InterruptedException, NumberParseException {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
ConversationsThreadsEncryption conversationsThreadsEncryption =
new ConversationsThreadsEncryption();
conversationsThreadsEncryption.setPublicKey(Base64.encodeToString(publicKey, Base64.NO_WRAP));
conversationsThreadsEncryption.setExchangeDate(System.currentTimeMillis());
conversationsThreadsEncryption.setKeystoreAlias(keystoreAlias);
ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao =
Datastore.datastore.conversationsThreadsEncryptionDao();
return conversationsThreadsEncryptionDao.insert(conversationsThreadsEncryption);
}
public static ConversationsThreadsEncryption fetchStoredPeerData(Context context,
String keystoreAlias) {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao =
Datastore.datastore.conversationsThreadsEncryptionDao();
return conversationsThreadsEncryptionDao.fetch(keystoreAlias);
}
public static KeyPair getKeyPairBasedVersioning(Context context, String keystoreAlias) throws UnrecoverableEntryException, CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, InterruptedException {
final KeyPair[] keyPair = new KeyPair[1];
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
CustomKeyStoreDao customKeyStoreDao = Datastore.datastore.customKeyStoreDao();
CustomKeyStore customKeyStore = customKeyStoreDao.find(keystoreAlias);
try {
if(customKeyStore != null)
keyPair[0] = customKeyStore.getKeyPair();
} catch (UnrecoverableKeyException | InvalidKeySpecException |
InvalidKeyException | BadPaddingException | IllegalBlockSizeException |
NoSuchPaddingException | InvalidAlgorithmParameterException |
NoSuchAlgorithmException | IOException | KeyStoreException |
CertificateException e) {
e.printStackTrace();
}
}
});
thread.start();
thread.join();
} else {
keyPair[0] = KeystoreHelpers.getKeyPairFromKeystore(keystoreAlias);
}
return keyPair[0];
}
protected static String getKeystoreForRatchets(String keystoreAlias) {
return keystoreAlias + "-ratchet-sessions";
}
public static byte[][] encrypt(Context context, final String keystoreAlias, byte[] data) throws Throwable {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao =
Datastore.datastore.conversationsThreadsEncryptionDao();
ConversationsThreadsEncryption conversationsThreadsEncryption =
conversationsThreadsEncryptionDao.findByKeystoreAlias(keystoreAlias);
States states;
final String keystoreAliasRatchet = getKeystoreForRatchets(keystoreAlias);
KeyPair keyPair = getKeyPairBasedVersioning(context, keystoreAliasRatchet);
if(keyPair == null) {
/**
* You are Alice, so act like it
*/
PublicKey publicKey = SecurityECDH.buildPublicKey(
Base64.decode(conversationsThreadsEncryption.getPublicKey(), Base64.DEFAULT));
keyPair = getKeyPairBasedVersioning(context, keystoreAlias);
final byte[] SK = SecurityECDH.generateSecretKey(keyPair, publicKey);
states = new States();
byte[] output = Ratchets.ratchetInitAlice(keystoreAliasRatchet, states, SK, publicKey);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S)
storeInCustomKeystore(context, keystoreAliasRatchet, states.DHs, output);
}
else {
states = new States(keyPair, conversationsThreadsEncryption.getStates());
}
byte[] AD = Base64.decode(conversationsThreadsEncryption.getPublicKey(), Base64.NO_WRAP);
Pair<Headers, byte[][]> cipherPair = Ratchets.ratchetEncrypt(states, data, AD);
conversationsThreadsEncryption.setStates(states.getSerializedStates());
conversationsThreadsEncryptionDao.update(conversationsThreadsEncryption);
return new byte[][]{Bytes.concat(cipherPair.first.getSerialized(), cipherPair.second[0]),
cipherPair.second[1]};
}
public static byte[] decrypt(Context context, final String keystoreAlias,
final byte[] cipherText, byte[] mk, byte[] _AD) throws Throwable {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao =
Datastore.datastore.conversationsThreadsEncryptionDao();
ConversationsThreadsEncryption conversationsThreadsEncryption =
conversationsThreadsEncryptionDao.findByKeystoreAlias(keystoreAlias);
Headers header = new Headers();
byte[] outputCipherText = header.deSerializeHeader(cipherText);
States states;
final String keystoreAliasRatchet = getKeystoreForRatchets(keystoreAlias);
KeyPair keyPair = getKeyPairBasedVersioning(context, keystoreAliasRatchet);
if(keyPair == null) {
/**
* You are Bob, act like it
*/
keyPair = getKeyPairBasedVersioning(context, keystoreAlias);
PublicKey publicKey = SecurityECDH.buildPublicKey(
Base64.decode(conversationsThreadsEncryption.getPublicKey(), Base64.DEFAULT));
final byte[] SK = SecurityECDH.generateSecretKey(keyPair, publicKey);
states = Ratchets.ratchetInitBob(new States(), SK, keyPair);
} else {
states = new States(keyPair, conversationsThreadsEncryption.getStates());
}
byte[] AD = _AD == null ?
getKeyPairBasedVersioning(context, keystoreAlias).getPublic().getEncoded() : _AD;
Pair<byte[], byte[]> decryptedText = Ratchets.ratchetDecrypt(keystoreAliasRatchet, states,
header, outputCipherText, AD, mk);
if(mk == null) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.S && decryptedText.second != null) {
storeInCustomKeystore(context, keystoreAliasRatchet, states.DHs, decryptedText.second);
}
conversationsThreadsEncryption.setStates(states.getSerializedStates());
conversationsThreadsEncryptionDao.update(conversationsThreadsEncryption);
}
return decryptedText.first;
}
public static String buildTransmissionText(byte[] data) throws Exception {
return convertToDefaultTextFormat(data);
}
public static byte[] extractTransmissionText(String text) throws Exception {
String encodedText;
if(text.startsWith(DEFAULT_TEXT_START_PREFIX_SHORTER) &&
text.endsWith(DEFAULT_TEXT_END_PREFIX_SHORTER))
encodedText = text.substring(DEFAULT_TEXT_START_PREFIX_SHORTER.length(),
(text.length() - DEFAULT_TEXT_END_PREFIX_SHORTER.length()));
else if(text.startsWith(DEFAULT_TEXT_START_PREFIX) && text.endsWith(DEFAULT_TEXT_END_PREFIX))
encodedText = text.substring(DEFAULT_TEXT_START_PREFIX.length(),
(text.length() - DEFAULT_TEXT_END_PREFIX.length()));
else
throw new Exception("Invalid Transmission Text");
return Base64.decode(encodedText, Base64.NO_WRAP);
}
public final static int REQUEST_KEY = 0;
public final static int AGREEMENT_KEY = 1;
public final static int IGNORE_KEY = 2;
public static int getKeyType(Context context, String keystoreAlias, byte[] publicKey) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
if(isAvailableInKeystore(keystoreAlias)) {
ConversationsThreadsEncryption conversationsThreadsEncryption =
fetchStoredPeerData(context, keystoreAlias);
if(conversationsThreadsEncryption == null) {
return AGREEMENT_KEY;
}
if(conversationsThreadsEncryption.getPublicKey().equals(
Base64.encodeToString(publicKey, Base64.NO_WRAP))) {
return IGNORE_KEY;
}
}
return REQUEST_KEY;
}
public static void clear(Context context, String keystoreAlias) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, InterruptedException {
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(),
Datastore.class, Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
removeFromKeystore(context, keystoreAlias);
removeFromKeystore(context, getKeystoreForRatchets(keystoreAlias));
ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao =
Datastore.datastore.conversationsThreadsEncryptionDao();
conversationsThreadsEncryptionDao.delete(keystoreAlias);
conversationsThreadsEncryptionDao.delete(getKeystoreForRatchets(keystoreAlias));
}
}
| 23,340 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
E2EECompactActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/E2EECompactActivity.java | package com.afkanerd.deku.E2EE;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Base64;
import android.util.Pair;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.afkanerd.deku.DefaultSMS.CustomAppCompactActivity;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.DefaultSMS.R;
import com.google.android.material.textfield.TextInputLayout;
import com.google.i18n.phonenumbers.NumberParseException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
public class E2EECompactActivity extends CustomAppCompactActivity {
protected ThreadedConversations threadedConversations;
View securePopUpRequest;
protected String keystoreAlias;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
boolean isEncrypted = false;
/**
*
* @param text
* @param subscriptionId
* @param threadedConversations
* @param messageId
* @param _mk
* @throws NumberParseException
* @throws InterruptedException
*/
@Override
public void sendTextMessage(final String text, int subscriptionId,
ThreadedConversations threadedConversations, String messageId,
final byte[] _mk) throws NumberParseException, InterruptedException {
if(threadedConversations.is_secured && !isEncrypted) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
byte[][] cipherText = E2EEHandler.encrypt(getApplicationContext(),
keystoreAlias, text.getBytes(StandardCharsets.UTF_8));
String text = E2EEHandler.buildTransmissionText(cipherText[0]);
isEncrypted = true;
sendTextMessage(text, subscriptionId, threadedConversations, messageId,
cipherText[1]);
} catch (Throwable e) {
e.printStackTrace();
}
}
});
}
else {
isEncrypted = false;
super.sendTextMessage(text, subscriptionId, threadedConversations, messageId, _mk);
}
}
@Override
public void informSecured(boolean secured) {
runOnUiThread(new Runnable() {
@Override
public void run() {
threadedConversations.is_secured = secured;
if(secured && securePopUpRequest != null) {
securePopUpRequest.setVisibility(View.GONE);
TextInputLayout layout = findViewById(R.id.conversations_send_text_layout);
layout.setPlaceholderText(getString(R.string.send_message_secured_text_box_hint));
}
}
});
}
protected void sendDataMessage(ThreadedConversations threadedConversations) {
final int subscriptionId = SIMHandler.getDefaultSimSubscription(getApplicationContext());
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
Pair<String, byte[]> transmissionRequestKeyPair =
E2EEHandler.buildForEncryptionRequest(getApplicationContext(),
threadedConversations.getAddress());
final String messageId = String.valueOf(System.currentTimeMillis());
Conversation conversation = new Conversation();
conversation.setThread_id(threadedConversations.getThread_id());
conversation.setAddress(threadedConversations.getAddress());
conversation.setIs_key(true);
conversation.setMessage_id(messageId);
conversation.setData(Base64.encodeToString(transmissionRequestKeyPair.second,
Base64.DEFAULT));
conversation.setSubscription_id(subscriptionId);
conversation.setType(Telephony.Sms.MESSAGE_TYPE_OUTBOX);
conversation.setDate(String.valueOf(System.currentTimeMillis()));
conversation.setStatus(Telephony.Sms.STATUS_PENDING);
long id = conversationsViewModel.insert(getApplicationContext(), conversation);
SMSDatabaseWrapper.send_data(getApplicationContext(), conversation);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void showSecureRequestPopUpMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.conversation_secure_popup_request_menu_title));
View conversationSecurePopView = View.inflate(getApplicationContext(),
R.layout.conversation_secure_popup_menu, null);
builder.setView(conversationSecurePopView);
Button yesButton = conversationSecurePopView.findViewById(R.id.conversation_secure_popup_menu_send);
Button cancelButton = conversationSecurePopView.findViewById(R.id.conversation_secure_popup_menu_cancel);
TextView descriptionText = conversationSecurePopView.findViewById(R.id.conversation_secure_popup_menu_text_description);
String descriptionTextRevised = descriptionText.getText()
.toString()
.replaceAll("\\[contact name]", threadedConversations.getContact_name() == null ?
threadedConversations.getAddress() : threadedConversations.getContact_name());
descriptionText.setText(descriptionTextRevised);
AlertDialog dialog = builder.create();
yesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendDataMessage(threadedConversations);
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void setSecurePopUpRequest() {
securePopUpRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSecureRequestPopUpMenu();
}
});
}
public void setEncryptionThreadedConversations(ThreadedConversations threadedConversations) {
this.threadedConversations = threadedConversations;
}
@Override
protected void onStart() {
super.onStart();
securePopUpRequest = findViewById(R.id.conversations_request_secure_pop_layout);
setSecurePopUpRequest();
// if(!SettingsHandler.alertNotEncryptedCommunicationDisabled(getApplicationContext()))
// securePopUpRequest.setVisibility(View.VISIBLE);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (R.id.conversation_main_menu_encrypt_lock == item.getItemId()) {
if(securePopUpRequest != null) {
securePopUpRequest.setVisibility(securePopUpRequest.getVisibility() == View.VISIBLE ?
View.GONE : View.VISIBLE);
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if(threadedConversations != null) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
keystoreAlias = E2EEHandler.deriveKeystoreAlias(threadedConversations.getAddress(), 0);
threadedConversations.is_secured =
E2EEHandler.canCommunicateSecurely(getApplicationContext(), keystoreAlias);
if(threadedConversations.is_secured) {
runOnUiThread(new Runnable() {
@Override
public void run() {
TextInputLayout layout = findViewById(R.id.conversations_send_text_layout);
layout.setPlaceholderText(getString(R.string.send_message_secured_text_box_hint));
}
});
}
} catch (IOException | GeneralSecurityException | NumberParseException e) {
e.printStackTrace();
}
}
});
}
}
}
| 9,467 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
EndToEndFragments.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/EndToEndFragments.java | package com.afkanerd.deku.E2EE;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.preference.PreferenceFragmentCompat;
import com.afkanerd.deku.DefaultSMS.R;
public class EndToEndFragments extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
setPreferencesFromResource(R.xml.communication_encryption_preferences, rootKey);
}
}
| 469 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
CustomKeyStore.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/Security/CustomKeyStore.java | package com.afkanerd.deku.E2EE.Security;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityECDH;
import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityRSA;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
@Entity(indices = {@Index(value={"keystoreAlias"}, unique=true)})
public class CustomKeyStore {
@PrimaryKey(autoGenerate = true)
private long id;
private long date;
private String keystoreAlias;
private String publicKey;
private String privateKey;
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getKeystoreAlias() {
return keystoreAlias;
}
public void setKeystoreAlias(String keystoreAlias) {
this.keystoreAlias = keystoreAlias;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
public String getPrivateKey() {
return this.privateKey;
}
public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
}
public PrivateKey buildPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException,
UnrecoverableKeyException, CertificateException, KeyStoreException, IOException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
PrivateKey keystorePrivateKey = SecurityECDH.getPrivateKeyFromKeystore(this.keystoreAlias);
byte[] decodedPrivateKey = Base64.decode(this.privateKey, Base64.NO_WRAP);
byte[] privateKey = SecurityRSA.decrypt(keystorePrivateKey, decodedPrivateKey);
return SecurityECDH.buildPrivateKey(privateKey);
}
public KeyPair getKeyPair() throws UnrecoverableKeyException, CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
PrivateKey keystorePrivateKey = SecurityECDH.getPrivateKeyFromKeystore(this.keystoreAlias);
byte[] decodedPrivateKey = Base64.decode(this.privateKey, Base64.NO_WRAP);
byte[] privateKey = SecurityRSA.decrypt(keystorePrivateKey, decodedPrivateKey);
PublicKey x509PublicKey = SecurityECDH.buildPublicKey(Base64.decode(publicKey, Base64.NO_WRAP));
PrivateKey x509PrivateKey = SecurityECDH.buildPrivateKey(privateKey);
// return CryptoHelpers.buildKeyPair(x509PublicKey, x509PrivateKey);
return new KeyPair(x509PublicKey, x509PrivateKey);
}
}
| 3,847 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
CustomKeyStoreDao.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/E2EE/Security/CustomKeyStoreDao.java | package com.afkanerd.deku.E2EE.Security;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface CustomKeyStoreDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(CustomKeyStore customKeyStore);
@Query("SELECT * FROM CustomKeyStore WHERE keystoreAlias = :keystoreAlias LIMIT 1")
CustomKeyStore find(String keystoreAlias);
@Query("DELETE FROM CustomKeyStore WHERE keystoreAlias = :keystoreAlias")
int delete(String keystoreAlias);
@Query("SELECT * FROM CustomKeyStore")
List<CustomKeyStore> getAll();
@Query("DELETE FROM CustomKeyStore")
void clear();
}
| 788 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ThreadedConversationsActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/ThreadedConversationsActivity.java | package com.afkanerd.deku.DefaultSMS;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.ARCHIVED_MESSAGE_TYPES;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.BLOCKED_MESSAGE_TYPES;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.DRAFTS_MESSAGE_TYPES;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.ENCRYPTED_MESSAGES_THREAD_FRAGMENT;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.MUTED_MESSAGE_TYPE;
import static com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment.UNREAD_MESSAGE_TYPES;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.app.NotificationManagerCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.room.Room;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao;
import com.afkanerd.deku.DefaultSMS.Fragments.ThreadedConversationsFragment;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationsViewModel;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientHandler;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
public class ThreadedConversationsActivity extends CustomAppCompactActivity implements ThreadedConversationsFragment.ViewModelsInterface {
public static final String UNIQUE_WORK_MANAGER_NAME = BuildConfig.APPLICATION_ID;
FragmentManager fragmentManager = getSupportFragmentManager();
ActionBar ab;
MaterialToolbar toolbar;
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations_threads);
toolbar = findViewById(R.id.conversation_threads_toolbar);
setSupportActionBar(toolbar);
ab = getSupportActionBar();
threadedConversationsViewModel = new ViewModelProvider(this).get(
ThreadedConversationsViewModel.class);
threadedConversationsViewModel.databaseConnector = databaseConnector;
fragmentManagement();
configureNavigationBar();
}
public void configureNavigationBar() {
navigationView = findViewById(R.id.conversations_threads_navigation_view);
View view = getLayoutInflater().inflate(R.layout.header_navigation_drawer, null);
TextView textView = view.findViewById(R.id.conversations_threads_navigation_view_version_number);
textView.setText(BuildConfig.VERSION_NAME);
navigationView.addHeaderView(view);
MenuItem inboxMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_inbox);
MenuItem draftMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_drafts);
MenuItem encryptedMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_encrypted);
MenuItem unreadMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_unread);
MenuItem blockedMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_blocked);
MenuItem mutedMenuItem = navigationView.getMenu().findItem(R.id.navigation_view_menu_muted);
threadedConversationsViewModel.folderMetrics.observe(this, new Observer<List<Integer>>() {
@Override
public void onChanged(List<Integer> integers) {
// inboxMenuItem.setTitle(getString(R.string.conversations_navigation_view_inbox)
// + "(" + integers.get(0) + ")");
draftMenuItem.setTitle(getString(R.string.conversations_navigation_view_drafts)
+ "(" + integers.get(0) + ")");
encryptedMenuItem.setTitle(getString(R.string.homepage_fragment_tab_encrypted)
+ "(" + integers.get(1) + ")");
unreadMenuItem.setTitle(getString(R.string.conversations_navigation_view_unread)
+ "(" + integers.get(2) + ")");
blockedMenuItem.setTitle(getString(R.string.conversations_navigation_view_blocked)
+ "(" + integers.get(3) + ")");
mutedMenuItem.setTitle(getString(R.string.conversation_menu_muted_label)
+ "(" + integers.get(4) + ")");
}
});
DrawerLayout drawerLayout = findViewById(R.id.conversations_drawer);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.open();
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
String messageType = "";
String label = "";
String noContent = "";
int defaultMenu = -1;
int actionModeMenu = -1;
if(item.getItemId() == R.id.navigation_view_menu_inbox) {
fragmentManagement();
drawerLayout.close();
return true;
} else if(item.getItemId() == R.id.navigation_view_menu_drafts) {
messageType = DRAFTS_MESSAGE_TYPES;
label = getString(R.string.conversations_navigation_view_drafts);
noContent = getString(R.string.homepage_draft_no_message);
defaultMenu = R.menu.drafts_menu;
actionModeMenu = R.menu.conversations_threads_menu_items_selected;
} else if(item.getItemId() == R.id.navigation_view_menu_encrypted) {
messageType = ENCRYPTED_MESSAGES_THREAD_FRAGMENT;
label = getString(R.string.conversations_navigation_view_encryption);
noContent = getString(R.string.homepage_encryption_no_message);
defaultMenu = R.menu.conversations_threads_menu;
actionModeMenu = R.menu.conversations_threads_menu_items_selected;
}
else if(item.getItemId() == R.id.navigation_view_menu_unread) {
messageType = UNREAD_MESSAGE_TYPES;
label = getString(R.string.conversations_navigation_view_unread);
noContent = getString(R.string.homepage_unread_no_message);
defaultMenu = R.menu.read_menu;
actionModeMenu = R.menu.conversations_threads_menu_items_selected;
}
else if(item.getItemId() == R.id.navigation_view_menu_archive) {
messageType = ARCHIVED_MESSAGE_TYPES;
label = getString(R.string.conversations_navigation_view_archived);
noContent = getString(R.string.homepage_archive_no_message);
defaultMenu = R.menu.archive_menu;
actionModeMenu = R.menu.archive_menu_items_selected;
}
else if(item.getItemId() == R.id.navigation_view_menu_blocked) {
messageType = BLOCKED_MESSAGE_TYPES;
label = getString(R.string.conversation_menu_block);
noContent = getString(R.string.homepage_blocked_no_message);
defaultMenu = R.menu.blocked_conversations;
actionModeMenu = R.menu.blocked_conversations_items_selected;
}
else if(item.getItemId() == R.id.navigation_view_menu_muted) {
messageType = MUTED_MESSAGE_TYPE;
label = getString(R.string.conversation_menu_muted_label);
noContent = getString(R.string.homepage_muted_no_muted);
defaultMenu = R.menu.muted_menu;
actionModeMenu = R.menu.muted_menu_items_selected;
}
else return false;
Bundle bundle = new Bundle();
bundle.putString(ThreadedConversationsFragment.MESSAGES_THREAD_FRAGMENT_TYPE,
messageType);
bundle.putString(ThreadedConversationsFragment.MESSAGES_THREAD_FRAGMENT_LABEL, label);
bundle.putString(ThreadedConversationsFragment.MESSAGES_THREAD_FRAGMENT_NO_CONTENT,
noContent);
bundle.putInt(ThreadedConversationsFragment.MESSAGES_THREAD_FRAGMENT_DEFAULT_MENU,
defaultMenu);
bundle.putInt(ThreadedConversationsFragment.MESSAGES_THREAD_FRAGMENT_DEFAULT_ACTION_MODE_MENU,
actionModeMenu);
fragmentManager.beginTransaction().replace(R.id.view_fragment,
ThreadedConversationsFragment.class, bundle, null)
.setReorderingAllowed(true)
.commit();
drawerLayout.close();
return true;
}
});
}
private void fragmentManagement() {
fragmentManager.beginTransaction().replace(R.id.view_fragment,
ThreadedConversationsFragment.class, null, "HOMEPAGE_TAG")
.setReorderingAllowed(true)
.commit();
}
private void cancelAllNotifications() {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.cancelAll();
}
public void onNewMessageClick(View view) {
Intent intent = new Intent(this, ComposeNewMessageActivity.class);
startActivity(intent);
}
@Override
protected void onResume() {
super.onResume();
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.getCount(getApplicationContext());
}
});
}
@Override
public ThreadedConversationsViewModel getThreadedConversationsViewModel() {
return threadedConversationsViewModel;
}
} | 11,215 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
SettingsActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/SettingsActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import com.afkanerd.deku.DefaultSMS.Fragments.SettingsFragment;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar myToolbar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.settings_title));
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings_fragment, new SettingsFragment())
.commit();
}
} | 926 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
SearchMessagesThreadsActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/SearchMessagesThreadsActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.cursoradapter.widget.CursorAdapter;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.SearchConversationRecyclerAdapter;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao;
import com.afkanerd.deku.DefaultSMS.Models.Contacts;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.SearchViewModel;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import java.util.List;
public class SearchMessagesThreadsActivity extends AppCompatActivity {
SearchViewModel searchViewModel;
MutableLiveData<String> searchString = new MutableLiveData<>();
ThreadedConversations threadedConversations = new ThreadedConversations();
Datastore databaseConnector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_messages_threads);
if(Datastore.datastore == null || !Datastore.datastore.isOpen())
Datastore.datastore = Room.databaseBuilder(getApplicationContext(), Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
databaseConnector = Datastore.datastore;
searchViewModel = new ViewModelProvider(this).get(
SearchViewModel.class);
searchViewModel.databaseConnector = Datastore.datastore;
Toolbar myToolbar = (Toolbar) findViewById(R.id.search_messages_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SearchConversationRecyclerAdapter searchConversationRecyclerAdapter =
new SearchConversationRecyclerAdapter();
CustomContactsCursorAdapter customContactsCursorAdapter = new CustomContactsCursorAdapter(getApplicationContext(),
Contacts.filterContacts(getApplicationContext(), ""), 0);
onSearchRequested();
ListView suggestionsListView = findViewById(R.id.search_messages_suggestions_list);
suggestionsListView.setAdapter(customContactsCursorAdapter);
SearchView searchView = findViewById(R.id.search_view_input);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchString.setValue(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 1) {
customContactsCursorAdapter.changeCursor(
Contacts.filterContacts(getApplicationContext(), newText));
} else if(newText.length() < 1) {
searchString.setValue(null);
}
return true;
}
});
RecyclerView messagesThreadRecyclerView = findViewById(R.id.search_results_recycler_view);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
messagesThreadRecyclerView.setLayoutManager(linearLayoutManager);
messagesThreadRecyclerView.setAdapter(searchConversationRecyclerAdapter);
searchString.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
try {
if(s == null || s.isEmpty()) {
searchConversationRecyclerAdapter.searchString = null;
}
else {
searchConversationRecyclerAdapter.searchString = s;
}
searchViewModel.search(getApplicationContext(), s);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
if(getIntent().hasExtra(Conversation.THREAD_ID)) {
searchViewModel.getByThreadId(getIntent().getStringExtra(Conversation.THREAD_ID)).observe(this,
new Observer<Pair<List<ThreadedConversations>,Integer>>() {
@Override
public void onChanged(Pair<List<ThreadedConversations>,Integer> smsList) {
if(searchString.getValue() != null &&
!searchString.getValue().isEmpty() && smsList.first.isEmpty())
findViewById(R.id.search_nothing_found).setVisibility(View.VISIBLE);
else {
findViewById(R.id.search_nothing_found).setVisibility(View.GONE);
}
searchConversationRecyclerAdapter.mDiffer.submitList(smsList.first);
searchConversationRecyclerAdapter.searchIndex = smsList.second;
}
});
}
else {
searchViewModel.get().observe(this,
new Observer<Pair<List<ThreadedConversations>,Integer>>() {
@Override
public void onChanged(Pair<List<ThreadedConversations>,Integer> smsList) {
if (smsList != null && smsList.first.isEmpty())
findViewById(R.id.search_nothing_found).setVisibility(View.VISIBLE);
else {
findViewById(R.id.search_nothing_found).setVisibility(View.GONE);
}
searchConversationRecyclerAdapter.mDiffer.submitList(smsList.first);
searchConversationRecyclerAdapter.searchIndex = smsList.second;
}
});
}
}
public static class CustomContactsCursorAdapter extends CursorAdapter {
public CustomContactsCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// return LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return LayoutInflater.from(context).inflate(R.layout.conversations_threads_layout, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String address = cursor.getString(
cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
TextView textView = view.findViewById(R.id.messages_thread_address_text);
textView.setTextSize(14);
textView.setText(name);
TextView textView2 = view.findViewById(R.id.messages_thread_text);
textView2.setTextSize(12);
textView2.setText(address);
ImageView avatarImage = view.findViewById(R.id.messages_threads_contact_photo);
final int color = Helpers.generateColor(address);
Drawable drawable = context.getDrawable(R.drawable.baseline_account_circle_24);
drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
avatarImage.setImageDrawable(drawable);
view.findViewById(R.id.messages_threads_layout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, ConversationActivity.class);
intent.putExtra(Conversation.ADDRESS, address);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
}
} | 9,015 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
CustomAppCompactActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/CustomAppCompactActivity.java | package com.afkanerd.deku.DefaultSMS;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.room.Room;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ConversationsViewModel;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationsViewModel;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao;
import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.NativeSMSDB;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.E2EE.E2EEHandler;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientHandler;
import com.google.i18n.phonenumbers.NumberParseException;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomAppCompactActivity extends DualSIMConversationActivity {
protected final static String DRAFT_PRESENT_BROADCAST = "DRAFT_PRESENT_BROADCAST";
protected ConversationsViewModel conversationsViewModel;
protected ThreadedConversationsViewModel threadedConversationsViewModel;
public Datastore databaseConnector;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!_checkIsDefaultApp()) {
startActivity(new Intent(this, DefaultCheckActivity.class));
finish();
}
if(Datastore.datastore == null || !Datastore.datastore.isOpen()) {
Log.d(getClass().getName(), "Yes I am closed");
Datastore.datastore = Room.databaseBuilder(getApplicationContext(), Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.build();
}
databaseConnector = Datastore.datastore;
}
private boolean _checkIsDefaultApp() {
final String myPackageName = getPackageName();
final String defaultPackage = Telephony.Sms.getDefaultSmsPackage(this);
return myPackageName.equals(defaultPackage);
}
protected void informSecured(boolean secured) { }
private void cancelAllNotifications(int id) {
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getApplicationContext());
notificationManager.cancel(id);
}
protected void sendTextMessage(Conversation conversation,
ThreadedConversations threadedConversations, String messageId) throws NumberParseException, InterruptedException {
sendTextMessage(conversation.getText(),
conversation.getSubscription_id(),
threadedConversations, messageId, null);
}
protected void sendTextMessage(final String text, int subscriptionId,
ThreadedConversations threadedConversations, String messageId,
byte[] _mk) throws NumberParseException, InterruptedException {
if(text != null) {
if(messageId == null)
messageId = String.valueOf(System.currentTimeMillis());
final String messageIdFinal = messageId;
Conversation conversation = new Conversation();
conversation.setMessage_id(messageId);
conversation.setText(text);
conversation.setThread_id(threadedConversations.getThread_id());
conversation.setSubscription_id(subscriptionId);
conversation.setType(Telephony.Sms.MESSAGE_TYPE_OUTBOX);
conversation.setDate(String.valueOf(System.currentTimeMillis()));
conversation.setAddress(threadedConversations.getAddress());
conversation.setStatus(Telephony.Sms.STATUS_PENDING);
// TODO: should encrypt this before storing
if(_mk != null)
conversation.set_mk(Base64.encodeToString(_mk, Base64.NO_WRAP));
if(conversationsViewModel != null) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
conversationsViewModel.insert(getApplicationContext(), conversation);
SMSDatabaseWrapper.send_text(getApplicationContext(), conversation, null);
// conversationsViewModel.updateThreadId(conversation.getThread_id(),
// _messageId, id);
} catch (Exception e) {
e.printStackTrace();
NativeSMSDB.Outgoing.register_failed(getApplicationContext(), messageIdFinal, 1);
conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_FAILED);
conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED);
conversation.setError_code(1);
conversationsViewModel.update(conversation);
}
}
});
}
}
}
protected void saveDraft(final String messageId, final String text, ThreadedConversations threadedConversations) throws InterruptedException {
if(text != null) {
if(conversationsViewModel != null) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
Conversation conversation = new Conversation();
conversation.setMessage_id(messageId);
conversation.setThread_id(threadedConversations.getThread_id());
conversation.setText(text);
conversation.setRead(true);
conversation.setType(Telephony.Sms.MESSAGE_TYPE_DRAFT);
conversation.setDate(String.valueOf(System.currentTimeMillis()));
conversation.setAddress(threadedConversations.getAddress());
conversation.setStatus(Telephony.Sms.STATUS_PENDING);
try {
conversationsViewModel.insert(getApplicationContext(), conversation);
ThreadedConversations tc =
ThreadedConversations.build(getApplicationContext(), conversation);
databaseConnector.threadedConversationsDao().insert(tc);
SMSDatabaseWrapper.saveDraft(getApplicationContext(), conversation);
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent(DRAFT_PRESENT_BROADCAST);
sendBroadcast(intent);
}
});
}
}
}
protected void cancelNotifications(String threadId) {
if (!threadId.isEmpty()) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(
getApplicationContext());
notificationManager.cancel(Integer.parseInt(threadId));
}
}
}
| 8,262 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
AboutActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AboutActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.afkanerd.deku.DefaultSMS.BuildConfig;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Toolbar toolbar = findViewById(R.id.about_toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setTitle(getString(R.string.about_deku));
ab.setDisplayHomeAsUpEnabled(true);
setVersion();
setClickListeners();
}
private void setVersion() {
TextView textView = findViewById(R.id.about_version_text);
textView.setText(BuildConfig.VERSION_NAME);
}
private void setClickListeners() {
TextView textView = findViewById(R.id.about_github_link);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = getString(R.string.about_deku_github_url);
Intent shareIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(shareIntent);
}
});
}
} | 1,514 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
DefaultCheckActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/DefaultCheckActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import androidx.room.Room;
import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.role.RoleManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientHandler;
import com.google.android.material.button.MaterialButton;
import java.util.ArrayList;
import java.util.List;
public class DefaultCheckActivity extends AppCompatActivity {
public static final int READ_SMS_PERMISSION_REQUEST_CODE = 1;
public static final int READ_CONTACTS_PERMISSION_REQUEST_CODE = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default_check);
MaterialButton materialButton = findViewById(R.id.default_check_make_default_btn);
materialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makeDefault(v);
}
});
if(checkIsDefaultApp()) {
startUserActivities();
}
}
private boolean checkIsDefaultApp() {
final String myPackageName = getPackageName();
final String defaultPackage = Telephony.Sms.getDefaultSmsPackage(this);
return myPackageName.equals(defaultPackage);
}
// public void quicktest() {
// Intent intent = new Intent(Intent.ACTION_SENDTO);
// intent.setData(Uri.parse("smsto:"));
//
// // Set the recipient phone number
// intent.putExtra("address", "123456789; 1234567890; 12345678901");
// // here i can send message to emulator 5556,5558,5560
// // you can change in real device
// intent.putExtra("sms_body", "Hello friends!");
// startActivity(intent);
// }
public void clickPrivacyPolicy(View view) {
String url = getString(R.string.privacy_policy_url);
Intent shareIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(shareIntent);
}
public void makeDefault(View view) {
Log.d(getLocalClassName(), "Got into make default function..");
final String myPackageName = getApplicationContext().getPackageName();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
RoleManager roleManager = (RoleManager) getSystemService(ROLE_SERVICE);
Intent roleManagerIntent = roleManager.createRequestRoleIntent(RoleManager.ROLE_SMS);
roleManagerIntent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
startActivityForResult(roleManagerIntent, 0);
}
else {
Intent intent =
new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
startActivity(intent);
}
}
private void startServices() {
GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
try {
gatewayClientHandler.startServices(getApplicationContext());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void startMigrations() {
if(Datastore.datastore == null || !Datastore.datastore.isOpen())
Datastore.datastore = Room.databaseBuilder(getApplicationContext(), Datastore.class,
Datastore.databaseName)
.enableMultiInstanceInvalidation()
.addMigrations(new Migrations.Migration4To5())
.addMigrations(new Migrations.Migration5To6())
.addMigrations(new Migrations.Migration6To7())
.addMigrations(new Migrations.Migration7To8())
.addMigrations(new Migrations.Migration9To10())
.addMigrations(new Migrations.Migration10To11(getApplicationContext()))
.addMigrations(new Migrations.MIGRATION_11_12())
.build();
}
private void startUserActivities() {
startMigrations();
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
configureNotifications();
startServices();
}
});
Intent intent = new Intent(this, ThreadedConversationsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void configureNotifications(){
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel();
}
}
ArrayList<String> notificationsChannelIds = new ArrayList<>();
ArrayList<String> notificationsChannelNames = new ArrayList<>();
private void createNotificationChannel() {
notificationsChannelIds.add(getString(R.string.incoming_messages_channel_id));
notificationsChannelNames.add(getString(R.string.incoming_messages_channel_name));
notificationsChannelIds.add(getString(R.string.running_gateway_clients_channel_id));
notificationsChannelNames.add(getString(R.string.running_gateway_clients_channel_name));
notificationsChannelIds.add(getString(R.string.foreground_service_failed_channel_id));
notificationsChannelNames.add(getString(R.string.foreground_service_failed_channel_name));
createNotificationChannelIncomingMessage();
createNotificationChannelRunningGatewayListeners();
createNotificationChannelReconnectGatewayListeners();
}
private void createNotificationChannelIncomingMessage() {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(
notificationsChannelIds.get(0), notificationsChannelNames.get(0), importance);
channel.setDescription(getString(R.string.incoming_messages_channel_description));
channel.enableLights(true);
channel.setLightColor(R.color.logo_primary);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
private void createNotificationChannelRunningGatewayListeners() {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(
notificationsChannelIds.get(1), notificationsChannelNames.get(1), importance);
channel.setDescription(getString(R.string.running_gateway_clients_channel_description));
channel.setLightColor(R.color.logo_primary);
channel.setLockscreenVisibility(Notification.DEFAULT_ALL);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
private void createNotificationChannelReconnectGatewayListeners() {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(
notificationsChannelIds.get(2), notificationsChannelNames.get(2), importance);
channel.setDescription(getString(R.string.running_gateway_clients_channel_description));
channel.setLightColor(R.color.logo_primary);
channel.setLockscreenVisibility(Notification.DEFAULT_ALL);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (reqCode == 0) {
if (resultCode == Activity.RESULT_OK) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit()
.putBoolean(getString(R.string.configs_load_natives), true)
.apply();
startUserActivities();
}
}
}
public boolean checkPermissionToReadContacts() {
int check = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
return (check == PackageManager.PERMISSION_GRANTED);
}
} | 9,753 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
RespondViaMessageActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/RespondViaMessageActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class RespondViaMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Seems this gets called when the user rejects a call, now that's interesting
*/
}
} | 419 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
LinkedDevicesQRActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/LinkedDevicesQRActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.budiyev.android.codescanner.CodeScanner;
import com.budiyev.android.codescanner.CodeScannerView;
import com.budiyev.android.codescanner.DecodeCallback;
import com.google.zxing.Result;
import org.json.JSONObject;
import java.util.List;
public class LinkedDevicesQRActivity extends AppCompatActivity {
private CodeScanner codeScanner;
public final String WEB_LINKED_INCOMING = "incoming";
public final String WEB_LINKED_OUTGOING = "outgoing";
public final String WEB_LINKED_INCOMING_URL = "url";
public final String WEB_LINKED_INCOMING_TAG = "tag";
public final String WEB_LINKED_OUTGOING_URL = "url";
public final String WEB_LINKED_OUTGOING_PORT = "port";
public final String WEB_LINKED_OUTGOING_USERNAME = "username";
public final String WEB_LINKED_OUTGOING_PASSWORD = "password";
public final String WEB_LINKED_OUTGOING_FRIENDLY_NAME = "friendly_name";
public final String WEB_LINKED_OUTGOING_VIRTUAL_HOST = "virtual_host";
public final String WEB_LINKED_OUTGOING_PROJECT_NAME = "project_name";
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
Toolbar myToolbar = (Toolbar) findViewById(R.id.activity_web_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.linked_devices_scan_qr_code_title));
CodeScannerView scannerView = findViewById(R.id.web_qr_scanner_view);
codeScanner = new CodeScanner(this, scannerView);
codeScanner.setAutoFocusEnabled(true);
codeScanner.setDecodeCallback(new DecodeCallback() {
@Override
public void onDecoded(@NonNull final Result result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
// String resultValue = result.getText();
//
// JSONObject jsonObject = new JSONObject(resultValue);
//
// JSONObject incomingObject = jsonObject.getJSONObject(WEB_LINKED_INCOMING);
// JSONObject outgoingObject = jsonObject.getJSONObject(WEB_LINKED_OUTGOING);
//
// String tag = incomingObject.getString(WEB_LINKED_INCOMING_TAG);
// String url = incomingObject.getString(WEB_LINKED_INCOMING_URL);
//
// String rmqUrl = outgoingObject.getString(WEB_LINKED_OUTGOING_URL);
// int rmqPort = outgoingObject.getInt(WEB_LINKED_OUTGOING_PORT);
// String rmqUsername = outgoingObject.getString(WEB_LINKED_OUTGOING_USERNAME);
// String rmqPassword = outgoingObject.getString(WEB_LINKED_OUTGOING_PASSWORD);
// String rmqFriendlyName = outgoingObject.getString(WEB_LINKED_OUTGOING_FRIENDLY_NAME);
// String rmqVirtualHost = outgoingObject.getString(WEB_LINKED_OUTGOING_VIRTUAL_HOST);
// String rmqProjectName = outgoingObject.getString(WEB_LINKED_OUTGOING_PROJECT_NAME);
//
// GatewayServer gatewayServer = new GatewayServer();
// gatewayServer.setTag(tag);
// gatewayServer.setURL(url);
//
// GatewayServerHandler gatewayServerHandler = new GatewayServerHandler(getApplicationContext());
// gatewayServerHandler.add(gatewayServer);
// gatewayServerHandler.close();
//
// Toast.makeText(getApplicationContext(),
// getString(R.string.linked_devices_new_gateway_server_added),
// Toast.LENGTH_SHORT)
// .show();
//
// GatewayClient gatewayClient = new GatewayClient();
// gatewayClient.setHostUrl(rmqUrl);
// gatewayClient.setPort(rmqPort);
// gatewayClient.setUsername(rmqUsername);
// gatewayClient.setPassword(rmqPassword);
// gatewayClient.setFriendlyConnectionName(rmqFriendlyName);
// gatewayClient.setVirtualHost(rmqVirtualHost);
// gatewayClient.setProjectName(rmqProjectName);
//
// List<String> bindings = GatewayClientHandler.getPublisherDetails(getApplicationContext(),
// rmqProjectName);
//
// gatewayClient.setProjectBinding(bindings.get(0));
// if(bindings.size() > 1)
// gatewayClient.setProjectBinding2(bindings.get(1));
//
// GatewayClientHandler gatewayClientHandler = new GatewayClientHandler(getApplicationContext());
// long id = gatewayClientHandler.add(gatewayClient);
// gatewayClientHandler.close();
//
//
//// Intent intent = new Intent(getApplicationContext(), GatewayClientCustomizationActivity.class);
//// intent.putExtra(GatewayClientListingActivity.GATEWAY_CLIENT_ID, id);
// gatewayClient.setId(id);
// GatewayClientHandler.setListening(getApplicationContext(), gatewayClient);
//
// Toast.makeText(getApplicationContext(),
// getString(R.string.linked_devices_new_gateway_client_added),
// Toast.LENGTH_SHORT)
// .show();
// Intent intent = new Intent(getApplicationContext(), ThreadedConversationsActivity.class);
// startActivity(intent);
// finish();
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
});
scannerView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
codeScanner.startPreview();
}
});
}
@Override
protected void onResume() {
super.onResume();
codeScanner.startPreview();
}
@Override
protected void onPause() {
codeScanner.releaseResources();
super.onPause();
}
} | 7,140 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ConversationActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/ConversationActivity.java | package com.afkanerd.deku.DefaultSMS;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BlockedNumberContract;
import android.provider.Telephony;
import android.telecom.TelecomManager;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagingData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.Models.Contacts;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ConversationsRecyclerAdapter;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversationsHandler;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ConversationsViewModel;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ConversationTemplateViewHandler;
import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore;
import com.afkanerd.deku.DefaultSMS.Models.NativeSMSDB;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.E2EE.E2EECompactActivity;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
public class ConversationActivity extends E2EECompactActivity {
public static final String IMAGE_URI = "IMAGE_URI";
public static final String SEARCH_STRING = "SEARCH_STRING";
public static final String SEARCH_INDEX = "SEARCH_INDEX";
public static final int SEND_SMS_PERMISSION_REQUEST_CODE = 1;
ActionMode actionMode;
ConversationsRecyclerAdapter conversationsRecyclerAdapter;
TextInputEditText smsTextView;
MutableLiveData<String> mutableLiveDataComposeMessage = new MutableLiveData<>();
LinearLayoutManager linearLayoutManager;
RecyclerView singleMessagesThreadRecyclerView;
MutableLiveData<List<Integer>> searchPositions = new MutableLiveData<>();
ImageButton backSearchBtn;
ImageButton forwardSearchBtn;
Toolbar toolbar;
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversations);
// test();
toolbar = (Toolbar) findViewById(R.id.conversation_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try {
configureActivityDependencies();
instantiateGlobals();
configureToolbars();
configureRecyclerView();
configureMessagesTextBox();
configureLayoutForMessageType();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy.
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance.
smsTextView.setText(savedInstanceState.getString(DRAFT_TEXT));
savedInstanceState.remove(DRAFT_TEXT);
savedInstanceState.remove(DRAFT_ID);
}
private void test() {
if(BuildConfig.DEBUG)
getIntent().putExtra(SEARCH_STRING, "Android");
}
@Override
protected void onResume() {
super.onResume();
TextInputLayout layout = findViewById(R.id.conversations_send_text_layout);
layout.requestFocus();
if(threadedConversations.is_secured)
layout.setPlaceholderText(getString(R.string.send_message_secured_text_box_hint));
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
NativeSMSDB.Incoming.update_read(getApplicationContext(), 1,
threadedConversations.getThread_id(), null);
conversationsViewModel.updateToRead(getApplicationContext());
threadedConversations.setIs_read(true);
databaseConnector.threadedConversationsDao().update(threadedConversations);
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
try {
getMenuInflater().inflate(R.menu.conversations_menu, menu);
if (isShortCode) {
menu.findItem(R.id.conversation_main_menu_call).setVisible(false);
menu.findItem(R.id.conversation_main_menu_encrypt_lock).setVisible(false);
}
} catch (Exception e) {
e.printStackTrace();
}
if(threadedConversations.isIs_mute()) {
menu.findItem(R.id.conversations_menu_unmute).setVisible(true);
menu.findItem(R.id.conversations_menu_mute).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
private void resetSearch() {
findViewById(R.id.conversations_search_results_found).setVisibility(View.GONE);
conversationsRecyclerAdapter.searchString = null;
conversationsRecyclerAdapter.resetSearchItems(searchPositions.getValue());
searchPositions = new MutableLiveData<>();
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (R.id.conversation_main_menu_call == item.getItemId()) {
ThreadedConversationsHandler.call(getApplicationContext(), threadedConversations);
return true;
}
else if(R.id.conversation_main_menu_search == item.getItemId()) {
Intent intent = new Intent(getApplicationContext(), SearchMessagesThreadsActivity.class);
intent.putExtra(Conversation.THREAD_ID, threadedConversations.getThread_id());
startActivity(intent);
}
else if (R.id.conversations_menu_block == item.getItemId()) {
blockContact();
if(actionMode != null)
actionMode.finish();
return true;
}
else if (R.id.conversations_menu_mute == item.getItemId()) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
conversationsViewModel.mute();
threadedConversations.setIs_mute(true);
invalidateMenu();
runOnUiThread(new Runnable() {
@Override
public void run() {
configureToolbars();
Toast.makeText(getApplicationContext(), getString(R.string.conversation_menu_muted),
Toast.LENGTH_SHORT).show();
if(actionMode != null)
actionMode.finish();
}
});
}
});
return true;
}
else if (R.id.conversations_menu_unmute == item.getItemId()) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
conversationsViewModel.unMute();
threadedConversations.setIs_mute(false);
invalidateMenu();
runOnUiThread(new Runnable() {
@Override
public void run() {
configureToolbars();
Toast.makeText(getApplicationContext(), getString(R.string.conversation_menu_unmuted),
Toast.LENGTH_SHORT).show();
if(actionMode != null)
actionMode.finish();
}
});
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
private void configureActivityDependencies() throws Exception {
/**
* Address = This could come from Shared Intent, Contacts etc
* ThreadID = This comes from Thread screen and notifications
* ThreadID is the intended way of populating the messages
* ==> If not ThreadId do not populate, everything else should take the pleasure of finding
* and sending a threadID to this intent
*/
if(getIntent().getAction() != null && (getIntent().getAction().equals(Intent.ACTION_SENDTO) ||
getIntent().getAction().equals(Intent.ACTION_SEND))) {
String sendToString = getIntent().getDataString();
if (sendToString != null && (sendToString.contains("smsto:") ||
sendToString.contains("sms:"))) {
String defaultRegion = Helpers.getUserCountry(getApplicationContext());
String address = Helpers.getFormatCompleteNumber(sendToString, defaultRegion);
getIntent().putExtra(Conversation.ADDRESS, address);
}
}
if(!getIntent().hasExtra(Conversation.THREAD_ID) &&
!getIntent().hasExtra(Conversation.ADDRESS)) {
throw new Exception("No threadId nor Address supplied for activity");
}
if(getIntent().hasExtra(Conversation.THREAD_ID)) {
ThreadedConversations threadedConversations = new ThreadedConversations();
threadedConversations.setThread_id(getIntent().getStringExtra(Conversation.THREAD_ID));
this.threadedConversations = ThreadedConversationsHandler.get(
databaseConnector.threadedConversationsDao(), threadedConversations);
}
else if(getIntent().hasExtra(Conversation.ADDRESS)) {
ThreadedConversations threadedConversations = new ThreadedConversations();
threadedConversations.setAddress(getIntent().getStringExtra(Conversation.ADDRESS));
this.threadedConversations = ThreadedConversationsHandler.get(getApplicationContext(),
getIntent().getStringExtra(Conversation.ADDRESS));
}
final String defaultUserCountry = Helpers.getUserCountry(getApplicationContext());
final String address = this.threadedConversations.getAddress();
this.threadedConversations.setAddress(
Helpers.getFormatCompleteNumber(address, defaultUserCountry));
String contactName = Contacts.retrieveContactName(getApplicationContext(),
this.threadedConversations.getAddress());
if(contactName == null) {
this.threadedConversations.setContact_name(Helpers.getFormatNationalNumber(address,
defaultUserCountry ));
} else {
this.threadedConversations.setContact_name(contactName);
}
setEncryptionThreadedConversations(this.threadedConversations);
isShortCode = Helpers.isShortCode(this.threadedConversations);
}
int searchPointerPosition;
TextView searchFoundTextView;
private void scrollRecyclerViewSearch(int position) {
if(position == -2){
String text = "0/0 " + getString(R.string.conversations_search_results_found);
searchFoundTextView.setText(text);
return;
}
conversationsRecyclerAdapter.refresh();
if(position != -3)
singleMessagesThreadRecyclerView.scrollToPosition(position);
String text = (searchPointerPosition == -1 ?
0 :
searchPointerPosition + 1) + "/" + searchPositions.getValue().size() + " " + getString(R.string.conversations_search_results_found);
searchFoundTextView.setText(text);
}
private void instantiateGlobals() throws GeneralSecurityException, IOException {
searchFoundTextView = findViewById(R.id.conversations_search_results_found_counter_text);
backSearchBtn = findViewById(R.id.conversation_search_found_back_btn);
forwardSearchBtn = findViewById(R.id.conversation_search_found_forward_btn);
smsTextView = findViewById(R.id.conversation_send_text_input);
singleMessagesThreadRecyclerView = findViewById(R.id.single_messages_thread_recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(false);
linearLayoutManager.setReverseLayout(true);
singleMessagesThreadRecyclerView.setLayoutManager(linearLayoutManager);
conversationsRecyclerAdapter = new ConversationsRecyclerAdapter(threadedConversations);
conversationsViewModel = new ViewModelProvider(this)
.get(ConversationsViewModel.class);
conversationsViewModel.datastore = Datastore.datastore;
backSearchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (searchPointerPosition <= 0)
searchPointerPosition = searchPositions.getValue().size();
scrollRecyclerViewSearch(searchPositions.getValue().get(--searchPointerPosition));
}
});
forwardSearchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (searchPointerPosition >= searchPositions.getValue().size() -1)
searchPointerPosition = -1;
scrollRecyclerViewSearch(searchPositions.getValue().get(++searchPointerPosition));
}
});
searchPositions.observe(this, new Observer<List<Integer>>() {
@Override
public void onChanged(List<Integer> integers) {
if(!integers.isEmpty()) {
searchPointerPosition = 0;
scrollRecyclerViewSearch(
firstScrollInitiated ?
searchPositions.getValue().get(searchPointerPosition):-3);
} else {
conversationsRecyclerAdapter.searchString = null;
scrollRecyclerViewSearch(-2);
}
}
});
}
boolean firstScrollInitiated = false;
LifecycleOwner lifecycleOwner;
Conversation conversation = new Conversation();
private void configureRecyclerView() throws InterruptedException {
singleMessagesThreadRecyclerView.setAdapter(conversationsRecyclerAdapter);
singleMessagesThreadRecyclerView.setItemViewCacheSize(500);
lifecycleOwner = this;
conversationsRecyclerAdapter.addOnPagesUpdatedListener(new Function0<Unit>() {
@Override
public Unit invoke() {
if(conversationsRecyclerAdapter.getItemCount() < 1 &&
getIntent().getAction() != null &&
!getIntent().getAction().equals(Intent.ACTION_SENDTO) &&
!getIntent().getAction().equals(Intent.ACTION_SEND))
finish();
else if(searchPositions != null && searchPositions.getValue() != null
&& !searchPositions.getValue().isEmpty()
&& !firstScrollInitiated) {
singleMessagesThreadRecyclerView.scrollToPosition(
searchPositions.getValue().get(searchPositions.getValue().size() -1));
firstScrollInitiated = true;
}
else if(linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
singleMessagesThreadRecyclerView.scrollToPosition(0);
}
return null;
}
});
if(this.threadedConversations != null) {
if(getIntent().hasExtra(SEARCH_STRING)) {
conversationsViewModel.threadId = threadedConversations.getThread_id();
findViewById(R.id.conversations_search_results_found).setVisibility(View.VISIBLE);
String searching = getIntent().getStringExtra(SEARCH_STRING);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
searchForInput(searching);
}
});
configureSearchBox();
searchPositions.setValue(new ArrayList<>(
Collections.singletonList(
getIntent().getIntExtra(SEARCH_INDEX, 0))));
conversationsViewModel.getSearch(getApplicationContext(),
threadedConversations.getThread_id(), searchPositions.getValue())
.observe(this, new Observer<PagingData<Conversation>>() {
@Override
public void onChanged(PagingData<Conversation> conversationPagingData) {
conversationsRecyclerAdapter.submitData(getLifecycle(),
conversationPagingData);
}
});
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String messageId = intent.getStringExtra(Conversation.ID);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
Conversation conversation = databaseConnector.conversationDao()
.getMessage(messageId);
conversation.setRead(true);
conversationsViewModel.update(conversation);
}
});
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(IncomingTextSMSBroadcastReceiver.SMS_DELIVER_ACTION);
intentFilter.addAction(IncomingDataSMSBroadcastReceiver.DATA_DELIVER_ACTION);
intentFilter.addAction(IncomingTextSMSBroadcastReceiver.SMS_UPDATED_BROADCAST_INTENT);
intentFilter.addAction(IncomingDataSMSBroadcastReceiver.DATA_UPDATED_BROADCAST_INTENT);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S)
registerReceiver(broadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
else
registerReceiver(broadcastReceiver, intentFilter);
}
else if(this.threadedConversations.getThread_id()!= null &&
!this.threadedConversations.getThread_id().isEmpty()) {
conversationsViewModel.get(this.threadedConversations.getThread_id())
.observe(this, new Observer<PagingData<Conversation>>() {
@Override
public void onChanged(PagingData<Conversation> smsList) {
conversationsRecyclerAdapter.submitData(getLifecycle(), smsList);
}
});
}
}
conversationsRecyclerAdapter.retryFailedMessage.observe(this, new Observer<Conversation>() {
@Override
public void onChanged(Conversation conversation) {
List<Conversation> list = new ArrayList<>();
list.add(conversation);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
conversationsViewModel.deleteItems(getApplicationContext(), list);
try {
sendTextMessage(conversation, threadedConversations, conversation.getMessage_id());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
conversationsRecyclerAdapter.retryFailedDataMessage.observe(this, new Observer<Conversation>() {
@Override
public void onChanged(Conversation conversation) {
List<Conversation> list = new ArrayList<>();
list.add(conversation);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
conversationsViewModel.deleteItems(getApplicationContext(), list);
try {
sendDataMessage(threadedConversations);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
conversationsRecyclerAdapter.mutableSelectedItems.observe(this,
new Observer<HashMap<Long, ConversationTemplateViewHandler>>() {
@Override
public void onChanged(HashMap<Long, ConversationTemplateViewHandler> selectedItems) {
if(selectedItems == null || selectedItems.isEmpty()) {
if(actionMode != null) {
actionMode.finish();
}
return;
}
else if(actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
if(selectedItems.size() > 1 && actionMode != null)
actionMode.invalidate();
if(actionMode != null)
actionMode.setTitle(String.valueOf(selectedItems.size()));
}
});
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
private void configureSearchBox() {
// findViewById(R.id.conversations_pop_ups_layouts).setVisibility(View.VISIBLE);
findViewById(R.id.conversations_search_results_found).setVisibility(View.VISIBLE);
actionMode = startSupportActionMode(searchActionModeCallback);
}
private void configureToolbars() {
setTitle(getAbTitle());
if(!isShortCode)
getSupportActionBar().setSubtitle(getAbSubTitle());
}
private String getAbTitle() {
String abTitle = getIntent().getStringExtra(Conversation.ADDRESS);
if(this.threadedConversations == null || this.threadedConversations.getContact_name() == null) {
this.threadedConversations.setContact_name(
Contacts.retrieveContactName(getApplicationContext(), abTitle));
}
return (this.threadedConversations.getContact_name() != null &&
!this.threadedConversations.getContact_name().isEmpty()) ?
this.threadedConversations.getContact_name(): this.threadedConversations.getAddress();
}
private String getAbSubTitle() {
// return this.threadedConversations != null &&
// this.threadedConversations.getAddress() != null ?
// this.threadedConversations.getAddress(): "";
if(threadedConversations.isIs_mute())
return getString(R.string.conversation_menu_mute);
return "";
}
boolean isShortCode = false;
@Override
protected void onPause() {
super.onPause();
if (smsTextView.getText() != null && !smsTextView.getText().toString().isEmpty()) {
try {
saveDraft(String.valueOf(System.currentTimeMillis()),
smsTextView.getText().toString(), threadedConversations);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null)
unregisterReceiver(broadcastReceiver);
}
static final String DRAFT_TEXT = "DRAFT_TEXT";
static final String DRAFT_ID = "DRAFT_ID";
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state.
savedInstanceState.putString(DRAFT_TEXT, smsTextView.getText().toString());
savedInstanceState.putString(DRAFT_ID, String.valueOf(System.currentTimeMillis()));
// Always call the superclass so it can save the view hierarchy state.
super.onSaveInstanceState(savedInstanceState);
}
private void emptyDraft(){
conversationsViewModel.clearDraft(getApplicationContext());
}
SmsManager smsManager = SmsManager.getDefault();
public String getSMSCount(String text) {
final List<String> messages = smsManager.divideMessage(text);
final int segmentCount = messages.get(messages.size() -1).length();
return segmentCount +"/"+messages.size();
}
private void configureMessagesTextBox() {
if (mutableLiveDataComposeMessage.getValue() == null ||
mutableLiveDataComposeMessage.getValue().isEmpty())
findViewById(R.id.conversation_send_btn).setVisibility(View.INVISIBLE);
TextView counterView = findViewById(R.id.conversation_compose_text_counter);
View sendBtn = findViewById(R.id.conversation_send_btn);
mutableLiveDataComposeMessage.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
int visibility = View.GONE;
if(!s.isEmpty()) {
counterView.setText(getSMSCount(s));
visibility = View.VISIBLE;
}
TextView dualSimCardName =
(TextView) findViewById(R.id.conversation_compose_dual_sim_send_sim_name);
if(SIMHandler.isDualSim(getApplicationContext())) {
dualSimCardName.setVisibility(View.VISIBLE);
}
sendBtn.setVisibility(visibility);
counterView.setVisibility(visibility);
}
});
smsTextView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
view.getParent().requestDisallowInterceptTouchEvent(true);
if ((motionEvent.getAction() & MotionEvent.ACTION_UP) != 0 &&
(motionEvent.getActionMasked() & MotionEvent.ACTION_UP) != 0) {
view.getParent().requestDisallowInterceptTouchEvent(false);
}
return false;
}
});
findViewById(R.id.conversation_send_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if(smsTextView.getText() != null && defaultSubscriptionId.getValue() != null) {
final String text = smsTextView.getText().toString();
sendTextMessage(text, defaultSubscriptionId.getValue(),
threadedConversations, String.valueOf(System.currentTimeMillis()),
null);
smsTextView.setText(null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
smsTextView.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
mutableLiveDataComposeMessage.setValue(s.toString());
}
});
// Message has been shared from another app to send by SMS
if (getIntent().hasExtra(Conversation.SHARED_SMS_BODY)) {
smsTextView.setText(getIntent().getStringExtra(Conversation.SHARED_SMS_BODY));
getIntent().removeExtra(Conversation.SHARED_SMS_BODY);
}
try {
checkDrafts();
} catch(Exception e) {
e.printStackTrace();
}
}
private void checkDrafts() throws InterruptedException {
if(smsTextView.getText() == null || smsTextView.getText().toString().isEmpty())
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
Conversation conversation =
conversationsViewModel.fetchDraft();
if (conversation != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
smsTextView.setText(conversation.getText());
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
emptyDraft();
}
}
});
}
private void configureLayoutForMessageType() {
if(isShortCode) {
// Cannot reply to message
ConstraintLayout smsLayout = findViewById(R.id.compose_message_include_layout);
smsLayout.setVisibility(View.INVISIBLE);
Snackbar shortCodeSnackBar = Snackbar.make(findViewById(R.id.conversation_coordinator_layout),
getString(R.string.conversation_shortcode_description), Snackbar.LENGTH_INDEFINITE);
// AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), R.style.Theme_main);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.conversation_shortcode_learn_more_text))
.setNegativeButton(getString(R.string.conversation_shortcode_learn_more_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
};
shortCodeSnackBar.setAction(getString(R.string.conversation_shortcode_action_button),
onClickListener);
shortCodeSnackBar.show();
}
}
private void blockContact() {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversations.setIs_blocked(true);
databaseConnector.threadedConversationsDao().update(threadedConversations);
}
});
ContentValues contentValues = new ContentValues();
contentValues.put(BlockedNumberContract.BlockedNumbers.COLUMN_ORIGINAL_NUMBER,
threadedConversations.getAddress());
Uri uri = getContentResolver().insert(BlockedNumberContract.BlockedNumbers.CONTENT_URI,
contentValues);
Toast.makeText(getApplicationContext(), getString(R.string.conversations_menu_block_toast),
Toast.LENGTH_SHORT).show();
TelecomManager telecomManager = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
startActivity(telecomManager.createManageBlockedNumbersIntent(), null);
}
private void shareItem() {
Set<Map.Entry<Long, ConversationTemplateViewHandler>> entry =
conversationsRecyclerAdapter.mutableSelectedItems.getValue().entrySet();
String text = entry.iterator().next().getValue().getText();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
// Only use for components you have control over
ComponentName[] excludedComponentNames = {
new ComponentName(BuildConfig.APPLICATION_ID, ComposeNewMessageActivity.class.getName())
};
shareIntent.putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, excludedComponentNames);
startActivity(shareIntent);
}
private void copyItem() {
Set<Map.Entry<Long, ConversationTemplateViewHandler>> entry =
conversationsRecyclerAdapter.mutableSelectedItems.getValue().entrySet();
String text = entry.iterator().next().getValue().getText();
ClipData clip = ClipData.newPlainText(text, text);
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), getString(R.string.conversation_copied),
Toast.LENGTH_SHORT).show();
}
private void deleteItems() throws Exception {
List<Conversation> conversationList = new ArrayList<>();
for(ConversationTemplateViewHandler viewHandler :
conversationsRecyclerAdapter.mutableSelectedItems.getValue().values()) {
Conversation conversation = new Conversation();
conversation.setId(viewHandler.getId());
conversation.setMessage_id(viewHandler.getMessage_id());
conversationList.add(conversation);
}
conversationsViewModel.deleteItems(getApplicationContext(), conversationList);
}
private void searchForInput(String search){
conversationsRecyclerAdapter.searchString = search;
try {
searchPositions.postValue(conversationsViewModel.search(search));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void viewDetailsPopUp() throws InterruptedException {
Set<Map.Entry<Long, ConversationTemplateViewHandler>> entry =
conversationsRecyclerAdapter.mutableSelectedItems.getValue().entrySet();
String messageId = entry.iterator().next().getValue().getMessage_id();
StringBuilder detailsBuilder = new StringBuilder();
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(getString(R.string.conversation_menu_view_details_title))
.setMessage(detailsBuilder);
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
Conversation conversation = conversationsViewModel.fetch(messageId);
runOnUiThread(new Runnable() {
@Override
public void run() {
detailsBuilder.append(getString(R.string.conversation_menu_view_details_type))
.append(!conversation.getText().isEmpty() ?
getString(R.string.conversation_menu_view_details_type_text):
getString(R.string.conversation_menu_view_details_type_data))
.append("\n")
.append(conversation.getType() == Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX ?
getString(R.string.conversation_menu_view_details_from) :
getString(R.string.conversation_menu_view_details_to))
.append(conversation.getAddress())
.append("\n")
.append(getString(R.string.conversation_menu_view_details_sent))
.append(conversation.getType() == Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX ?
Helpers.formatLongDate(Long.parseLong(conversation.getDate_sent())) :
Helpers.formatLongDate(Long.parseLong(conversation.getDate())));
if(conversation.getType() == Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX ) {
detailsBuilder.append("\n")
.append(getString(R.string.conversation_menu_view_details_received))
.append(Helpers.formatLongDate(Long.parseLong(conversation.getDate())));
}
AlertDialog dialog = builder.create();
dialog.show();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == SEND_SMS_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0) {
Toast.makeText(this, "Let's do this!!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission denied!", Toast.LENGTH_LONG).show();
}
}
}
TextInputEditText textInputEditText;
private final ActionMode.Callback searchActionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Objects.requireNonNull(getSupportActionBar()).hide();
View viewGroup = getLayoutInflater().inflate(R.layout.conversation_search_bar_layout,
null);
mode.setCustomView(viewGroup);
// MenuInflater inflater = mode.getMenuInflater();
// inflater.inflate(R.menu.conversations_menu_search, menu);
//
// MenuItem searchItem = menu.findItem(R.id.conversations_search_active);
// searchItem.expandActionView();
String searchString = getIntent().getStringExtra(SEARCH_STRING);
getIntent().removeExtra(SEARCH_STRING);
textInputEditText = viewGroup.findViewById(R.id.conversation_search_input);
textInputEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if(editable != null && editable.length() > 1) {
conversationsRecyclerAdapter.searchString = editable.toString();
conversationsRecyclerAdapter.resetSearchItems(searchPositions.getValue());
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
searchForInput(editable.toString());
}
});
}
else {
conversationsRecyclerAdapter.searchString = null;
if(actionMode != null)
actionMode.finish();
}
}
});
textInputEditText.setText(searchString);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
// Called when the user exits the action mode.
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
toolbar.setVisibility(View.VISIBLE);
resetSearch();
}
};
private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Objects.requireNonNull(getSupportActionBar()).hide();
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.conversations_menu_item_selected, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
if(Objects.requireNonNull(conversationsRecyclerAdapter.mutableSelectedItems.getValue()).size() > 1) {
menu.clear();
mode.getMenuInflater().inflate(R.menu.conversations_menu_items_selected, menu);
return true;
}
return false; // Return false if nothing is done.
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (R.id.conversations_menu_copy == id) {
copyItem();
if(actionMode != null)
actionMode.finish();
return true;
}
else if (R.id.conversations_menu_share == id) {
shareItem();
if(actionMode != null)
actionMode.finish();
return true;
}
else if (R.id.conversations_menu_delete == id ||
R.id.conversations_menu_delete_multiple == id) {
try {
deleteItems();
if(actionMode != null)
actionMode.finish();
} catch(Exception e) {
e.printStackTrace();
}
return true;
}
else if (R.id.conversations_menu_view_details == id) {
try {
viewDetailsPopUp();
if(actionMode != null)
actionMode.finish();
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
// Called when the user exits the action mode.
@Override
public void onDestroyActionMode(ActionMode mode) {
Objects.requireNonNull(getSupportActionBar()).show();
actionMode = null;
conversationsRecyclerAdapter.resetAllSelectedItems();
}
};
} | 45,488 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
DualSIMConversationActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/DualSIMConversationActivity.java | package com.afkanerd.deku.DefaultSMS;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.telephony.SubscriptionInfo;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.afkanerd.deku.DefaultSMS.Models.SIMHandler;
import java.util.List;
public class DualSIMConversationActivity extends AppCompatActivity {
protected MutableLiveData<Integer> defaultSubscriptionId = new MutableLiveData<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
ImageButton sendImageButton;
TextView currentSimcardTextView;
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
sendImageButton = findViewById(R.id.conversation_send_btn);
currentSimcardTextView = findViewById(R.id.conversation_compose_dual_sim_send_sim_name);
final boolean dualSim = SIMHandler.isDualSim(getApplicationContext());
defaultSubscriptionId.observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
if(dualSim) {
String subscriptionName = SIMHandler.getSubscriptionName(getApplicationContext(), integer);
currentSimcardTextView.setText(subscriptionName);
}
}
});
if(sendImageButton != null) {
String subscriptionName = SIMHandler.getSubscriptionName(getApplicationContext(),
SIMHandler.getDefaultSimSubscription(getApplicationContext()));
defaultSubscriptionId.setValue(SIMHandler.getDefaultSimSubscription(getApplicationContext()));
if(dualSim) {
currentSimcardTextView.setText(subscriptionName);
sendImageButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showMultiDualSimAlert();
return true;
}
});
}
}
}
private void showMultiDualSimAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.sim_chooser_layout_text));
// builder.setMessage(getString(R.string.messages_thread_delete_confirmation_text));
View simChooserView = View.inflate(getApplicationContext(), R.layout.sim_chooser_layout, null);
builder.setView(simChooserView);
List<SubscriptionInfo> subscriptionInfos = SIMHandler.getSimCardInformation(getApplicationContext());
Bitmap sim1Bitmap = subscriptionInfos.get(0).createIconBitmap(getApplicationContext());
Bitmap sim2Bitmap = subscriptionInfos.get(1).createIconBitmap(getApplicationContext());
ImageView sim1ImageView = simChooserView.findViewById(R.id.sim_layout_simcard_1_img);
TextView sim1TextView = simChooserView.findViewById(R.id.sim_layout_simcard_1_name);
ImageView sim2ImageView = simChooserView.findViewById(R.id.sim_layout_simcard_2_img);
TextView sim2TextView = simChooserView.findViewById(R.id.sim_layout_simcard_2_name);
sim1ImageView.setImageBitmap(sim1Bitmap);
AlertDialog dialog = builder.create();
sim1ImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
defaultSubscriptionId.setValue(subscriptionInfos.get(0).getSubscriptionId());
dialog.dismiss();
}
});
sim1TextView.setText(subscriptionInfos.get(0).getDisplayName());
sim2ImageView.setImageBitmap(sim2Bitmap);
sim2ImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
defaultSubscriptionId.setValue(subscriptionInfos.get(1).getSubscriptionId());
dialog.dismiss();
}
});
sim2TextView.setText(subscriptionInfos.get(1).getDisplayName());
dialog.show();
}
}
| 4,516 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ComposeNewMessageActivity.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/ComposeNewMessageActivity.java | package com.afkanerd.deku.DefaultSMS;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import com.afkanerd.deku.DefaultSMS.Models.Contacts;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ContactsRecyclerAdapter;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ContactsViewModel;
import com.google.android.material.textfield.TextInputEditText;
import com.google.i18n.phonenumbers.NumberParseException;
import java.util.List;
public class ComposeNewMessageActivity extends AppCompatActivity {
ContactsViewModel contactsViewModel;
RecyclerView contactsRecyclerView;
ContactsRecyclerAdapter contactsRecyclerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compose_new_message);
Toolbar myToolbar = findViewById(R.id.compose_new_message_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.compose_new_message_title));
contactsViewModel = new ViewModelProvider(this).get(
ContactsViewModel.class);
contactsRecyclerAdapter = new ContactsRecyclerAdapter( this);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
contactsRecyclerView = findViewById(R.id.compose_new_message_contact_list_recycler_view);
contactsRecyclerView.setLayoutManager(linearLayoutManager);
contactsRecyclerView.setAdapter(contactsRecyclerAdapter);
contactsViewModel.getContacts(getApplicationContext()).observe(this, new Observer<List<Contacts>>() {
@Override
public void onChanged(List<Contacts> contacts) {
contactsRecyclerAdapter.submitList(contacts);
}
});
TextInputEditText textInputEditText = findViewById(R.id.compose_new_message_to);
textInputEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
new Thread(new Runnable() {
@Override
public void run() {
if (s != null && !s.toString().isEmpty()) {
try {
contactsViewModel.filterContact(s.toString());
} catch (NumberParseException e) {
e.printStackTrace();
}
}
else {
try {
contactsViewModel.filterContact("");
} catch (NumberParseException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
_checkSharedContent();
}
private void _checkSharedContent() {
if (Intent.ACTION_SEND.equals(getIntent().getAction()) && getIntent().getType() != null) {
if ("text/plain".equals(getIntent().getType())) {
String sharedSMS = getIntent().getStringExtra(Intent.EXTRA_TEXT);
contactsRecyclerAdapter.setSharedMessage(sharedSMS);
}
}
}
@Override
protected void onResume() {
super.onResume();
findViewById(R.id.compose_new_message_to).requestFocus();
}
}
| 4,220 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
SettingsFragment.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Fragments/SettingsFragment.java | package com.afkanerd.deku.DefaultSMS.Fragments;
import static androidx.core.content.ContextCompat.getSystemService;
import android.app.LocaleManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.os.LocaleListCompat;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.afkanerd.deku.E2EE.EndToEndFragments;
//import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity;
//import com.afkanerd.deku.Router.GatewayServers.GatewayServerListingActivity;
import com.afkanerd.deku.DefaultSMS.R;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity;
import com.afkanerd.deku.Router.GatewayServers.GatewayServerListingActivity;
import java.util.Locale;
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
setPreferencesFromResource(R.xml.settings_preferences, rootKey);
// Preference securityPrivacyPreference = findPreference(getString(R.string.settings_security_end_to_end));
// securityPrivacyPreference.setFragment(EndToEndFragments.class.getCanonicalName());
Preference developersPreferences = findPreference(getString(R.string.settings_advanced_developers_key));
developersPreferences.setFragment(DevelopersFragment.class.getCanonicalName());
ListPreference languagePreference = findPreference(getString(R.string.settings_locale));
languagePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(@NonNull Preference preference, Object newValue) {
String languageLocale = (String) newValue;
// LocaleList currentAppLocales = getContext().getSystemService(LocaleManager.class)
// .getApplicationLocales();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2) {
getContext().getSystemService(LocaleManager.class)
.setApplicationLocales(
new LocaleList(Locale.forLanguageTag(languageLocale)));
}
else {
LocaleListCompat appLocale = LocaleListCompat.forLanguageTags(languageLocale);
AppCompatDelegate.setApplicationLocales(appLocale);
}
return true;
}
});
}
} | 2,793 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
DevelopersFragment.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Fragments/DevelopersFragment.java | package com.afkanerd.deku.DefaultSMS.Fragments;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.afkanerd.deku.DefaultSMS.R;
import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity;
import io.reactivex.rxjava3.annotations.NonNull;
public class DevelopersFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
setPreferencesFromResource(R.xml.developer_preferences, rootKey);
Preference smsListeningSMSWithoutBorders = findPreference("settings_sms_listening_gateway_clients");
smsListeningSMSWithoutBorders.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(@NonNull Preference preference) {
startActivity(new Intent(getContext(), GatewayClientListingActivity.class));
return true;
}
});
}
}
| 1,147 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ThreadedConversationsFragment.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Fragments/ThreadedConversationsFragment.java | package com.afkanerd.deku.DefaultSMS.Fragments;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.BlockedNumberContract;
import android.provider.DocumentsContract;
import android.telecom.TelecomManager;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.paging.PagingData;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.afkanerd.deku.DefaultSMS.AboutActivity;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter;
import com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationsViewModel;
import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao;
import com.afkanerd.deku.DefaultSMS.Models.Archive;
import com.afkanerd.deku.DefaultSMS.Models.Contacts;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ThreadedConversationsTemplateViewHolder;
import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper;
import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor;
import com.afkanerd.deku.DefaultSMS.R;
import com.afkanerd.deku.DefaultSMS.SearchMessagesThreadsActivity;
import com.afkanerd.deku.DefaultSMS.SettingsActivity;
import com.afkanerd.deku.DefaultSMS.ThreadedConversationsActivity;
import com.afkanerd.deku.E2EE.E2EEHandler;
import com.afkanerd.deku.Router.Router.RouterActivity;
import com.google.i18n.phonenumbers.NumberParseException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
public class ThreadedConversationsFragment extends Fragment {
ThreadedConversationsViewModel threadedConversationsViewModel;
ThreadedConversationRecyclerAdapter threadedConversationRecyclerAdapter;
RecyclerView messagesThreadRecyclerView;
public static final String MESSAGES_THREAD_FRAGMENT_DEFAULT_MENU =
"MESSAGES_THREAD_FRAGMENT_DEFAULT_MENU";
public static final String MESSAGES_THREAD_FRAGMENT_DEFAULT_ACTION_MODE_MENU =
"MESSAGES_THREAD_FRAGMENT_DEFAULT_ACTION_MODE_MENU";
public static final String MESSAGES_THREAD_FRAGMENT_LABEL =
"MESSAGES_THREAD_FRAGMENT_LABEL";
public static final String MESSAGES_THREAD_FRAGMENT_NO_CONTENT =
"MESSAGES_THREAD_FRAGMENT_NO_CONTENT";
public static final String MESSAGES_THREAD_FRAGMENT_TYPE = "MESSAGES_THREAD_FRAGMENT_TYPE";
public static final String ALL_MESSAGES_THREAD_FRAGMENT = "ALL_MESSAGES_THREAD_FRAGMENT";
public static final String PLAIN_MESSAGES_THREAD_FRAGMENT = "PLAIN_MESSAGES_THREAD_FRAGMENT";
public static final String ENCRYPTED_MESSAGES_THREAD_FRAGMENT = "ENCRYPTED_MESSAGES_THREAD_FRAGMENT";
public static final String ARCHIVED_MESSAGE_TYPES = "ARCHIVED_MESSAGE_TYPES";
public static final String BLOCKED_MESSAGE_TYPES = "BLOCKED_MESSAGE_TYPES";
public static final String MUTED_MESSAGE_TYPE = "MUTED_MESSAGE_TYPE";
public static final String DRAFTS_MESSAGE_TYPES = "DRAFTS_MESSAGE_TYPES";
public static final String UNREAD_MESSAGE_TYPES = "UNREAD_MESSAGE_TYPES";
public static final String AUTOMATED_MESSAGES_THREAD_FRAGMENT = "AUTOMATED_MESSAGES_THREAD_FRAGMENT";
ActionBar actionBar;
public interface ViewModelsInterface {
ThreadedConversationsViewModel getThreadedConversationsViewModel();
}
private ViewModelsInterface viewModelsInterface;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_conversations_threads, container, false);
}
public void setLabels(View view, String label, String noContent) {
((TextView) view.findViewById(R.id.conversation_threads_fragment_label))
.setText(label);
((TextView) view.findViewById(R.id.homepage_no_message))
.setText(noContent);
}
ActionMode actionMode;
protected int defaultMenu = R.menu.conversations_threads_menu;
protected int actionModeMenu = R.menu.conversations_threads_menu_items_selected;
private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
actionBar.hide();
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(actionModeMenu, menu);
List<String> threadsIds = new ArrayList<>();
for(ThreadedConversationsTemplateViewHolder
threadedConversationsTemplateViewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values())
threadsIds.add(threadedConversationsTemplateViewHolder.id);
if(menu.findItem(R.id.conversations_threads_main_menu_mark_all_read) != null &&
menu.findItem(R.id.conversations_threads_main_menu_mark_all_unread) != null)
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
boolean hasUnread = threadedConversationsViewModel.hasUnread(threadsIds);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(hasUnread) {
menu.findItem(R.id.conversations_threads_main_menu_mark_all_read).setVisible(true);
menu.findItem(R.id.conversations_threads_main_menu_mark_all_unread).setVisible(false);
}
else {
menu.findItem(R.id.conversations_threads_main_menu_mark_all_read).setVisible(false);
menu.findItem(R.id.conversations_threads_main_menu_mark_all_unread).setVisible(true);
}
}
});
}
});
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done.
}
public Runnable getDeleteRunnable(List<String> ids) {
return new Runnable() {
@Override
public void run() {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
List<String> foundList = threadedConversationsViewModel.
databaseConnector.threadedConversationsDao().findAddresses(ids);
threadedConversationsViewModel.delete(getContext(), ids);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
threadedConversationRecyclerAdapter.resetAllSelectedItems();
}
});
for(String address : foundList) {
try {
String keystoreAlias =
E2EEHandler.deriveKeystoreAlias( address, 0);
E2EEHandler.clear(getContext(), keystoreAlias);
} catch (KeyStoreException | NumberParseException |
InterruptedException |
NoSuchAlgorithmException | IOException |
CertificateException e) {
e.printStackTrace();
}
}
}
});
}
};
}
private void showAlert(Runnable runnable) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getString(R.string.messages_thread_delete_confirmation_title));
builder.setMessage(getString(R.string.messages_thread_delete_confirmation_text));
builder.setPositiveButton(getString(R.string.messages_thread_delete_confirmation_yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
runnable.run();
}
});
builder.setNegativeButton(getString(R.string.messages_thread_delete_confirmation_cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if(threadedConversationRecyclerAdapter != null) {
if(item.getItemId() == R.id.conversations_threads_main_menu_delete ||
item.getItemId() == R.id.archive_delete) {
if(threadedConversationRecyclerAdapter.selectedItems != null &&
threadedConversationRecyclerAdapter.selectedItems.getValue() != null) {
List<String> ids = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
ids.add(viewHolder.id);
}
showAlert(getDeleteRunnable(ids));
}
return true;
}
else if(item.getItemId() == R.id.conversations_threads_main_menu_archive) {
List<Archive> archiveList = new ArrayList<>();
if(threadedConversationRecyclerAdapter.selectedItems != null &&
threadedConversationRecyclerAdapter.selectedItems.getValue() != null)
for(ThreadedConversationsTemplateViewHolder templateViewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
Archive archive = new Archive();
archive.thread_id = templateViewHolder.id;
archive.is_archived = true;
archiveList.add(archive);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.archive(archiveList);
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
else if(item.getItemId() == R.id.archive_unarchive) {
List<Archive> archiveList = new ArrayList<>();
if(threadedConversationRecyclerAdapter.selectedItems != null &&
threadedConversationRecyclerAdapter.selectedItems.getValue() != null)
for(ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
Archive archive = new Archive();
archive.thread_id = viewHolder.id;
archive.is_archived = false;
archiveList.add(archive);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.unarchive(archiveList);
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
else if(item.getItemId() == R.id.conversations_threads_main_menu_mark_all_unread) {
if(threadedConversationRecyclerAdapter.selectedItems != null &&
threadedConversationRecyclerAdapter.selectedItems.getValue() != null) {
List<String> threadIds = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
threadIds.add(viewHolder.id);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.markUnRead(getContext(), threadIds);
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
}
else if(item.getItemId() == R.id.conversations_threads_main_menu_mark_all_read) {
if(threadedConversationRecyclerAdapter.selectedItems != null &&
threadedConversationRecyclerAdapter.selectedItems.getValue() != null) {
List<String> threadIds = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
threadIds.add(viewHolder.id);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.markRead(getContext(), threadIds);
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
}
else if(item.getItemId() == R.id.blocked_main_menu_unblock) {
List<String> threadIds = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
threadIds.add(viewHolder.id);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.unblock(getContext(), threadIds);
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
else if(item.getItemId() == R.id.conversations_threads_main_menu_mute) {
List<String> threadIds = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
threadIds.add(viewHolder.id);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.mute(threadIds);
threadedConversationsViewModel.getCount(getContext());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
threadedConversationRecyclerAdapter.notifyDataSetChanged();
}
});
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
else if(item.getItemId() == R.id.conversation_threads_main_menu_unmute_selected) {
List<String> threadIds = new ArrayList<>();
for (ThreadedConversationsTemplateViewHolder viewHolder :
threadedConversationRecyclerAdapter.selectedItems.getValue().values()) {
threadIds.add(viewHolder.id);
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.unMute(threadIds);
threadedConversationsViewModel.getCount(getContext());
}
});
threadedConversationRecyclerAdapter.resetAllSelectedItems();
return true;
}
}
return false;
}
// Called when the user exits the action mode.
@Override
public void onDestroyActionMode(ActionMode mode) {
actionBar.show();
actionMode = null;
if(threadedConversationRecyclerAdapter != null)
threadedConversationRecyclerAdapter.resetAllSelectedItems();
}
};
@Override
public void onResume() {
super.onResume();
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
if(getContext() != null) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
if(sharedPreferences.getBoolean(getString(R.string.configs_load_natives), true)) {
sharedPreferences.edit().putBoolean(getString(R.string.configs_load_natives), false)
.apply();
threadedConversationsViewModel.reset(getContext());
}
}
}
});
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
viewModelsInterface = (ViewModelsInterface) view.getContext();
setHasOptionsMenu(true);
Bundle args = getArguments();
String messageType;
if(args != null) {
messageType = args.getString(MESSAGES_THREAD_FRAGMENT_TYPE);
setLabels(view, args.getString(MESSAGES_THREAD_FRAGMENT_LABEL),
args.getString(MESSAGES_THREAD_FRAGMENT_NO_CONTENT));
defaultMenu = args.getInt(MESSAGES_THREAD_FRAGMENT_DEFAULT_MENU);
actionModeMenu = args.getInt(MESSAGES_THREAD_FRAGMENT_DEFAULT_ACTION_MODE_MENU);
} else {
messageType = ALL_MESSAGES_THREAD_FRAGMENT;
setLabels(view, getString(R.string.conversations_navigation_view_inbox), getString(R.string.homepage_no_message));
}
actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(),
LinearLayoutManager.VERTICAL, false);
threadedConversationsViewModel = viewModelsInterface.getThreadedConversationsViewModel();
threadedConversationRecyclerAdapter = new ThreadedConversationRecyclerAdapter(
threadedConversationsViewModel.databaseConnector.threadedConversationsDao());
threadedConversationRecyclerAdapter.selectedItems.observe(getViewLifecycleOwner(),
new Observer<HashMap<Long, ThreadedConversationsTemplateViewHolder>>() {
@Override
public void onChanged(HashMap<Long, ThreadedConversationsTemplateViewHolder>
threadedConversationsTemplateViewHolders) {
if(threadedConversationsTemplateViewHolders == null ||
threadedConversationsTemplateViewHolders.isEmpty()) {
if(actionMode != null) {
actionMode.finish();
}
return;
} else if(actionMode == null) {
actionMode = getActivity().startActionMode(actionModeCallback);
}
if(actionMode != null)
actionMode.setTitle(
String.valueOf(threadedConversationsTemplateViewHolders.size()));
}
});
messagesThreadRecyclerView = view.findViewById(R.id.messages_threads_recycler_view);
messagesThreadRecyclerView.setLayoutManager(linearLayoutManager);
messagesThreadRecyclerView.setAdapter(threadedConversationRecyclerAdapter);
// messagesThreadRecyclerView.setItemViewCacheSize(500);
threadedConversationRecyclerAdapter.addOnPagesUpdatedListener(new Function0<Unit>() {
@Override
public Unit invoke() {
if(threadedConversationRecyclerAdapter.getItemCount() < 1)
view.findViewById(R.id.homepage_no_message).setVisibility(View.VISIBLE);
else
view.findViewById(R.id.homepage_no_message).setVisibility(View.GONE);
return null;
}
});
switch(Objects.requireNonNull(messageType)) {
case ENCRYPTED_MESSAGES_THREAD_FRAGMENT:
Log.d(getClass().getName(), "Fragment at encrypted");
try {
threadedConversationsViewModel.getEncrypted().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case UNREAD_MESSAGE_TYPES:
threadedConversationsViewModel.getUnread().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
break;
case ARCHIVED_MESSAGE_TYPES:
threadedConversationsViewModel.getArchived().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
break;
case DRAFTS_MESSAGE_TYPES:
threadedConversationsViewModel.getDrafts().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
break;
case BLOCKED_MESSAGE_TYPES:
threadedConversationsViewModel.getBlocked().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
break;
case MUTED_MESSAGE_TYPE:
threadedConversationsViewModel.getMuted().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
break;
case ALL_MESSAGES_THREAD_FRAGMENT:
default:
threadedConversationsViewModel.get().observe(getViewLifecycleOwner(),
new Observer<PagingData<ThreadedConversations>>() {
@Override
public void onChanged(PagingData<ThreadedConversations> smsList) {
threadedConversationRecyclerAdapter.submitData(getLifecycle(), smsList);
view.findViewById(R.id.homepage_messages_loader).setVisibility(View.GONE);
}
});
}
}
private static final int CREATE_FILE = 777;
public void exportInbox() {
// Request code for creating a PDF document.
String filename = "deku_sms_backup_" + System.currentTimeMillis() + ".json";
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/json");
intent.putExtra(Intent.EXTRA_TITLE, filename);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
// intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, CREATE_FILE);
}
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (requestCode == CREATE_FILE && resultCode == Activity.RESULT_OK) {
// The result data contains a URI for the document or directory that
// the user selected.
if (resultData != null) {
Uri uri = resultData.getData();
// Perform operations on the document using its URI.
if(uri == null)
return;
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
ParcelFileDescriptor pfd = requireActivity().getContentResolver().
openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream =
new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(threadedConversationsViewModel.getAllExport()
.getBytes());
// Let the document provider know you're done by closing the stream.
fileOutputStream.close();
pfd.close();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getContext(),
getString(R.string.conversations_exported_complete),
Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(defaultMenu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.conversation_threads_main_menu_search) {
Intent searchIntent = new Intent(getContext(), SearchMessagesThreadsActivity.class);
searchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(searchIntent);
}
if (item.getItemId() == R.id.conversation_threads_main_menu_routed) {
Intent routingIntent = new Intent(getContext(), RouterActivity.class);
routingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(routingIntent);
}
if (item.getItemId() == R.id.conversation_threads_main_menu_settings) {
Intent settingsIntent = new Intent(getContext(), SettingsActivity.class);
startActivity(settingsIntent);
}
if (item.getItemId() == R.id.conversation_threads_main_menu_about) {
Intent aboutIntent = new Intent(getContext(), AboutActivity.class);
aboutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(aboutIntent);
}
if(item.getItemId() == R.id.conversation_threads_main_menu_clear_drafts) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
try {
threadedConversationsViewModel.clearDrafts(getContext());
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
if(item.getItemId() == R.id.conversation_threads_main_menu_mark_all_read) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.markAllRead(getContext());
}
});
}
else if(item.getItemId() == R.id.conversation_threads_main_menu_unmute_all) {
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.unMuteAll();
}
});
}
else if(item.getItemId() == R.id.conversations_menu_export) {
exportInbox();
}
else if(item.getItemId() == R.id.blocked_main_menu_unblock_manager_id) {
TelecomManager telecomManager = (TelecomManager)
getContext().getSystemService(Context.TELECOM_SERVICE);
startActivity(telecomManager.createManageBlockedNumbersIntent(), null);
return true;
}
ThreadingPoolExecutor.executorService.execute(new Runnable() {
@Override
public void run() {
threadedConversationsViewModel.getCount(getContext());
}
});
return true;
}
}
| 34,259 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
ThreadingPoolExecutor.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/ThreadingPoolExecutor.java | package com.afkanerd.deku.DefaultSMS.Models;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadingPoolExecutor {
public static final ExecutorService executorService = Executors.newFixedThreadPool(4);
}
| 261 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
Contacts.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Contacts.java | package com.afkanerd.deku.DefaultSMS.Models;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.BlockedNumberContract;
import android.provider.ContactsContract;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DiffUtil;
import androidx.room.Ignore;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class Contacts {
@Ignore
public int type;
public long id;
public String number = "";
public String contactName = "";
Context context;
public static final int TYPE_OLD_CONTACT = 1;
public static final int TYPE_NEW_CONTACT = 2;
public Contacts(Context context, long id, String contactName, @NonNull String number){
this.id = id;
this.contactName = contactName;
this.context = context;
this.type = TYPE_OLD_CONTACT;
this.number = number;
}
public Contacts(){ }
public static Cursor filterContacts(Context context, String filter) {
if(filter.isEmpty())
return null;
String[] projection = {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " IS NOT NULL AND " +
ContactsContract.CommonDataKinds.Phone.NUMBER + " <> '' AND (" +
ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + filter + "%' OR " +
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE '%" + filter + "%')";
String[] selectionArgs = null;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
selection,
selectionArgs,
sortOrder
);
}
public static Cursor getPhonebookContacts(Context context) {
String[] projection = {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " IS NOT NULL AND " +
ContactsContract.CommonDataKinds.Phone.NUMBER + " <> ''";
String[] selectionArgs = null;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
return context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
selection,
selectionArgs,
sortOrder
);
}
public static String retrieveContactName(Context context, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(
uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME},
null,
null, null);
if(cursor != null && cursor.moveToFirst()) {
int displayNameIndex = cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME);
String contactName = cursor.getString(displayNameIndex);
cursor.close();
return contactName;
}
return null;
}
public static String retrieveContactPhoto(Context context, String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(
uri,
new String[]{ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI},
null,
null, null);
String contactPhotoThumbUri = "";
if(cursor.moveToFirst()) {
int displayContactPhoto = cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI);
contactPhotoThumbUri = String.valueOf(cursor.getString(displayContactPhoto));
}
return contactPhotoThumbUri;
}
@Override
public boolean equals(@Nullable Object obj) {
if(obj != null) {
Contacts contacts = (Contacts) obj;
return contacts.number.equals(this.number) &&
contacts.contactName.equals(this.contactName);
}
return false;
}
public static final DiffUtil.ItemCallback<Contacts> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Contacts>() {
@Override
public boolean areItemsTheSame(@NonNull Contacts oldItem, @NonNull Contacts newItem) {
return oldItem.number.equals(newItem.number);
}
@Override
public boolean areContentsTheSame(@NonNull Contacts oldItem, @NonNull Contacts newItem) {
return oldItem.equals(newItem);
}
};
public static Bitmap getContactBitmapPhoto(Context context, String phoneNumber) {
// Get the bitmap.
try {
Uri photoUri = Uri.parse(retrieveContactPhoto(context, phoneNumber));
return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(photoUri));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static Cursor getBlocked(Context context) {
return context.getContentResolver().query(BlockedNumberContract.BlockedNumbers.CONTENT_URI,
new String[]{BlockedNumberContract.BlockedNumbers.COLUMN_ID,
BlockedNumberContract.BlockedNumbers.COLUMN_ORIGINAL_NUMBER,
BlockedNumberContract.BlockedNumbers.COLUMN_E164_NUMBER},
null, null, null);
}
}
| 6,407 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
NotificationsHandler.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/NotificationsHandler.java | package com.afkanerd.deku.DefaultSMS.Models;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.service.notification.StatusBarNotification;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.app.Person;
import androidx.core.app.RemoteInput;
import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSReplyActionBroadcastReceiver;
import com.afkanerd.deku.DefaultSMS.Commons.Helpers;
import com.afkanerd.deku.DefaultSMS.ConversationActivity;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation;
import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations;
import com.afkanerd.deku.DefaultSMS.R;
import java.util.ArrayList;
import java.util.List;
public class NotificationsHandler {
public static void sendIncomingTextMessageNotification(Context context, Conversation conversation) {
NotificationCompat.MessagingStyle messagingStyle = getMessagingStyle(context, conversation, null);
Intent replyIntent = getReplyIntent(context, conversation);
PendingIntent pendingIntent = getPendingIntent(context, conversation);
NotificationCompat.Builder builder = getNotificationBuilder(context, replyIntent,
conversation, pendingIntent);
builder.setStyle(messagingStyle);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(Integer.parseInt(conversation.getThread_id()), builder.build());
}
public static PendingIntent getPendingIntent(Context context, Conversation conversation) {
Intent receivedIntent = getReceivedIntent(context, conversation);
return PendingIntent.getActivity(context, Integer.parseInt(conversation.getThread_id()),
receivedIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
}
public static Person getPerson(Context context, Conversation conversation) {
String contactName = Contacts.retrieveContactName(context, conversation.getAddress());
Person.Builder personBuilder = new Person.Builder()
.setName(contactName == null ? conversation.getAddress() : contactName)
.setKey(contactName == null ? conversation.getAddress() : contactName);
return personBuilder.build();
}
public static Intent getReplyIntent(Context context, Conversation conversation) {
if(conversation != null &&
!Helpers.isShortCode(ThreadedConversations.build(context, conversation) )) {
Intent replyBroadcastIntent = new Intent(context, IncomingTextSMSReplyActionBroadcastReceiver.class);
replyBroadcastIntent.putExtra(IncomingTextSMSReplyActionBroadcastReceiver.REPLY_ADDRESS,
conversation.getAddress());
replyBroadcastIntent.putExtra(IncomingTextSMSReplyActionBroadcastReceiver.REPLY_THREAD_ID,
conversation.getThread_id());
replyBroadcastIntent.putExtra(IncomingTextSMSReplyActionBroadcastReceiver.REPLY_SUBSCRIPTION_ID,
conversation.getSubscription_id());
replyBroadcastIntent.setAction(IncomingTextSMSReplyActionBroadcastReceiver.REPLY_BROADCAST_INTENT);
return replyBroadcastIntent;
}
return null;
}
public static Intent getReceivedIntent(Context context, Conversation conversation) {
Intent receivedSmsIntent = new Intent(context, ConversationActivity.class);
receivedSmsIntent.putExtra(Conversation.ADDRESS, conversation.getAddress());
receivedSmsIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id());
receivedSmsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
return receivedSmsIntent;
}
private static class MessageTrackers {
String title;
StringBuilder message = new StringBuilder();
Person person;
}
public static NotificationCompat.MessagingStyle getMessagingStyle(Context context,
Conversation conversation,
String reply) {
Person person = getPerson(context, conversation);
Person.Builder personBuilder = new Person.Builder()
.setName(context.getString(R.string.notification_title_reply_you))
.setKey(context.getString(R.string.notification_title_reply_you));
Person replyPerson = personBuilder.build();
String contactName = Contacts.retrieveContactName(context, conversation.getAddress());
NotificationCompat.MessagingStyle messagingStyle =
new NotificationCompat.MessagingStyle(contactName == null ?
conversation.getAddress() : contactName);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
List<StatusBarNotification> notifications = notificationManager.getActiveNotifications();
List<MessageTrackers> listMessages = new ArrayList<>();
for(StatusBarNotification notification : notifications) {
if (notification.getId() == Integer.parseInt(conversation.getThread_id())) {
Bundle extras = notification.getNotification().extras;
String prevMessage = extras.getCharSequence(Notification.EXTRA_TEXT).toString();
String prevTitle = extras.getCharSequence(Notification.EXTRA_TITLE).toString();
MessageTrackers messageTrackers = new MessageTrackers();
messageTrackers.message.append(prevMessage);
messageTrackers.title = prevTitle;
messageTrackers.person = prevTitle.equals(contactName == null ?
conversation.getAddress() : contactName) ?
person : replyPerson;
listMessages.add(messageTrackers);
}
}
MessageTrackers messageTrackers = new MessageTrackers();
messageTrackers.message.append(conversation.isIs_key() ?
context.getString(R.string.notification_title_new_key) :
reply == null ? conversation.getText() : reply);
messageTrackers.title = reply == null ?
(contactName == null ? conversation.getAddress() : contactName) : context.getString(R.string.notification_title_reply_you);
messageTrackers.person = reply == null ? person : replyPerson;
listMessages.add(messageTrackers);
StringBuilder personConversations = new StringBuilder();
StringBuilder replyConversations = new StringBuilder();
List<MessageTrackers> newTrackers = new ArrayList<>();
for(MessageTrackers messageTracker : listMessages) {
if(messageTracker.title.equals(contactName == null ? conversation.getAddress(): contactName)) {
if(personConversations.length() > 0)
personConversations.append("\n\n");
personConversations.append(messageTracker.message);
if(replyConversations.length() > 0) {
MessageTrackers messageTrackers1 = new MessageTrackers();
messageTrackers1.person = replyPerson;
messageTrackers1.message = replyConversations;
newTrackers.add(messageTrackers1);
replyConversations = new StringBuilder();
}
}
else {
if(replyConversations.length() > 0)
replyConversations.append("\n\n");
replyConversations.append(messageTracker.message);
if(personConversations.length() > 0) {
MessageTrackers messageTrackers1 = new MessageTrackers();
messageTrackers1.person = person;
messageTrackers1.message = personConversations;
newTrackers.add(messageTrackers1);
personConversations = new StringBuilder();
}
}
}
if(personConversations.length() > 0) {
MessageTrackers messageTrackers1 = new MessageTrackers();
messageTrackers1.person = person;
messageTrackers1.message = personConversations;
newTrackers.add(messageTrackers1);
}
if(replyConversations.length() > 0) {
MessageTrackers messageTrackers1 = new MessageTrackers();
messageTrackers1.person = replyPerson;
messageTrackers1.message = replyConversations;
newTrackers.add(messageTrackers1);
}
for(MessageTrackers messageTracker : newTrackers) {
messagingStyle.addMessage(new NotificationCompat.MessagingStyle.Message(
messageTracker.message, System.currentTimeMillis(),messageTracker.person));
}
// messagingStyle.addMessage(new NotificationCompat.MessagingStyle.Message(
// conversation.getText(), System.currentTimeMillis(), person));
return messagingStyle;
}
public static NotificationCompat.Builder
getNotificationBuilder(Context context, Intent replyBroadcastIntent, Conversation conversation,
PendingIntent pendingIntent){
String shortcutInfo = getShortcutInfo(context, conversation);
String contactName = Contacts.retrieveContactName(context, conversation.getAddress());
NotificationCompat.BubbleMetadata bubbleMetadata = new NotificationCompat.BubbleMetadata
.Builder(contactName == null ? conversation.getAddress() : contactName)
.setDesiredHeight(400)
.build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context, context.getString(R.string.incoming_messages_channel_id))
.setContentTitle(contactName == null ? conversation.getAddress() : contactName)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_stat_name)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setAllowSystemGeneratedContextualActions(true)
.setPriority(Notification.PRIORITY_MAX)
.setShortcutId(shortcutInfo)
.setBubbleMetadata(bubbleMetadata)
.setContentIntent(pendingIntent)
.setCategory(NotificationCompat.CATEGORY_MESSAGE);
String markAsReadLabel = context.getResources().getString(R.string.notifications_mark_as_read_label);
Intent markAsReadIntent = new Intent(context, IncomingTextSMSReplyActionBroadcastReceiver.class);
markAsReadIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id());
markAsReadIntent.putExtra(Conversation.ID, conversation.getMessage_id());
markAsReadIntent.setAction(IncomingTextSMSReplyActionBroadcastReceiver.MARK_AS_READ_BROADCAST_INTENT);
PendingIntent markAsReadPendingIntent =
PendingIntent.getBroadcast(context, Integer.parseInt(conversation.getThread_id()),
markAsReadIntent,
PendingIntent.FLAG_MUTABLE);
NotificationCompat.Action markAsReadAction = new NotificationCompat.Action.Builder(null,
markAsReadLabel, markAsReadPendingIntent)
.build();
builder.addAction(markAsReadAction);
if(replyBroadcastIntent != null) {
PendingIntent replyPendingIntent =
PendingIntent.getBroadcast(context, Integer.parseInt(conversation.getThread_id()),
replyBroadcastIntent,
PendingIntent.FLAG_MUTABLE);
String replyLabel = context.getResources().getString(R.string.notifications_reply_label);
RemoteInput remoteInput = new RemoteInput.Builder(
IncomingTextSMSReplyActionBroadcastReceiver.KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(null,
replyLabel, replyPendingIntent)
.addRemoteInput(remoteInput)
.build();
builder.addAction(replyAction);
}
else if(conversation.getThread_id() != null){
Intent muteIntent = new Intent(context, IncomingTextSMSReplyActionBroadcastReceiver.class);
muteIntent.putExtra(Conversation.ADDRESS, conversation.getAddress());
muteIntent.putExtra(Conversation.ID, conversation.getMessage_id());
muteIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id());
muteIntent.setAction(IncomingTextSMSReplyActionBroadcastReceiver.MUTE_BROADCAST_INTENT);
PendingIntent mutePendingIntent =
PendingIntent.getBroadcast(context, Integer.parseInt(conversation.getThread_id()),
muteIntent, PendingIntent.FLAG_MUTABLE);
NotificationCompat.Action muteAction = new NotificationCompat.Action.Builder(null,
context.getString(R.string.conversation_menu_mute), mutePendingIntent)
.build();
builder.addAction(muteAction);
}
return builder;
}
private static String getShortcutInfo(Context context, Conversation conversation) {
Uri smsUrl = Uri.parse("smsto:" + conversation.getAddress());
Intent intent = new Intent(Intent.ACTION_SENDTO, smsUrl);
intent.putExtra(Conversation.THREAD_ID, conversation.getThread_id());
Person person = getPerson(context, conversation);
String contactName = Contacts.retrieveContactName(context, conversation.getAddress());
ShortcutInfoCompat shortcutInfoCompat = new ShortcutInfoCompat.Builder(context,
contactName == null ? conversation.getAddress() : contactName)
.setLongLived(true)
.setIntent(intent)
.setShortLabel(contactName == null ? conversation.getAddress() : contactName)
.setPerson(person)
.build();
ShortcutManagerCompat.pushDynamicShortcut(context, shortcutInfoCompat);
return shortcutInfoCompat.getId();
}
}
| 15,057 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
SMSPduLevel.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/SMSPduLevel.java | package com.afkanerd.deku.DefaultSMS.Models;
import android.util.Log;
import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver;
import java.text.ParseException;
public class SMSPduLevel {
public static void interpret_PDU(byte[] pdu) throws ParseException {
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU: " + pdu.length);
//
// String pduHex = DataHelper.getHexOfByte(pdu);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU: " + pduHex);
//
// int pduIterator = 0;
//
// byte SMSC_length = pdu[pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_length: " + (int) SMSC_length);
//
// byte SMSC_address_format = pdu[++pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_address_format: " +
// Integer.toHexString(SMSC_address_format));
//
// String SMSC_address_format_binary = DataHelper.byteToBinary(new byte[]{SMSC_address_format});
// parse_address_format(SMSC_address_format_binary.substring(SMSC_address_format_binary.length() - 7));
//
// byte[] SMSC_address = SMSHandler.copyBytes(pdu, ++pduIterator, --SMSC_length);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_address_format - binary: " + SMSC_address_format_binary);
//
// int[] addressHolder = DataHelper.bytesToNibbleArray(SMSC_address);
// String address = DataHelper.arrayToString(addressHolder);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_address: " + address);
//
// pduIterator += --SMSC_length;
//
// // TPDU begins
// byte first_octet = pdu[++pduIterator];
// String first_octet_binary = Integer.toBinaryString(first_octet);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU First octet binary: " + first_octet_binary);
//
// byte sender_address_length = pdu[++pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU Sender address length: " + (int) sender_address_length);
//
// byte sender_address_type = pdu[++pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU Sender address type: " +
// DataHelper.getHexOfByte(new byte[]{sender_address_type}));
//
// byte[] sender_address = copyBytes(pdu, ++pduIterator, sender_address_length / 2);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU Sender address: " +
// DataHelper.getHexOfByte(sender_address));
//
// addressHolder = DataHelper.bytesToNibbleArray(sender_address);
// address = DataHelper.arrayToString(addressHolder);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMS_Sender_address: " + address);
//
// pduIterator += (sender_address_length / 2) - 1;
//
// byte PID = pdu[++pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU PID: " +
// DataHelper.getHexOfByte(new byte[]{PID}));
//
// byte DCS = pdu[++pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU DCS: " +
// DataHelper.getHexOfByte(new byte[]{DCS}));
//
// byte[] SCTS = copyBytes(pdu, ++pduIterator, 7);
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SCTS: " +
// DataHelper.getHexOfByte(SCTS));
// String timestamp = DataHelper.arrayToString(DataHelper.bytesToNibbleArray(SCTS));
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SCTS: " + timestamp);
//
// SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
// Date date = sdf.parse(timestamp);
//
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU Timestamp: " + date.toString());
//
// pduIterator += 7;
//
// byte UDL = pdu[pduIterator];
// Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU UDL: " +
// DataHelper.getHexOfByte(new byte[]{UDL}));
}
public static void parse_address_format(String SMSC_address_format) {
Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU parsing address format: " + SMSC_address_format);
// TODO: compare and match the different TON and NPI values
final String TON_INTERNATIONAL = "001";
final String TON_NATIONAL = "010";
final String NPI_ISDN = "0001";
String SMSC_TON = SMSC_address_format.substring(0, 3);
String SMSC_NPI = SMSC_address_format.substring(3);
Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_TON: " + SMSC_TON);
Log.d(IncomingTextSMSBroadcastReceiver.class.getName(), "PDU SMSC_NPI: " + SMSC_NPI);
}
// A function that takes a pdu string as input and returns an array of two strings: the OA and DA
}
| 4,923 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
Compression.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Compression.java | package com.afkanerd.deku.DefaultSMS.Models;
import android.util.Log;
import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
public class Compression {
public static byte[] compressDeflate(byte[] input) {
// Create a new Deflater instance
Deflater deflater = new Deflater();
// Set the input data for the deflater
deflater.setInput(input);
// Tell the deflater that we're done with the input data
deflater.finish();
// Create a new ByteArrayOutputStream to hold the compressed data
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
// Create a new buffer to hold the compressed data
byte[] buffer = new byte[1024];
int length;
// Compress the input data and write the compressed data to the ByteArrayOutputStream
while (!deflater.finished()) {
length = deflater.deflate(buffer);
outputStream.write(buffer, 0, length);
}
// Close the ByteArrayOutputStream and the Deflater
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
deflater.end();
// Return the compressed data as a byte array
return outputStream.toByteArray();
}
public static byte[] compressLZ4(byte[] inputBytes) {
try {
// Create an LZ4 compressor
LZ4Factory factory = LZ4Factory.fastestInstance();
LZ4Compressor compressor = factory.fastCompressor();
// Compress the input bytes
byte[] compressedBytes = compressor.compress(inputBytes);
// Return the compressed bytes
return compressedBytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static byte[] compressGzip(byte[] inputBytes) {
try {
// Create a ByteArrayOutputStream to hold the compressed output
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Create a GZIPOutputStream to compress the input bytes
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
// Write the input bytes to the GZIPOutputStream
gzipOutputStream.write(inputBytes);
// Close the GZIPOutputStream to flush any remaining data and finalize the compression
gzipOutputStream.close();
// Return the compressed bytes
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static byte[] decompressGZIP(byte[] inputBytes) {
try {
// Create a GZIP input stream from the input bytes
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(inputBytes));
// Create a byte output stream to hold the decompressed bytes
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Decompress the input bytes
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = gzipInputStream.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
// Close the streams
gzipInputStream.close();
byteArrayOutputStream.close();
// Return the decompressed bytes
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static byte[] decompressDeflate(byte[] input) throws Throwable {
try {
// Create an Inflater for decompression
Inflater inflater = new Inflater();
inflater.setInput(input, 0, input.length);
// Create a byte output stream to hold the decompressed bytes
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// Decompress the input bytes
byte[] buffer = new byte[100];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
byteArrayOutputStream.write(buffer, 0, count);
if(count == 0 && !inflater.finished()) {
Log.d(Compression.class.getName(), "Error decompressing.." + inflater.getRemaining());
break;
}
}
// Close the streams
inflater.end();
byteArrayOutputStream.close();
// Return the decompressed bytes
return byteArrayOutputStream.toByteArray();
} catch (DataFormatException | IOException e) {
throw new Throwable(e);
}
// Inflater decompresser = new Inflater();
// decompresser.setInput(input, 0, input.length);
// byte[] result = new byte[100];
// int resultLength = decompresser.inflate(result);
// decompresser.end();
}
public static boolean isDeflateCompressed(byte[] data) {
// Create a new Deflater instance
Deflater deflater = new Deflater();
// Set the input data for the deflater
deflater.setInput(data);
// Tell the deflater that we're done with the input data
deflater.finish();
// Create a new buffer to hold the compressed data
byte[] buffer = new byte[1024];
int length;
// Compress the input data and check if the output size is smaller
while (!deflater.finished()) {
length = deflater.deflate(buffer);
if (length > data.length) {
return true; // Input data is compressed with deflate algorithm
}
}
// Input data is not compressed with deflate algorithm
return false;
}
} | 6,258 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
Archive.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Archive.java | package com.afkanerd.deku.DefaultSMS.Models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class Archive {
@NonNull
@PrimaryKey
public String thread_id;
public boolean is_archived;
}
| 269 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
SIMHandler.java | /FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/SIMHandler.java | package com.afkanerd.deku.DefaultSMS.Models;
import static android.content.Context.TELEPHONY_SERVICE;
import static androidx.core.content.ContextCompat.getSystemService;
import android.content.Context;
import android.telephony.CellInfo;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import java.util.List;
public class SIMHandler {
public static List<SubscriptionInfo> getSimCardInformation(Context context) {
SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
return subscriptionManager.getActiveSubscriptionInfoList();
}
public static boolean isDualSim(Context context) {
TelephonyManager manager = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
return manager.getPhoneCount() > 1;
}
private static String getSimStateString(int simState) {
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
return "Absent";
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
return "Network locked";
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
return "PIN required";
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
return "PUK required";
case TelephonyManager.SIM_STATE_READY:
return "Ready";
case TelephonyManager.SIM_STATE_UNKNOWN:
default:
return "Unknown";
}
}
public static int getDefaultSimSubscription(Context context) {
int subId = SubscriptionManager.getDefaultSmsSubscriptionId();
if(subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID)
return getSimCardInformation(context).get(0).getSubscriptionId();
return subId;
}
public static String getSubscriptionName(Context context, int subscriptionId) {
List<SubscriptionInfo> subscriptionInfos = getSimCardInformation(context);
for(SubscriptionInfo subscriptionInfo : subscriptionInfos)
if(subscriptionInfo.getSubscriptionId() == subscriptionId) {
if(subscriptionInfo.getCarrierName() != null)
return subscriptionInfo.getDisplayName().toString();
}
return "";
}
}
| 2,428 | Java | .java | deku-messaging/Deku-SMS-Android | 171 | 11 | 26 | 2021-12-16T13:07:42Z | 2024-05-06T18:37:37Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.