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
Transmissions.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Transmissions.java
package com.afkanerd.deku.DefaultSMS.Models; import android.app.PendingIntent; import android.telephony.SmsManager; import android.widget.Toast; import java.util.ArrayList; public class Transmissions { private static final short DATA_TRANSMISSION_PORT = 8200; public static void sendTextSMS(String destinationAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent, Integer subscriptionId) throws Exception { if (text == null || text.isEmpty()) return; SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId); try { ArrayList<String> dividedMessage = smsManager.divideMessage(text); if (dividedMessage.size() < 2) smsManager.sendTextMessage(destinationAddress, null, text, sentIntent, deliveryIntent); else { ArrayList<PendingIntent> sentPendingIntents = new ArrayList<>(); ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<>(); for (int i = 0; i < dividedMessage.size() - 1; i++) { sentPendingIntents.add(null); deliveredPendingIntents.add(null); } sentPendingIntents.add(sentIntent); deliveredPendingIntents.add(deliveryIntent); smsManager.sendMultipartTextMessage(destinationAddress, null, dividedMessage, sentPendingIntents, deliveredPendingIntents); } } catch (Exception e) { throw new Exception(e); } } public static void sendDataSMS(String destinationAddress, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent, Integer subscriptionId) throws Exception { if (data == null) return; SmsManager smsManager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId); try { smsManager.sendDataMessage( destinationAddress, null, DATA_TRANSMISSION_PORT, data, sentIntent, deliveryIntent); } catch (Exception e) { throw new Exception(e); } } }
2,388
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ServiceHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/ServiceHandler.java
package com.afkanerd.deku.DefaultSMS.Models; import android.app.ActivityManager; import android.content.Context; import java.util.List; public class ServiceHandler { public static List<ActivityManager.RunningServiceInfo> getRunningService(Context context){ ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); return activityManager.getRunningServices(Integer.MAX_VALUE); } }
455
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
SMSDatabaseWrapper.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/SMSDatabaseWrapper.java
package com.afkanerd.deku.DefaultSMS.Models; import android.content.Context; import android.os.Bundle; import android.provider.Telephony; import android.util.Base64; import android.util.Log; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; public class SMSDatabaseWrapper extends NativeSMSDB.Outgoing { public static void send_data(Context context, Conversation conversation) throws Exception { String transmissionAddress = Helpers.getFormatForTransmission(conversation.getAddress(), Helpers.getUserCountry(context)); String[] nativeOutputs = NativeSMSDB.Outgoing._send_data(context, conversation.getMessage_id(), transmissionAddress, Base64.decode(conversation.getData(), Base64.DEFAULT), conversation.getSubscription_id(), null); } public static void send_text(Context context, Conversation conversation, Bundle bundle) throws Exception { String transmissionAddress = Helpers.getFormatForTransmission(conversation.getAddress(), Helpers.getUserCountry(context)); String[] nativeOutputs = NativeSMSDB.Outgoing._send_text(context, conversation.getMessage_id(), transmissionAddress, conversation.getText(), conversation.getSubscription_id(), bundle); // conversation.setThread_id(nativeOutputs[NativeSMSDB.THREAD_ID]); } public static void saveDraft(Context context, Conversation conversation) { Log.d(SMSDatabaseWrapper.class.getName(), "Saving draft: " + conversation.getText()); String[] outputs = NativeSMSDB.Outgoing.register_drafts(context, conversation.getMessage_id(), conversation.getAddress(), conversation.getText(), conversation.getSubscription_id()); // return outputs[NativeSMSDB.THREAD_ID]; } public static void deleteDraft(Context context, String threadId) { NativeSMSDB.deleteTypeForThread(context, String.valueOf(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT), threadId); } public static void deleteAllDraft(Context context) { NativeSMSDB.deleteAllType(context, String.valueOf(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT)); } }
2,299
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
SettingsHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/SettingsHandler.java
package com.afkanerd.deku.DefaultSMS.Models; import android.content.Context; import android.content.SharedPreferences; import androidx.preference.PreferenceManager; public class SettingsHandler { public static boolean alertNotEncryptedCommunicationDisabled(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); return sharedPreferences.getBoolean("encryption_disable", false); } }
468
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
NativeSMSDB.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/NativeSMSDB.java
package com.afkanerd.deku.DefaultSMS.Models; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Telephony; import android.telephony.SmsMessage; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.widget.Toast; import androidx.annotation.NonNull; import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver; import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Set; public class NativeSMSDB { public static String ID = "ID"; public static int THREAD_ID = 0; public static int MESSAGE_ID = 1; public static int BODY = 2; public static int ADDRESS = 3; public static int SUBSCRIPTION_ID = 4; public static int DATE_SENT = 5; public static int DATE = 6; public static Cursor fetchAll(Context context) { return context.getContentResolver().query( Telephony.Sms.CONTENT_URI, null, "thread_id IS NOT NULL", null, null); } public static Cursor fetchByThreadId(Context context, String threadId) { return context.getContentResolver().query(Telephony.Sms.CONTENT_URI, null, Telephony.Sms.THREAD_ID + "=?", new String[]{threadId}, null); } public static Cursor fetchByMessageId(@NonNull Context context, String id) { return context.getContentResolver().query( Telephony.Sms.CONTENT_URI, null, Telephony.Sms._ID + "=?", new String[]{id}, null); } public static int deleteMultipleMessages(Context context, String[] ids) { return context.getContentResolver().delete( Telephony.Sms.CONTENT_URI, Telephony.Sms._ID + " in (" + TextUtils.join(",", Collections.nCopies(ids.length, "?")) + ")", ids); } public static int deleteThreads(Context context, String[] threadIds) { return context.getContentResolver().delete( Telephony.Sms.CONTENT_URI, Telephony.TextBasedSmsColumns.THREAD_ID + " in (" + TextUtils.join(",", Collections.nCopies(threadIds.length, "?")) + ")", threadIds); } protected static int deleteMessage(Context context, String messageId) { try { return context.getContentResolver().delete( Telephony.Sms.CONTENT_URI, Telephony.Sms._ID + " = ?", new String[]{messageId}); } catch (Exception e) { e.printStackTrace(); } return -1; } protected static int deleteTypeForThread(Context context, String type, String threadId) { try { return context.getContentResolver().delete( Telephony.Sms.CONTENT_URI, Telephony.TextBasedSmsColumns.THREAD_ID + " = ? AND " + Telephony.TextBasedSmsColumns.TYPE + " = ?", new String[]{threadId, type}); } catch (Exception e) { e.printStackTrace(); } return -1; } protected static int deleteAllType(Context context, String type) { try { return context.getContentResolver().delete( Telephony.Sms.CONTENT_URI, Telephony.TextBasedSmsColumns.TYPE + " = ?", new String[]{type}); } catch (Exception e) { e.printStackTrace(); } return -1; } /* * Places which require playing with Native SMS DB * Outgoing: * Actions: * - Manual * - From send message * - From notifications - X * Broadcast: * - state changes * - Auto * - pending - X * - sent - X * - failed - X * - delivered -X * * Incoming: * Actions: * - Manual: * - Read status */ private static String[] parseNewIncomingUriForThreadInformation(Context context, Uri uri) { if(uri == null) return null; Cursor cursor = context.getContentResolver().query( uri, new String[]{ Telephony.TextBasedSmsColumns.THREAD_ID, Telephony.Sms._ID}, null, null, null); if (cursor.moveToFirst()) { String threadId = cursor.getString( cursor.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.THREAD_ID)); String messageId = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms._ID)); cursor.close(); return new String[]{threadId, messageId}; } return null; } private static String[] broadcastStateChanged(Context context, String messageId) { /** * Threads ID * Message ID */ Cursor cursor = context.getContentResolver().query( Telephony.Sms.CONTENT_URI, new String[]{ Telephony.TextBasedSmsColumns.THREAD_ID, Telephony.Sms._ID}, Telephony.Sms._ID + "=?", new String[]{messageId}, null); if (cursor.moveToFirst()) { String threadId = cursor.getString( cursor.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.THREAD_ID)); cursor.close(); return new String[]{threadId, messageId}; } return null; } public static class Outgoing { private static int update_status(Context context, int statusCode, String messageId, int errorCode) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.TextBasedSmsColumns.STATUS, statusCode); if(statusCode == Telephony.Sms.STATUS_NONE) contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT); if(statusCode == Telephony.Sms.STATUS_FAILED || errorCode > -1) { contentValues.put(Telephony.TextBasedSmsColumns.ERROR_CODE, errorCode); } try { return context.getContentResolver().update( Telephony.Sms.CONTENT_URI, contentValues, "_id=?", new String[]{messageId}); } catch (Exception e) { e.printStackTrace(); } return 0; } protected static String[] _send_text(Context context, String messageId, String destinationAddress, String text, int subscriptionId, Bundle bundle) throws Exception { String[] pendingOutputs = register_pending(context, messageId, destinationAddress, text, subscriptionId); PendingIntent[] pendingIntents = getPendingIntents(context, messageId, bundle); Transmissions.sendTextSMS(destinationAddress, text, pendingIntents[0], pendingIntents[1], subscriptionId); return pendingOutputs; } protected static String[] _send_data(Context context, String messageId, String destinationAddress, byte[] data, int subscriptionId, Bundle bundle) throws Exception { if(subscriptionId < 0) { Toast.makeText(context, "Subscription id not set!", Toast.LENGTH_LONG).show(); return null; } String[] outputs = register_pending_data(context, messageId, destinationAddress, Base64.encodeToString(data, Base64.DEFAULT), subscriptionId); PendingIntent[] pendingIntents = getPendingIntentsForData(context, messageId, bundle); Transmissions.sendDataSMS(destinationAddress, data, pendingIntents[0], pendingIntents[1], subscriptionId); return outputs; } protected static void _send_key(Context context, String messageId, String destinationAddress, byte[] data, int subscriptionId, Bundle bundle) throws Exception { PendingIntent[] pendingIntents = getPendingIntentsForData(context, messageId, bundle); Transmissions.sendDataSMS(destinationAddress, data, pendingIntents[0], pendingIntents[1], subscriptionId); } private static String[] register_pending_data(Context context, String messageId, String destinationAddress, String text, int subscriptionId) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms._ID, messageId); contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_OUTBOX); contentValues.put(Telephony.TextBasedSmsColumns.STATUS, Telephony.TextBasedSmsColumns.STATUS_PENDING); contentValues.put(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID, subscriptionId); contentValues.put(Telephony.TextBasedSmsColumns.ADDRESS, destinationAddress); contentValues.put(Telephony.TextBasedSmsColumns.DATE, String.valueOf(System.currentTimeMillis())); try { Uri uri = context.getContentResolver().insert( Telephony.Sms.CONTENT_URI, contentValues); return parseNewIncomingUriForThreadInformation(context, uri); } catch (Exception e) { throw e; } } private static String[] register_pending(Context context, String messageId, String destinationAddress, String text, int subscriptionId) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms._ID, messageId); contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_OUTBOX); contentValues.put(Telephony.TextBasedSmsColumns.STATUS, Telephony.TextBasedSmsColumns.STATUS_PENDING); contentValues.put(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID, subscriptionId); contentValues.put(Telephony.TextBasedSmsColumns.ADDRESS, destinationAddress); contentValues.put(Telephony.TextBasedSmsColumns.BODY, text); contentValues.put(Telephony.TextBasedSmsColumns.DATE_SENT, String.valueOf(System.currentTimeMillis())); try { Uri uri = context.getContentResolver().insert( Telephony.Sms.CONTENT_URI, contentValues); return parseNewIncomingUriForThreadInformation(context, uri); } catch (Exception e) { throw e; } } protected static String[] register_drafts(Context context, String messageId, String destinationAddress, String text, int subscriptionId) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms._ID, messageId); contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT); contentValues.put(Telephony.TextBasedSmsColumns.STATUS, Telephony.TextBasedSmsColumns.STATUS_PENDING); contentValues.put(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID, subscriptionId); contentValues.put(Telephony.TextBasedSmsColumns.ADDRESS, destinationAddress); contentValues.put(Telephony.TextBasedSmsColumns.BODY, text); contentValues.put(Telephony.TextBasedSmsColumns.DATE_SENT, String.valueOf(System.currentTimeMillis())); Uri uri = context.getContentResolver().insert( Telephony.Sms.CONTENT_URI, contentValues); return parseNewIncomingUriForThreadInformation(context, uri); } public static String[] register_failed(Context context, String messageId, int errorCode) { int numberChanged = update_status(context, Telephony.TextBasedSmsColumns.STATUS_FAILED, messageId, errorCode); return broadcastStateChanged(context, String.valueOf(messageId)); } public static String[] register_delivered(@NonNull Context context, String messageId) { int numberChanged = update_status(context, Telephony.TextBasedSmsColumns.STATUS_COMPLETE, messageId, -1); return broadcastStateChanged(context, String.valueOf(messageId)); } public static String[] register_sent(Context context, String messageId) { int numberChanged = update_status(context, Telephony.TextBasedSmsColumns.STATUS_NONE, messageId, -1); return broadcastStateChanged(context, String.valueOf(messageId)); } public static PendingIntent[] getPendingIntentsForData(Context context, String messageId, Bundle bundle) { Intent sentIntent = new Intent(IncomingDataSMSBroadcastReceiver.DATA_SENT_BROADCAST_INTENT); sentIntent.setPackage(context.getPackageName()); sentIntent.putExtra(ID, messageId); Intent deliveredIntent = new Intent(IncomingDataSMSBroadcastReceiver.DATA_DELIVERED_BROADCAST_INTENT); deliveredIntent.setPackage(context.getPackageName()); deliveredIntent.putExtra(Conversation.ID, messageId); if(bundle != null) { sentIntent.putExtras(bundle); deliveredIntent.putExtras(bundle); } PendingIntent sentPendingIntent = PendingIntent.getBroadcast(context, (int)Long.parseLong(messageId), sentIntent, PendingIntent.FLAG_IMMUTABLE); PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(context, (int)Long.parseLong(messageId), deliveredIntent, PendingIntent.FLAG_IMMUTABLE); return new PendingIntent[]{sentPendingIntent, deliveredPendingIntent}; } public static PendingIntent[] getPendingIntents(Context context, String messageId, Bundle bundle) { Intent sentIntent = new Intent(IncomingTextSMSBroadcastReceiver.SMS_SENT_BROADCAST_INTENT); sentIntent.setPackage(context.getPackageName()); sentIntent.putExtra(ID, messageId); Intent deliveredIntent = new Intent(IncomingTextSMSBroadcastReceiver.SMS_DELIVERED_BROADCAST_INTENT); deliveredIntent.setPackage(context.getPackageName()); deliveredIntent.putExtra(Conversation.ID, messageId); if(bundle != null) { sentIntent.putExtras(bundle); deliveredIntent.putExtras(bundle); } PendingIntent sentPendingIntent = PendingIntent.getBroadcast(context, (int)Long.parseLong(messageId), sentIntent, PendingIntent.FLAG_IMMUTABLE); PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(context, (int)Long.parseLong(messageId), deliveredIntent, PendingIntent.FLAG_IMMUTABLE); return new PendingIntent[]{sentPendingIntent, deliveredPendingIntent}; } } public static class Incoming { public static int update_all_read(Context context, int read, String[] threadId) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms.READ, read); try { return context.getContentResolver().update( Telephony.Sms.CONTENT_URI, contentValues, "thread_id in (" + TextUtils.join(",", Collections.nCopies(threadId.length, "?")) + ")", threadId); } catch (Exception e) { e.printStackTrace(); } return 0; } public static int update_all_read(Context context, int read) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms.READ, read); try { return context.getContentResolver().update( Telephony.Sms.CONTENT_URI, contentValues, null, null); } catch (Exception e) { e.printStackTrace(); } return 0; } public static int update_read(Context context, int read, String thread_id, String messageId) { ContentValues contentValues = new ContentValues(); contentValues.put(Telephony.Sms.READ, read); try { int updated = context.getContentResolver().update( Telephony.Sms.CONTENT_URI, contentValues, "thread_id=?", new String[]{thread_id}); return updated; } catch (Exception e) { e.printStackTrace(); } return 0; } public static String[] register_incoming_text(Context context, Intent intent) throws IOException { long messageId = System.currentTimeMillis(); ContentValues contentValues = new ContentValues(); Bundle bundle = intent.getExtras(); int subscriptionId = bundle.getInt("subscription", -1); String address = ""; StringBuilder bodyBuffer = new StringBuilder(); long dateSent = 0; long date = System.currentTimeMillis(); for (SmsMessage currentSMS : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { address = currentSMS.getDisplayOriginatingAddress(); // if(BuildConfig.DEBUG) { // Log.d(NativeSMSDB.class.getName(), "Incoming Display address: " + address); // Log.d(NativeSMSDB.class.getName(), "Incoming Originating address: " + currentSMS.getOriginatingAddress()); // Log.d(NativeSMSDB.class.getName(), "Incoming sent date: " + currentSMS.getTimestampMillis()); // Log.d(NativeSMSDB.class.getName(), "Incoming is reply: " + currentSMS.isReplyPathPresent()); // Log.d(NativeSMSDB.class.getName(), "Incoming is status reply: " + currentSMS.isStatusReportMessage()); // } String text_message = currentSMS.getDisplayMessageBody(); dateSent = currentSMS.getTimestampMillis(); bodyBuffer.append(text_message); } String body = bodyBuffer.toString(); contentValues.put(Telephony.Sms._ID, messageId); contentValues.put(Telephony.TextBasedSmsColumns.ADDRESS, address); contentValues.put(Telephony.TextBasedSmsColumns.BODY, body); contentValues.put(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID, subscriptionId); contentValues.put(Telephony.TextBasedSmsColumns.DATE_SENT, dateSent); contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX); try { Uri uri = context.getContentResolver().insert( Telephony.Sms.CONTENT_URI, contentValues); String[] broadcastOutputs = parseNewIncomingUriForThreadInformation(context, uri); String[] returnString = new String[7]; returnString[THREAD_ID] = broadcastOutputs[THREAD_ID]; returnString[MESSAGE_ID] = broadcastOutputs[MESSAGE_ID]; returnString[BODY] = body; returnString[ADDRESS] = address; returnString[SUBSCRIPTION_ID] = String.valueOf(subscriptionId); returnString[DATE_SENT] = String.valueOf(dateSent); returnString[DATE] = String.valueOf(date); return returnString; } catch (Exception e) { e.printStackTrace(); } return null; } public static String[] register_incoming_data(Context context, Intent intent) throws IOException { /* * Bundle: [ * android.telephony.extra.SUBSCRIPTION_INDEX, * messageId, * format, * android.telephony.extra.SLOT_INDEX, * pdus, * phone, * subscription * ] */ ContentValues contentValues = new ContentValues(); Bundle bundle = intent.getExtras(); int subscriptionId = bundle.getInt("subscription", -1); Set<String> keySet = bundle.keySet(); String address = ""; ByteArrayOutputStream dataBodyBuffer = new ByteArrayOutputStream(); long dateSent = 0; long date = System.currentTimeMillis(); for (SmsMessage currentSMS : Telephony.Sms.Intents.getMessagesFromIntent(intent)) { address = currentSMS.getOriginatingAddress(); dataBodyBuffer.write(currentSMS.getUserData()); dateSent = currentSMS.getTimestampMillis(); } String body = Base64.encodeToString(dataBodyBuffer.toByteArray(), Base64.DEFAULT); contentValues.put(Telephony.Sms._ID, System.currentTimeMillis()); contentValues.put(Telephony.TextBasedSmsColumns.ADDRESS, address); contentValues.put(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID, subscriptionId); contentValues.put(Telephony.TextBasedSmsColumns.TYPE, Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX); try { Uri uri = context.getContentResolver().insert( Telephony.Sms.CONTENT_URI, contentValues); String[] broadcastOutputs = parseNewIncomingUriForThreadInformation(context, uri); String[] returnString = new String[7]; returnString[THREAD_ID] = broadcastOutputs[THREAD_ID]; returnString[MESSAGE_ID] = broadcastOutputs[MESSAGE_ID]; returnString[BODY] = body; returnString[ADDRESS] = address; returnString[SUBSCRIPTION_ID] = String.valueOf(subscriptionId); returnString[DATE_SENT] = String.valueOf(dateSent); returnString[DATE] = String.valueOf(date); return returnString; } catch (Exception e) { e.printStackTrace(); } return null; } } }
23,921
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
SemaphoreManager.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Database/SemaphoreManager.java
package com.afkanerd.deku.DefaultSMS.Models.Database; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.Semaphore; public class SemaphoreManager { private static final Semaphore semaphore = new Semaphore(1); private static final Map<Integer, Semaphore> semaphoreMap = new HashMap<>(); public static void acquireSemaphore(int id) throws InterruptedException { if(!semaphoreMap.containsKey(id) || semaphoreMap.get(id) == null) semaphoreMap.put(id, new Semaphore(1)); Objects.requireNonNull(semaphoreMap.get(id)).acquire(); } public static void releaseSemaphore(int id) throws InterruptedException { if(!semaphoreMap.containsKey(id) || semaphoreMap.get(id) == null) semaphoreMap.put(id, new Semaphore(1)); Objects.requireNonNull(semaphoreMap.get(id)).release(); } public static void acquireSemaphore() throws InterruptedException { semaphore.acquire(); } public static void releaseSemaphore() throws InterruptedException { semaphore.release(); } }
1,117
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
Migrations.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Database/Migrations.java
package com.afkanerd.deku.DefaultSMS.Models.Database; import static com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientListingActivity.GATEWAY_CLIENT_LISTENERS; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import androidx.annotation.NonNull; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientHandler; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientProjects; public class Migrations { // Define the migration class public static class Migration4To5 extends Migration { public Migration4To5() { super(4, 5); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { // Step 1: Create the new table // database.execSQL("CREATE TABLE IF NOT EXISTS new_table (id INTEGER PRIMARY KEY, name TEXT)"); } } public static class Migration5To6 extends Migration { public Migration5To6() { super(5, 6); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { // Step 1: Create the new table database.execSQL("ALTER TABLE GatewayClient ADD COLUMN projectBinding2 TEXT"); } } public static class Migration6To7 extends Migration { public Migration6To7() { super(6, 7); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("DROP TABLE IF EXISTS GatewayServer"); database.execSQL("CREATE TABLE IF NOT EXISTS GatewayServer (" + "id INTEGER NOT NULL PRIMARY KEY, " + "format TEXT, date INTEGER, " + "protocol TEXT, URL TEXT)"); } } public static class Migration7To8 extends Migration { public Migration7To8() { super(7, 8); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE GatewayServer ADD COLUMN tag TEXT"); } } public static class Migration8To9 extends Migration { public Migration8To9() { super(8, 9); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("CREATE TABLE IF NOT EXISTS ThreadedConversations " + "(thread_id TEXT PRIMARY KEY NOT NULL, " + "msg_count INTEGER NOT NULL, " + "type INTEGER NOT NULL, " + "date TEXT, " + "is_archived INTEGER NOT NULL, " + "is_blocked INTEGER NOT NULL, " + "is_read INTEGER NOT NULL, " + "is_shortcode INTEGER NOT NULL, " + "snippet TEXT, " + "contact_name TEXT, " + "address TEXT, " + "formatted_datetime TEXT)"); database.execSQL("CREATE TABLE IF NOT EXISTS Conversation " + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "message_id TEXT, " + "thread_id TEXT, " + "date TEXT, " + "date_sent TEXT, " + "type INTEGER NOT NULL, " + "num_segments INTEGER NOT NULL, " + "subscription_id INTEGER NOT NULL, " + "error_code INTEGER NOT NULL, " + "status INTEGER NOT NULL, " + "read INTEGER NOT NULL, " + "is_encrypted INTEGER NOT NULL, " + "is_key INTEGER NOT NULL, " + "is_image INTEGER NOT NULL, " + "formatted_date TEXT, " + "address TEXT, " + "text TEXT, " + "data TEXT)"); database.execSQL("CREATE TABLE IF NOT EXISTS ConversationsThreadsEncryption " + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "publicKey TEXT, " + "keystoreAlias TEXT, " + "exchangeDate INTEGER NOT NULL)"); database.execSQL("UPDATE ThreadedConversations SET is_archived = 1 " + "WHERE thread_id IN (SELECT threadId as thread_id FROM Archive)"); database.execSQL("DROP TABLE IF EXISTS Archive"); database.execSQL("CREATE TABLE IF NOT EXISTS Archive " + "(thread_id TEXT PRIMARY KEY NOT NULL, is_archived INTEGER NOT NULL)"); database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_Conversation_message_id ON Conversation (message_id)"); database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_ConversationsThreadsEncryption_keystoreAlias " + "ON ConversationsThreadsEncryption (keystoreAlias)"); } } public static class Migration9To10 extends Migration { public Migration9To10() { super(9, 10); } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE ConversationsThreadsEncryption ADD COLUMN states TEXT"); database.execSQL("ALTER TABLE ConversationsThreadsEncryption ADD COLUMN _mk TEXT"); } } public static class Migration10To11 extends Migration { public Migration10To11(Context context) { super(10, 11); SharedPreferences sharedPreferences = context.getSharedPreferences(GatewayClientHandler.MIGRATIONS, Context.MODE_PRIVATE); if(!sharedPreferences.contains(GatewayClientHandler.MIGRATIONS_TO_11)) { context.getSharedPreferences(GatewayClientHandler.MIGRATIONS, Context.MODE_PRIVATE) .edit().putBoolean(GatewayClientHandler.MIGRATIONS_TO_11, true).apply(); sharedPreferences = context.getSharedPreferences(GATEWAY_CLIENT_LISTENERS, Context.MODE_PRIVATE); for(String key : sharedPreferences.getAll().keySet()) { sharedPreferences.edit().remove(key).apply(); } } } @Override public void migrate(@NonNull SupportSQLiteDatabase database) { } } public static class MIGRATION_11_12 extends Migration { public MIGRATION_11_12() { super(11, 12); } @Override public void migrate(@NonNull SupportSQLiteDatabase supportSQLiteDatabase) { Log.d(getClass().getName(), "Migration to 12 happening"); supportSQLiteDatabase.execSQL("ALTER TABLE ThreadedConversations " + "ADD COLUMN is_mute INTEGER NOT NULL DEFAULT 0"); supportSQLiteDatabase.execSQL("ALTER TABLE ThreadedConversations " + "ADD COLUMN is_secured INTEGER NOT NULL DEFAULT 0"); } }; }
7,140
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
Datastore.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Database/Datastore.java
package com.afkanerd.deku.DefaultSMS.Models.Database; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.AutoMigration; import androidx.room.Database; import androidx.room.DatabaseConfiguration; import androidx.room.InvalidationTracker; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteOpenHelper; import com.afkanerd.deku.DefaultSMS.Models.Archive; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryption; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryptionDao; import com.afkanerd.deku.E2EE.Security.CustomKeyStore; import com.afkanerd.deku.E2EE.Security.CustomKeyStoreDao; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClient; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientDAO; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientProjectDao; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientProjects; import com.afkanerd.deku.Router.GatewayServers.GatewayServer; import com.afkanerd.deku.Router.GatewayServers.GatewayServerDAO; //import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClient; //import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClientDAO; //import com.afkanerd.deku.Router.GatewayServers.GatewayServer; //import com.afkanerd.deku.Router.GatewayServers.GatewayServerDAO; //@Database(entities = {GatewayServer.class, Archive.class, GatewayClient.class, // ThreadedConversations.class, Conversation.class}, version = 9) @Database(entities = { ThreadedConversations.class, CustomKeyStore.class, Archive.class, GatewayServer.class, GatewayClientProjects.class, ConversationsThreadsEncryption.class, Conversation.class, GatewayClient.class}, version = 12, autoMigrations = {@AutoMigration(from = 11, to = 12)}) public abstract class Datastore extends RoomDatabase { public static Datastore datastore; public static String databaseName = "SMSWithoutBorders-Messaging-DB"; public abstract GatewayServerDAO gatewayServerDAO(); public abstract GatewayClientDAO gatewayClientDAO(); public abstract GatewayClientProjectDao gatewayClientProjectDao(); public abstract ThreadedConversationsDao threadedConversationsDao(); public abstract ConversationDao conversationDao(); public abstract CustomKeyStoreDao customKeyStoreDao(); public abstract ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao(); @Override public void clearAllTables() { } @NonNull @Override protected InvalidationTracker createInvalidationTracker() { return null; } @NonNull @Override protected SupportSQLiteOpenHelper createOpenHelper(@NonNull DatabaseConfiguration databaseConfiguration) { return null; } }
3,156
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ThreadedConversationsHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.Telephony; import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao; public class ThreadedConversationsHandler { public static ThreadedConversations get(Context context, String address) { long threadId = Telephony.Threads.getOrCreateThreadId(context, address); ThreadedConversations threadedConversations = new ThreadedConversations(); threadedConversations.setAddress(address); threadedConversations.setThread_id(String.valueOf(threadId)); return threadedConversations; } public static ThreadedConversations get(ThreadedConversationsDao threadedConversationsDao, ThreadedConversations threadedConversations) throws InterruptedException { final ThreadedConversations[] threadedConversations1 = {threadedConversations}; Thread thread = new Thread(new Runnable() { @Override public void run() { threadedConversations1[0] = threadedConversationsDao .get(threadedConversations.getThread_id()); } }); thread.start(); thread.join(); return threadedConversations1[0]; } public static void call(Context context, ThreadedConversations threadedConversations) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); callIntent.setData(Uri.parse("tel:" + threadedConversations.getAddress())); context.startActivity(callIntent); } }
1,720
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversations.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ThreadedConversations.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations; import android.content.Context; import android.database.Cursor; import android.provider.Telephony; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DiffUtil; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import com.afkanerd.deku.DefaultSMS.Models.Contacts; import com.afkanerd.deku.DefaultSMS.R; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity public class ThreadedConversations { public boolean isIs_secured() { return is_secured; } public void setIs_secured(boolean is_secured) { this.is_secured = is_secured; } @ColumnInfo(defaultValue = "0") public boolean is_secured = false; @NonNull @PrimaryKey private String thread_id; private String address; @Ignore private int avatar_color; @Ignore private String avatar_initials; @Ignore private String avatar_image; private int msg_count; private int type; private String date; private boolean is_archived; private boolean is_blocked; private boolean is_shortcode; private boolean is_read; private String snippet; private String contact_name; private String formatted_datetime; public boolean isIs_mute() { return is_mute; } public void setIs_mute(boolean is_mute) { this.is_mute = is_mute; } @ColumnInfo(defaultValue = "0") private boolean is_mute = false; public static ThreadedConversations build(Context context, Conversation conversation) { ThreadedConversations threadedConversations = new ThreadedConversations(); threadedConversations.setAddress(conversation.getAddress()); if(conversation.isIs_key()) { threadedConversations.setSnippet(context.getString(R.string.conversation_threads_secured_content)); } else threadedConversations.setSnippet(conversation.getText()); threadedConversations.setThread_id(conversation.getThread_id()); threadedConversations.setDate(conversation.getDate()); threadedConversations.setType(conversation.getType()); threadedConversations.setIs_read(conversation.isRead()); String contactName = Contacts.retrieveContactName(context, conversation.getAddress()); threadedConversations.setContact_name(contactName); return threadedConversations; } public static List<ThreadedConversations> buildRaw(Cursor cursor) { List<String> seenThreads = new ArrayList<>(); List<ThreadedConversations> threadedConversations = new ArrayList<>(); if(cursor.moveToFirst()) { do { ThreadedConversations threadedConversation = build(cursor); if(!seenThreads.contains(threadedConversation.getThread_id())) { seenThreads.add(threadedConversation.getThread_id()); threadedConversations.add(threadedConversation); } } while(cursor.moveToNext()); } return threadedConversations; } public static List<ThreadedConversations> buildRaw(Context context, List<Conversation> conversations) { List<ThreadedConversations> threadedConversations = new ArrayList<>(); for(Conversation conversation : conversations) { ThreadedConversations threadedConversation = build(context, conversation); String contactName = Contacts.retrieveContactName(context, threadedConversation.getAddress()); threadedConversation.setContact_name(contactName); threadedConversations.add(threadedConversation); } return threadedConversations; } public boolean isIs_shortcode() { return is_shortcode; } public void setIs_shortcode(boolean is_shortcode) { this.is_shortcode = is_shortcode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public static ThreadedConversations build(Cursor cursor) { int snippetIndex = cursor.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.BODY); int threadIdIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.THREAD_ID); int addressIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.ADDRESS); int typeIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.TYPE); int readIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.READ); int dateIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.DATE); ThreadedConversations threadedConversations = new ThreadedConversations(); threadedConversations.setSnippet(cursor.getString(snippetIndex)); threadedConversations.setThread_id(cursor.getString(threadIdIndex)); threadedConversations.setAddress(cursor.getString(addressIndex)); threadedConversations.setType(cursor.getInt(typeIndex)); threadedConversations.setIs_read(cursor.getInt(readIndex) == 1); threadedConversations.setDate(cursor.getString(dateIndex)); return threadedConversations; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getThread_id() { return thread_id; } public void setThread_id(String thread_id) { this.thread_id = thread_id; } public int getMsg_count() { return msg_count; } public void setMsg_count(int msg_count) { this.msg_count = msg_count; } public int getAvatar_color() { return avatar_color; } protected void setAvatar_color(int avatar_color) { this.avatar_color = avatar_color; } public boolean isIs_archived() { return is_archived; } public void setIs_archived(boolean is_archived) { this.is_archived = is_archived; } public boolean isIs_blocked() { return is_blocked; } public void setIs_blocked(boolean is_blocked) { this.is_blocked = is_blocked; } public boolean isIs_read() { return is_read; } public void setIs_read(boolean is_read) { this.is_read = is_read; } public String getSnippet() { return snippet; } public void setSnippet(String snippet) { this.snippet = snippet; } public String getContact_name() { return contact_name; } public void setContact_name(String contact_name) { this.contact_name = contact_name; // if(this.contact_name != null && !this.contact_name.isEmpty()) { // this.setAvatar_initials(this.contact_name.substring(0, 1)); // this.setAvatar_color(Helpers.generateColor(this.contact_name)); // } else { // this.setAvatar_initials(null); // try { // if (this.getAddress() != null && !this.getAddress().isEmpty()) // this.setAvatar_color(Helpers.generateColor(this.getAddress())); // else // this.setAvatar_color(Helpers.getRandomColor()); // } catch(Exception e) { // e.printStackTrace(); // } // } } public String getAvatar_initials() { return avatar_initials; } protected void setAvatar_initials(String avatar_initials) { this.avatar_initials = avatar_initials; } public String getAvatar_image() { return avatar_image; } public void setAvatar_image(String avatar_image) { this.avatar_image = avatar_image; } public String getFormatted_datetime() { return formatted_datetime; } public void setFormatted_datetime(String formatted_datetime) { this.formatted_datetime = formatted_datetime; } public static final DiffUtil.ItemCallback<ThreadedConversations> DIFF_CALLBACK = new DiffUtil.ItemCallback<ThreadedConversations>() { @Override public boolean areItemsTheSame(@NonNull ThreadedConversations oldItem, @NonNull ThreadedConversations newItem) { return oldItem.thread_id.equals(newItem.thread_id); } @Override public boolean areContentsTheSame(@NonNull ThreadedConversations oldItem, @NonNull ThreadedConversations newItem) { return oldItem.equals(newItem); } }; @Override public boolean equals(@Nullable Object obj) { if(obj instanceof ThreadedConversations) { ThreadedConversations threadedConversations = (ThreadedConversations) obj; return Objects.equals(threadedConversations.thread_id, this.thread_id) && threadedConversations.is_archived == this.is_archived && threadedConversations.is_blocked == this.is_blocked && threadedConversations.is_read == this.is_read && threadedConversations.type == this.type && threadedConversations.msg_count == this.msg_count && threadedConversations.is_mute == this.is_mute && Objects.equals(threadedConversations.date, this.date) && Objects.equals(threadedConversations.address, this.address) && Objects.equals(threadedConversations.contact_name, this.contact_name) && Objects.equals(threadedConversations.snippet, this.snippet); } return false; } public boolean diffReplace(ThreadedConversations threadedConversations) { if(!threadedConversations.equals(this)) return false; boolean diff = false; if(this.contact_name == null || !this.contact_name.equals(threadedConversations.getContact_name())) { this.contact_name = threadedConversations.getContact_name(); diff = true; } if(this.avatar_initials == null || !this.avatar_initials.equals(threadedConversations.getAvatar_initials())) { this.avatar_initials = threadedConversations.getAvatar_initials(); diff = true; } if(this.avatar_color != threadedConversations.getAvatar_color()) { this.avatar_color = threadedConversations.getAvatar_color(); diff = true; } if(this.snippet == null || !this.snippet.equals(threadedConversations.getSnippet())) { this.snippet = threadedConversations.getSnippet(); diff = true; } if(this.date == null || !this.date.equals(threadedConversations.getDate())) { this.date = threadedConversations.getDate(); diff = true; } if(this.type != threadedConversations.getType()) { this.type = threadedConversations.getType(); diff = true; } // if(this.is_read != threadedConversations.isIs_read()) { // this.is_read = threadedConversations.isIs_read(); // diff = true; // } this.msg_count = threadedConversations.getMsg_count(); return diff; } }
11,438
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
Conversation.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/Conversation.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations; import android.content.Context; import android.database.Cursor; import android.provider.Telephony; import android.util.Base64; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DiffUtil; 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.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore; import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations; import com.google.gson.annotations.Expose; @Entity(indices = {@Index(value={"message_id"}, unique=true)}) public class Conversation { public static final String ID = "ID"; public static final String ADDRESS = "ADDRESS"; public static final String THREAD_ID = "THREAD_ID"; public static final String SHARED_SMS_BODY = "sms_body"; @PrimaryKey(autoGenerate = true) public long id; public String message_id; public String thread_id; public String date; public String date_sent; public int type; public int num_segments; public int subscription_id; public int status; public int error_code; public boolean read; public boolean is_encrypted; public boolean is_key; public boolean is_image; public String formatted_date; public String address; public String text; public String data; // To stop gson from serializing this @Expose(serialize = false, deserialize = false) private String _mk; public String get_mk() { return _mk; } public void set_mk(String _mk) { this._mk = _mk; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public String getData() { return data; } public void setData(String data) { this.data = data; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDate_sent() { return date_sent; } public void setDate_sent(String date_sent) { this.date_sent = date_sent; } public String getMessage_id() { return String.valueOf(message_id); } public void setMessage_id(String message_id) { this.message_id = message_id; } public String getThread_id() { return thread_id; } public void setThread_id(String thread_id) { this.thread_id = thread_id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getNum_segments() { return num_segments; } public void setNum_segments(int num_segments) { this.num_segments = num_segments; } public int getSubscription_id() { return subscription_id; } public void setSubscription_id(int subscription_id) { this.subscription_id = subscription_id; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } public boolean isIs_encrypted() { return is_encrypted; } public void setIs_encrypted(boolean is_encrypted) { this.is_encrypted = is_encrypted; } public boolean isIs_key() { return is_key; } public void setIs_key(boolean is_key) { this.is_key = is_key; } public boolean isIs_image() { return is_image; } public void setIs_image(boolean is_image) { this.is_image = is_image; } public String getFormatted_date() { return formatted_date; } public void setFormatted_date(String formatted_date) { this.formatted_date = formatted_date; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Conversation(){} public Conversation(Cursor cursor) { int idIndex = cursor.getColumnIndexOrThrow(Telephony.Sms._ID); int bodyIndex = cursor.getColumnIndexOrThrow(Telephony.TextBasedSmsColumns.BODY); int threadIdIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.THREAD_ID); int addressIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.ADDRESS); int dateIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.DATE); int dateSentIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.DATE_SENT); int typeIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.TYPE); int statusIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.STATUS); int readIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.READ); int subscriptionIdIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.SUBSCRIPTION_ID); this.setMessage_id(cursor.getString(idIndex)); this.setText(cursor.getString(bodyIndex)); this.setThread_id(cursor.getString(threadIdIndex)); this.setAddress(cursor.getString(addressIndex)); this.setDate(cursor.getString(dateIndex)); this.setDate_sent(cursor.getString(dateSentIndex)); this.setType(cursor.getInt(typeIndex)); this.setStatus(cursor.getInt(statusIndex)); this.setRead(cursor.getInt(readIndex) == 1); this.setSubscription_id(cursor.getInt(subscriptionIdIndex)); } public static Conversation buildForDataTransmission(Conversation conversation, byte[] transmissionData) { String messageId = String.valueOf(System.currentTimeMillis()); Conversation newConversation = new Conversation(); newConversation.setIs_key(conversation.isIs_key()); newConversation.setMessage_id(messageId); newConversation.setData(Base64.encodeToString(transmissionData, Base64.DEFAULT)); newConversation.setSubscription_id(conversation.getSubscription_id()); newConversation.setType(Telephony.Sms.MESSAGE_TYPE_OUTBOX); newConversation.setDate(String.valueOf(System.currentTimeMillis())); newConversation.setAddress(conversation.getAddress()); newConversation.setStatus(Telephony.Sms.STATUS_PENDING); return newConversation; } public static Conversation build(Cursor cursor) { return new Conversation(cursor); } public static final DiffUtil.ItemCallback<Conversation> DIFF_CALLBACK = new DiffUtil.ItemCallback<Conversation>() { @Override public boolean areItemsTheSame(@NonNull Conversation oldItem, @NonNull Conversation newItem) { return oldItem.message_id.equals(newItem.message_id); } @Override public boolean areContentsTheSame(@NonNull Conversation oldItem, @NonNull Conversation newItem) { return oldItem.equals(newItem); } }; public boolean equals(@Nullable Object obj) { if(obj instanceof Conversation) { Conversation conversation = (Conversation) obj; if(data == null && text == null) return false; if(data == null) return conversation.thread_id.equals(this.thread_id) && conversation.message_id.equals(this.message_id) && conversation.text.equals(this.text) && conversation.status == this.status && conversation.date.equals(this.date) && conversation.address.equals(this.address) && conversation.isRead() == this.isRead() && conversation.type == this.type; if(text == null) return conversation.thread_id.equals(this.thread_id) && conversation.message_id.equals(this.message_id) && conversation.data.equals(this.data) && conversation.status == this.status && conversation.date.equals(this.date) && conversation.address.equals(this.address) && conversation.isRead() == this.isRead() && conversation.type == this.type; } return super.equals(obj); } }
8,836
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ConversationHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations; import android.content.Context; import android.provider.Telephony; import androidx.room.Room; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore; import java.util.List; public class ConversationHandler { public static ConversationDao conversationDao; public static Conversation buildConversationForSending(Context context, String body, int subscriptionId, String address) { long threadId = Telephony.Threads.getOrCreateThreadId(context, address); Conversation conversation = new Conversation(); conversation.setMessage_id(String.valueOf(System.currentTimeMillis())); conversation.setText(body); conversation.setSubscription_id(subscriptionId); conversation.setType(Telephony.Sms.MESSAGE_TYPE_OUTBOX); conversation.setDate(String.valueOf(System.currentTimeMillis())); conversation.setAddress(address); conversation.setThread_id(String.valueOf(threadId)); conversation.setStatus(Telephony.Sms.STATUS_PENDING); return conversation; } }
1,227
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsTemplateViewHolder.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ThreadedConversationsTemplateViewHolder.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import static android.provider.Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX; import static com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter.RECEIVED_UNREAD_VIEW_TYPE; import static com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter.RECEIVED_VIEW_TYPE; import static com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter.SENT_UNREAD_VIEW_TYPE; import static com.afkanerd.deku.DefaultSMS.AdaptersViewModels.ThreadedConversationRecyclerAdapter.SENT_VIEW_TYPE; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.provider.Telephony; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.Models.Contacts; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.R; import com.google.android.material.card.MaterialCardView; import java.util.List; import io.getstream.avatarview.AvatarView; public class ThreadedConversationsTemplateViewHolder extends RecyclerView.ViewHolder { public String id; public long messageId; public TextView snippet; public TextView address; public TextView date; public AvatarView contactInitials; public ImageView contactAvatar; public ImageView muteAvatar; public TextView youLabel; public ConstraintLayout layout; public MaterialCardView materialCardView; public View itemView; public ThreadedConversationsTemplateViewHolder(@NonNull View itemView) { super(itemView); this.itemView = itemView; snippet = itemView.findViewById(R.id.messages_thread_text); address = itemView.findViewById(R.id.messages_thread_address_text); date = itemView.findViewById(R.id.messages_thread_date); layout = itemView.findViewById(R.id.messages_threads_layout); youLabel = itemView.findViewById(R.id.message_you_label); contactInitials = itemView.findViewById(R.id.messages_threads_contact_initials); materialCardView = itemView.findViewById(R.id.messages_threads_cardview); contactAvatar = itemView.findViewById(R.id.messages_threads_contact_photo); muteAvatar = itemView.findViewById(R.id.messages_threads_mute_icon); } public void bind(ThreadedConversations conversation, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener, String defaultRegion) { this.id = String.valueOf(conversation.getThread_id()); int contactColor = Helpers.getColor(itemView.getContext(), id); if(conversation.getContact_name() != null && !conversation.getContact_name().isEmpty()) { this.contactAvatar.setVisibility(View.GONE); this.contactInitials.setVisibility(View.VISIBLE); this.contactInitials.setAvatarInitials(conversation.getContact_name().contains(" ") ? conversation.getContact_name() : conversation.getContact_name().substring(0, 1)); this.contactInitials.setAvatarInitialsBackgroundColor(contactColor); } else { this.contactAvatar.setVisibility(View.VISIBLE); this.contactInitials.setVisibility(View.GONE); Drawable drawable = contactAvatar.getDrawable(); if (drawable == null) { drawable = itemView.getContext().getDrawable(R.drawable.baseline_account_circle_24); } if(drawable != null) drawable.setColorFilter(contactColor, PorterDuff.Mode.SRC_IN); contactAvatar.setImageDrawable(drawable); } if(conversation.getContact_name() != null) { this.address.setText(conversation.getContact_name()); } else this.address.setText(conversation.getAddress()); this.snippet.setText(conversation.getSnippet()); String date = Helpers.formatDate(itemView.getContext(), Long.parseLong(conversation.getDate())); this.date.setText(date); this.materialCardView.setOnClickListener(onClickListener); this.materialCardView.setOnLongClickListener(onLongClickListener); if(conversation.isIs_mute()) this.muteAvatar.setVisibility(View.VISIBLE); else this.muteAvatar.setVisibility(View.GONE); // TODO: investigate new Avatar first before anything else // this.contactInitials.setPlaceholder(itemView.getContext().getDrawable(R.drawable.round_person_24)); } public static int getViewType(int position, List<ThreadedConversations> items) { if(position >= items.size()) return RECEIVED_VIEW_TYPE; ThreadedConversations threadedConversations = items.get(position); String snippet = threadedConversations.getSnippet(); int type = threadedConversations.getType(); // if(EncryptionHandlers.containersWaterMark(snippet) || EncryptionHandlers.isKeyExchange(snippet)) { // if(!threadedConversations.isIs_read()) { // return type == MESSAGE_TYPE_INBOX ? // RECEIVED_ENCRYPTED_UNREAD_VIEW_TYPE : SENT_ENCRYPTED_UNREAD_VIEW_TYPE; // } // else { // return type == MESSAGE_TYPE_INBOX ? // RECEIVED_ENCRYPTED_VIEW_TYPE : SENT_ENCRYPTED_VIEW_TYPE; // } // } if(!threadedConversations.isIs_read()) { return type == MESSAGE_TYPE_INBOX ? RECEIVED_UNREAD_VIEW_TYPE : SENT_UNREAD_VIEW_TYPE; } else { return type == MESSAGE_TYPE_INBOX ? RECEIVED_VIEW_TYPE : SENT_VIEW_TYPE; } } public void setCardOnClickListener(View.OnClickListener onClickListener) { this.materialCardView.setOnClickListener(onClickListener); } public static class ReadViewHolderThreadedConversations extends ThreadedConversationsTemplateViewHolder { public ReadViewHolderThreadedConversations(@NonNull View itemView) { super(itemView); snippet.setMaxLines(1); } } public static class UnreadViewHolderThreadedConversations extends ThreadedConversationsTemplateViewHolder { public UnreadViewHolderThreadedConversations(@NonNull View itemView) { super(itemView); address.setTextAppearance(R.style.conversation_unread_style); snippet.setTextAppearance(R.style.conversation_unread_style); date.setTextAppearance(R.style.conversation_unread_style); } } public static class UnreadEncryptedViewHolderThreadedConversations extends UnreadViewHolderThreadedConversations { public UnreadEncryptedViewHolderThreadedConversations(@NonNull View itemView) { super(itemView); snippet.setText(R.string.messages_thread_encrypted_content); } } public static class ReadEncryptedViewHolderThreadedConversations extends ReadViewHolderThreadedConversations { public ReadEncryptedViewHolderThreadedConversations(@NonNull View itemView) { super(itemView); snippet.setText(R.string.messages_thread_encrypted_content); } } public void highlight(){ materialCardView.setBackgroundResource(R.drawable.received_messages_drawable); // this.setIsRecyclable(false); } public void unHighlight(){ materialCardView.setBackgroundResource(0); // this.setIsRecyclable(true); } }
7,930
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationSentViewHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ConversationSentViewHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import android.graphics.Color; import android.provider.Telephony; import android.text.Spannable; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; //import androidx.constraintlayout.widget.ConstraintLayout; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.constraintlayout.widget.ConstraintLayout; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.SIMHandler; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.E2EE.E2EEHandler; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; public class ConversationSentViewHandler extends ConversationTemplateViewHandler { final static int BOTTOM_MARGIN = 4; TextView sentMessage; TextView sentMessageStatus; TextView date; TextView timestamp; ImageView imageView; ConstraintLayout imageConstraintLayout; LinearLayoutCompat linearLayoutCompat; public LinearLayoutCompat messageStatusLinearLayoutCompact; LinearLayoutCompat.LayoutParams layoutParams; boolean lastKnownStateIsFailed = false; public ConversationSentViewHandler(@NonNull View itemView) { super(itemView); sentMessage = itemView.findViewById(R.id.message_sent_text); sentMessageStatus = itemView.findViewById(R.id.message_thread_sent_status_text); date = itemView.findViewById(R.id.message_thread_sent_date_text); timestamp = itemView.findViewById(R.id.sent_message_date_segment); linearLayoutCompat = itemView.findViewById(R.id.conversation_linear_layout); messageStatusLinearLayoutCompact = itemView.findViewById(R.id.conversation_status_linear_layout); // constraintLayout = itemView.findViewById(R.id.message_sent_constraint); // imageConstraintLayout = itemView.findViewById(R.id.message_sent_image_container); // imageView = itemView.findViewById(R.id.message_sent_image_view); // constraint4 = itemView.findViewById(R.id.conversation_sent_layout_container); layoutParams = (LinearLayoutCompat.LayoutParams) linearLayoutCompat.getLayoutParams(); layoutParams.bottomMargin = Helpers.dpToPixel(16); linearLayoutCompat.setLayoutParams(layoutParams); } @Override public String getMessage_id() { return this.message_id; } @Override public String getText() { return sentMessage.getText().toString(); } @Override public void setId(Long id) { this.id = id; } @Override public long getId() { return this.id; } public void bind(Conversation conversation, String searchString) { this.id = conversation.getId(); this.message_id = conversation.getMessage_id(); String timestamp = Helpers.formatDateExtended(itemView.getContext(), Long.parseLong(conversation.getDate())); DateFormat dateFormat = new SimpleDateFormat("h:mm a"); String txDate = dateFormat.format(new Date(Long.parseLong(conversation.getDate()))); this.timestamp.setText(timestamp); this.date.setText(txDate); int status = conversation.getStatus(); String statusMessage = status == Telephony.TextBasedSmsColumns.STATUS_COMPLETE ? itemView.getContext().getString(R.string.sms_status_delivered) : itemView.getContext().getString(R.string.sms_status_sent); if(status == Telephony.TextBasedSmsColumns.STATUS_PENDING ) statusMessage = itemView.getContext().getString(R.string.sms_status_sending); else if(status == Telephony.TextBasedSmsColumns.STATUS_FAILED ) { statusMessage = itemView.getContext().getString(R.string.sms_status_failed); sentMessageStatus.setVisibility(View.VISIBLE); this.date.setVisibility(View.VISIBLE); sentMessageStatus.setTextAppearance(R.style.conversation_failed); this.date.setTextAppearance(R.style.conversation_failed); lastKnownStateIsFailed = true; } else { sentMessageStatus.setTextAppearance(R.style.Theme_main); this.date.setTextAppearance(R.style.Theme_main); } if(lastKnownStateIsFailed && status != Telephony.TextBasedSmsColumns.STATUS_FAILED) { sentMessageStatus = itemView.findViewById(R.id.message_thread_sent_status_text); lastKnownStateIsFailed = false; } statusMessage = " • " + statusMessage; if(conversation.getSubscription_id() > 0) { String subscriptionName = SIMHandler.getSubscriptionName(itemView.getContext(), conversation.getSubscription_id()); if(!subscriptionName.isEmpty()) statusMessage += " • " + subscriptionName; } sentMessageStatus.setText(statusMessage); final String text = conversation.getText(); if(searchString != null && !searchString.isEmpty() && text != null) { Spannable spannable = Helpers.highlightSubstringYellow(itemView.getContext(), text, searchString, true); sentMessage.setText(spannable); } else Helpers.highlightLinks(sentMessage, text, Color.BLACK); } @Override public View getContainerLayout() { return sentMessage; } @Override public void activate() { sentMessage.setBackgroundResource(R.drawable.sent_messages_highlighted_drawable); } @Override public void deactivate() { sentMessage.setBackgroundResource(R.drawable.sent_messages_drawable); } @Override public void toggleDetails() { int visibility = this.messageStatusLinearLayoutCompact.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE; this.messageStatusLinearLayoutCompact.setVisibility(visibility); } @Override public void hideDetails() { this.messageStatusLinearLayoutCompact.setVisibility(View.GONE); } @Override public void showDetails() { this.messageStatusLinearLayoutCompact.setVisibility(View.VISIBLE); } public static class TimestampConversationSentViewHandler extends ConversationSentViewHandler { public TimestampConversationSentViewHandler(@NonNull View itemView) { super(itemView); timestamp.setVisibility(View.VISIBLE); } } public static class KeySentViewHandler extends ConversationSentViewHandler { public KeySentViewHandler(@NonNull View itemView) { super(itemView); } public void highlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_highlighted_drawable); } public void unHighlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_drawable); } @Override public void bind(Conversation conversation, String searchString) { super.bind(conversation, searchString); sentMessage.setText(itemView.getContext().getString(R.string.conversation_key_title_requested)); sentMessage.setTextAppearance(R.style.key_request_initiated); } } public static class TimestampKeySentViewHandler extends KeySentViewHandler { public TimestampKeySentViewHandler(@NonNull View itemView) { super(itemView); } } public static class TimestampKeySentStartGroupViewHandler extends TimestampConversationSentViewHandler { public TimestampKeySentStartGroupViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); sentMessage.setBackground( itemView.getContext().getDrawable(R.drawable.sent_messages_start_view_drawable)); } public void highlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_start_highlight_drawable); } public void unHighlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_start_view_drawable); } } public static class ConversationSentStartViewHandler extends ConversationSentViewHandler { public ConversationSentStartViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); sentMessage.setBackground( itemView.getContext().getDrawable(R.drawable.sent_messages_start_view_drawable)); } public void highlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_start_highlight_drawable); } public void unHighlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_start_view_drawable); } } public static class ConversationSentEndViewHandler extends ConversationSentViewHandler { public ConversationSentEndViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(16); linearLayoutCompat.setLayoutParams(layoutParams); sentMessage.setBackground( itemView.getContext().getDrawable(R.drawable.sent_messages_end_view_drawable)); } public void highlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_end_highlight_drawable); } public void unHighlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_end_view_drawable); } } public static class ConversationSentMiddleViewHandler extends ConversationSentViewHandler { public ConversationSentMiddleViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); sentMessage.setBackground( itemView.getContext().getDrawable(R.drawable.sent_messages_middle_view_drawable)); } public void highlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_middle_hightlight_drawable); } public void unHighlight() { sentMessage.setBackgroundResource(R.drawable.sent_messages_middle_view_drawable); } } }
10,793
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsReceivedViewHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ThreadedConversationsReceivedViewHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import android.view.View; import androidx.annotation.NonNull; public class ThreadedConversationsReceivedViewHandler { public static class ReceivedViewHolderReadThreadedConversations extends ThreadedConversationsTemplateViewHolder.ReadViewHolderThreadedConversations { public ReceivedViewHolderReadThreadedConversations(@NonNull View itemView) { super(itemView); } } public static class ReceivedViewHolderUnreadThreadedConversations extends ThreadedConversationsTemplateViewHolder.UnreadViewHolderThreadedConversations { public ReceivedViewHolderUnreadThreadedConversations(@NonNull View itemView) { super(itemView); } } public static class ReceivedViewHolderEncryptedUnreadThreadedConversations extends ThreadedConversationsTemplateViewHolder.UnreadEncryptedViewHolderThreadedConversations { public ReceivedViewHolderEncryptedUnreadThreadedConversations(@NonNull View itemView) { super(itemView); } } public static class ReceivedViewHolderEncryptedReadThreadedConversations extends ThreadedConversationsTemplateViewHolder.ReadEncryptedViewHolderThreadedConversations { public ReceivedViewHolderEncryptedReadThreadedConversations(@NonNull View itemView) { super(itemView); } } }
1,399
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsSentViewHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ThreadedConversationsSentViewHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import android.graphics.Typeface; import android.provider.Telephony; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.R; public class ThreadedConversationsSentViewHandler { public static class SentViewHolderReadThreadedConversations extends ThreadedConversationsTemplateViewHolder.ReadViewHolderThreadedConversations { public SentViewHolderReadThreadedConversations(@NonNull View itemView) { super(itemView); youLabel.setVisibility(View.VISIBLE); } @Override public void bind(ThreadedConversations conversation, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener, String defaultRegion) { super.bind(conversation, onClickListener, onLongClickListener, defaultRegion); if(conversation.getType() == Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT) { this.date.setText(itemView.getContext().getString(R.string.thread_conversation_type_draft)); this.date.setTextAppearance(R.style.conversation_draft_style); this.snippet.setTextAppearance(R.style.conversation_draft_style); this.youLabel.setTextAppearance(R.style.conversation_draft_style); } } } public static class SentViewHolderUnreadThreadedConversations extends ThreadedConversationsTemplateViewHolder.UnreadViewHolderThreadedConversations { public SentViewHolderUnreadThreadedConversations(@NonNull View itemView) { super(itemView); youLabel.setVisibility(View.VISIBLE); this.youLabel.setTextAppearance(R.style.conversation_unread_style); } @Override public void bind(ThreadedConversations conversation, View.OnClickListener onClickListener, View.OnLongClickListener onLongClickListener, String defaultRegion) { super.bind(conversation, onClickListener, onLongClickListener, defaultRegion); if(conversation.getType() == Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT) { this.date.setText(itemView.getContext().getString(R.string.thread_conversation_type_draft)); this.date.setTextAppearance(R.style.conversation_draft_style); this.snippet.setTextAppearance(R.style.conversation_draft_style); this.youLabel.setTextAppearance(R.style.conversation_draft_style); } } } public static class SentViewHolderEncryptedUnreadThreadedConversations extends ThreadedConversationsTemplateViewHolder.UnreadEncryptedViewHolderThreadedConversations { public SentViewHolderEncryptedUnreadThreadedConversations(@NonNull View itemView) { super(itemView); youLabel.setVisibility(View.VISIBLE); this.youLabel.setTextAppearance(R.style.conversation_unread_style); } } public static class SentViewHolderEncryptedReadThreadedConversations extends ThreadedConversationsTemplateViewHolder.ReadEncryptedViewHolderThreadedConversations { public SentViewHolderEncryptedReadThreadedConversations(@NonNull View itemView) { super(itemView); youLabel.setVisibility(View.VISIBLE); } } }
3,485
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationReceivedViewHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ConversationReceivedViewHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import android.text.Spannable; import android.util.Base64; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.widget.LinearLayoutCompat; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.SIMHandler; import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.E2EE.E2EEHandler; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.concurrent.ExecutorService; public class ConversationReceivedViewHandler extends ConversationTemplateViewHandler { TextView receivedMessage; public TextView date; TextView timestamp; LinearLayoutCompat linearLayoutCompat; LinearLayoutCompat.LayoutParams layoutParams; public ConversationReceivedViewHandler(@NonNull View itemView) { super(itemView); receivedMessage = itemView.findViewById(R.id.message_received_text); date = itemView.findViewById(R.id.message_thread_received_date_text); timestamp = itemView.findViewById(R.id.received_message_date_segment); linearLayoutCompat = itemView.findViewById(R.id.conversation_received_linear_layout); layoutParams = (LinearLayoutCompat.LayoutParams) linearLayoutCompat.getLayoutParams(); layoutParams.bottomMargin = Helpers.dpToPixel(16); linearLayoutCompat.setLayoutParams(layoutParams); } @Override public String getMessage_id() { return this.message_id; } @Override public String getText() { return receivedMessage.getText().toString(); } @Override public void setId(Long id) { this.id = id; } @Override public long getId() { return this.id; } public void bind(Conversation conversation, String searchString) { this.id = conversation.getId(); this.message_id = conversation.getMessage_id(); String timestamp = Helpers.formatDateExtended(itemView.getContext(), Long.parseLong(conversation.getDate())); DateFormat dateFormat = new SimpleDateFormat("h:mm a"); String txDate = dateFormat.format(new Date(Long.parseLong(conversation.getDate()))); final String text = conversation.getText(); if(searchString != null && !searchString.isEmpty() && text != null) { Spannable spannable = Helpers.highlightSubstringYellow(itemView.getContext(), text, searchString, false); receivedMessage.setText(spannable); } else Helpers.highlightLinks(receivedMessage, text, itemView.getContext().getColor(R.color.primary_text_color)); if(conversation.getSubscription_id() > 0) { String subscriptionName = SIMHandler.getSubscriptionName(itemView.getContext(), conversation.getSubscription_id()); if(subscriptionName != null && !subscriptionName.isEmpty()) txDate += " • " + subscriptionName; } this.timestamp.setText(timestamp); this.date.setText(txDate); } @Override public View getContainerLayout() { return receivedMessage; } @Override public void activate() { receivedMessage.setBackgroundResource(R.drawable.received_messages_highlighted_drawable); } @Override public void deactivate() { receivedMessage.setBackgroundResource(R.drawable.received_messages_drawable); } @Override public void toggleDetails() { int visibility = this.date.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE; this.date.setVisibility(visibility); } @Override public void hideDetails() { this.date.setVisibility(View.GONE); } @Override public void showDetails() { this.date.setVisibility(View.VISIBLE); } public static class TimestampConversationReceivedViewHandler extends ConversationReceivedViewHandler { public TimestampConversationReceivedViewHandler(@NonNull View itemView) { super(itemView); timestamp.setVisibility(View.VISIBLE); } } public static class KeyReceivedViewHandler extends ConversationReceivedViewHandler { public KeyReceivedViewHandler(@NonNull View itemView) { super(itemView); } @Override public void bind(Conversation conversation, String searchString) { super.bind(conversation, searchString); receivedMessage.setTextAppearance(R.style.key_request_initiated); receivedMessage.setText( itemView.getContext().getString(R.string.conversation_threads_secured_content)); } } public static class TimestampKeyReceivedViewHandler extends KeyReceivedViewHandler { public TimestampKeyReceivedViewHandler(@NonNull View itemView) { super(itemView); timestamp.setVisibility(View.VISIBLE); } } public static class TimestampKeyReceivedStartViewHandler extends TimestampConversationReceivedViewHandler { public TimestampKeyReceivedStartViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); timestamp.setVisibility(View.VISIBLE); receivedMessage.setBackground( itemView.getContext().getDrawable(R.drawable.received_mesages_start_view_drawable)); } } public static class ConversationReceivedStartViewHandler extends ConversationReceivedViewHandler { public ConversationReceivedStartViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); receivedMessage.setBackground( itemView.getContext().getDrawable(R.drawable.received_mesages_start_view_drawable)); } } public static class ConversationReceivedEndViewHandler extends ConversationReceivedViewHandler { public ConversationReceivedEndViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(16); linearLayoutCompat.setLayoutParams(layoutParams); receivedMessage.setBackground( itemView.getContext().getDrawable(R.drawable.received_messages_end_view_drawable)); } } public static class ConversationReceivedMiddleViewHandler extends ConversationReceivedViewHandler { public ConversationReceivedMiddleViewHandler(@NonNull View itemView) { super(itemView); layoutParams.bottomMargin = Helpers.dpToPixel(1); linearLayoutCompat.setLayoutParams(layoutParams); receivedMessage.setBackground( itemView.getContext().getDrawable(R.drawable.received_messages_middle_view_drawable)); } } }
7,350
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationTemplateViewHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Models/Conversations/ViewHolders/ConversationTemplateViewHandler.java
package com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public abstract class ConversationTemplateViewHandler extends RecyclerView.ViewHolder { Long id; String message_id; public ConversationTemplateViewHandler(@NonNull View itemView) { super(itemView); } public abstract String getMessage_id(); public abstract String getText(); public abstract void setId(Long id); public abstract long getId(); public abstract View getContainerLayout(); public abstract void activate(); public abstract void deactivate(); public abstract void toggleDetails(); public abstract void hideDetails(); public abstract void showDetails(); }
822
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationDao.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/DAO/ConversationDao.java
package com.afkanerd.deku.DefaultSMS.DAO; import android.provider.Telephony; import androidx.lifecycle.LiveData; import androidx.paging.DataSource; import androidx.paging.PagingLiveData; import androidx.paging.PagingSource; 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 com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import java.util.List; @Dao public interface ConversationDao { @Query("SELECT * FROM Conversation WHERE thread_id =:thread_id AND type IS NOT 3 ORDER BY date DESC") PagingSource<Integer, Conversation> get(String thread_id); @Query("SELECT * FROM Conversation WHERE thread_id =:thread_id AND type IS NOT 3 ORDER BY date DESC") List<Conversation> getDefault(String thread_id); @Query("SELECT * FROM Conversation WHERE address =:address ORDER BY date DESC") PagingSource<Integer, Conversation> getByAddress(String address); @Query("SELECT * FROM Conversation WHERE thread_id =:thread_id ORDER BY date DESC") List<Conversation> getAll(String thread_id); @Query("SELECT * FROM ( SELECT * FROM Conversation GROUP BY thread_id HAVING MAX(date)) AS " + "latest_items WHERE thread_id IS NOT NULL ORDER BY date DESC") List<Conversation> getForThreading(); @Query("SELECT * FROM Conversation ORDER BY date DESC") List<Conversation> getComplete(); @Query("SELECT * FROM Conversation WHERE type = :type AND thread_id = :threadId ORDER BY date DESC") Conversation fetchTypedConversation(int type, String threadId); // @Query("SELECT * FROM Conversation WHERE body " + // "LIKE '%' || :text || '%' ORDER BY date DESC") // PagingSource<Integer, Conversation> find(String text); @Query("SELECT * FROM Conversation WHERE message_id =:message_id") Conversation getMessage(String message_id); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(Conversation conversation); @Insert(onConflict = OnConflictStrategy.REPLACE) List<Long> insertAll(List<Conversation> conversationList); @Update int update(Conversation conversation); @Update int update(List<Conversation> conversations); @Query("DELETE FROM Conversation WHERE thread_id = :threadId") int delete(String threadId); @Query("DELETE FROM Conversation WHERE thread_id IN (:threadIds)") void deleteAll(List<String> threadIds); @Query("DELETE FROM Conversation WHERE type = :type") int deleteAllType(int type); @Query("DELETE FROM Conversation WHERE type = :type AND thread_id = :thread_id") int deleteAllType(int type, String thread_id); @Delete int delete(Conversation conversation); @Delete int delete(List<Conversation> conversation); }
2,971
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsDao.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/DAO/ThreadedConversationsDao.java
package com.afkanerd.deku.DefaultSMS.DAO; import androidx.lifecycle.LiveData; import androidx.paging.PagingSource; 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 com.afkanerd.deku.DefaultSMS.Models.Archive; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import java.util.List; @Dao public interface ThreadedConversationsDao { @Query("SELECT * FROM ThreadedConversations") LiveData<List<ThreadedConversations>> getAllLiveData(); @Query("SELECT * FROM ThreadedConversations ORDER BY date DESC") List<ThreadedConversations> getAll(); @Query("SELECT * FROM ThreadedConversations WHERE is_archived = 1 ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getArchived(); @Query("SELECT * FROM ThreadedConversations WHERE is_blocked = 1 ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getBlocked(); @Query("SELECT ThreadedConversations.thread_id FROM ThreadedConversations WHERE is_archived = 1") List<String> getArchivedList(); @Query("SELECT ThreadedConversations.thread_id FROM ThreadedConversations WHERE is_blocked = 1") List<String> getBlockedList(); @Query("SELECT * FROM ThreadedConversations WHERE is_archived = 0 AND is_blocked = 0 " + "ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getAllWithoutArchived(); @Query("SELECT * FROM ThreadedConversations WHERE is_archived = 0 AND is_read = 0 ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getAllUnreadWithoutArchived(); @Query("SELECT * FROM ThreadedConversations WHERE is_mute = 1 ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getMuted(); @Query("SELECT COUNT(Conversation.id) FROM Conversation, ThreadedConversations WHERE " + "Conversation.thread_id = ThreadedConversations.thread_id AND " + "is_archived = 0 AND read = 0") int getCountUnread(); @Query("SELECT COUNT(Conversation.id) FROM Conversation, ThreadedConversations WHERE " + "Conversation.thread_id = ThreadedConversations.thread_id AND " + "is_archived = 0 AND read = 0 AND ThreadedConversations.thread_id IN(:ids)") int getCountUnread(List<String> ids); @Query("SELECT COUNT(ConversationsThreadsEncryption.id) FROM ConversationsThreadsEncryption") int getCountEncrypted(); @Query("SELECT COUNT(ThreadedConversations.thread_id) FROM ThreadedConversations " + "WHERE is_blocked = 1") int getCountBlocked(); @Query("SELECT COUNT(ThreadedConversations.thread_id) FROM ThreadedConversations " + "WHERE is_mute = 1") int getCountMuted(); @Query("SELECT Conversation.address, " + "Conversation.text as snippet, " + "Conversation.thread_id, " + "Conversation.date, Conversation.type, Conversation.read, " + "ThreadedConversations.msg_count, ThreadedConversations.is_archived, " + "ThreadedConversations.is_blocked, ThreadedConversations.is_read, " + "ThreadedConversations.is_shortcode, ThreadedConversations.contact_name, " + "ThreadedConversations.is_mute, ThreadedConversations.is_secured " + "FROM Conversation, ThreadedConversations WHERE " + "Conversation.type = :type AND ThreadedConversations.thread_id = Conversation.thread_id " + "ORDER BY Conversation.date DESC") PagingSource<Integer, ThreadedConversations> getThreadedDrafts(int type); @Query("SELECT Conversation.address, " + "Conversation.text as snippet, " + "Conversation.thread_id, " + "Conversation.date, Conversation.type, Conversation.read, " + "0 as msg_count, ThreadedConversations.is_archived, ThreadedConversations.is_blocked, " + "ThreadedConversations.is_read, ThreadedConversations.is_shortcode, " + "ThreadedConversations.is_mute, ThreadedConversations.is_secured " + "FROM Conversation, ThreadedConversations WHERE " + "Conversation.type = :type AND ThreadedConversations.thread_id = Conversation.thread_id " + "ORDER BY Conversation.date DESC") List<ThreadedConversations> getThreadedDraftsList(int type); @Query("SELECT COUNT(ThreadedConversations.thread_id) " + "FROM Conversation, ThreadedConversations WHERE " + "Conversation.type = :type AND ThreadedConversations.thread_id = Conversation.thread_id " + "ORDER BY Conversation.date DESC") int getThreadedDraftsListCount(int type); @Query("DELETE FROM ThreadedConversations WHERE ThreadedConversations.type = :type") int deleteForType(int type); @Query("DELETE FROM Conversation WHERE Conversation.type = :type") int clearConversationType(int type); @Transaction default void clearDrafts(int type) { clearConversationType(type); deleteForType(type); } @Query("UPDATE ThreadedConversations SET is_read = :read") int updateAllRead(int read); @Query("UPDATE Conversation SET read = :read") int updateAllReadConversation(int read); @Query("UPDATE ThreadedConversations SET is_read = :read WHERE thread_id IN(:ids)") int updateAllRead(int read, List<String> ids); @Query("UPDATE ThreadedConversations SET is_read = :read WHERE thread_id = :id") int updateAllRead(int read, long id); @Query("UPDATE ThreadedConversations SET is_mute = :muted WHERE thread_id = :id") int updateMuted(int muted, String id); @Query("UPDATE ThreadedConversations SET is_mute = :muted WHERE thread_id IN(:ids)") int updateMuted(int muted, List<String> ids); @Query("UPDATE ThreadedConversations SET is_mute = 0 WHERE is_mute = 1") int updateUnMuteAll(); @Query("UPDATE Conversation SET read = :read WHERE thread_id IN(:ids)") int updateAllReadConversation(int read, List<String> ids); @Query("UPDATE Conversation SET read = :read WHERE thread_id = :id") int updateAllReadConversation(int read, long id); @Transaction default void updateRead(int read) { updateAllRead(read); updateAllReadConversation(read); } @Transaction default void updateRead(int read, List<String> ids) { updateAllRead(read, ids); updateAllReadConversation(read, ids); } @Transaction default void updateRead(int read, long id) { updateAllRead(read, id); updateAllReadConversation(read, id); } @Insert(onConflict = OnConflictStrategy.REPLACE) List<Long> insertAll(List<ThreadedConversations> threadedConversationsList); @Query("SELECT * FROM ThreadedConversations WHERE thread_id =:thread_id") ThreadedConversations get(String thread_id); @Query("SELECT * FROM ThreadedConversations WHERE thread_id IN (:threadIds)") List<ThreadedConversations> getList(List<String> threadIds); @Query("SELECT * FROM ThreadedConversations WHERE address =:address") ThreadedConversations getByAddress(String address); @Query("SELECT * FROM ThreadedConversations WHERE address IN(:addresses) AND is_archived = 0 " + "ORDER BY date DESC") PagingSource<Integer, ThreadedConversations> getByAddress(List<String> addresses); @Query("SELECT * FROM ThreadedConversations WHERE address NOT IN(:addresses)") PagingSource<Integer, ThreadedConversations> getNotInAddress(List<String> addresses); @Query("SELECT address FROM ThreadedConversations WHERE thread_id IN (:threadedConversationsList)") List<String> findAddresses(List<String> threadedConversationsList); @Query("SELECT Conversation.* FROM Conversation, ThreadedConversations WHERE text " + "LIKE '%' || :search_string || '%' AND Conversation.thread_id = ThreadedConversations.thread_id " + "GROUP BY ThreadedConversations.thread_id ORDER BY date DESC") List<Conversation> findAddresses(String search_string ); @Query("SELECT * FROM Conversation WHERE thread_id =:thread_id AND text " + "LIKE '%' || :search_string || '%' GROUP BY thread_id ORDER BY date DESC") List<Conversation> findByThread(String search_string, String thread_id); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(ThreadedConversations threadedConversations); @Update int update(ThreadedConversations threadedConversations); @Delete void delete(ThreadedConversations threadedConversations); // @Delete // void delete(List<ThreadedConversations> threadedConversations); @Query("DELETE FROM ThreadedConversations WHERE thread_id IN(:ids)") void delete(List<String> ids); @Query("DELETE FROM threadedconversations") void deleteAll(); @Update(entity = ThreadedConversations.class) void archive(List<Archive> archiveList); @Update(entity = ThreadedConversations.class) void unarchive(List<Archive> archiveList); }
9,195
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
MMSReceiverBroadcastReceiver.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/BroadcastReceivers/MMSReceiverBroadcastReceiver.java
package com.afkanerd.deku.DefaultSMS.BroadcastReceivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import com.afkanerd.deku.DefaultSMS.BuildConfig; public class MMSReceiverBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(BuildConfig.DEBUG) Log.d(getClass().getName(), "New MMS received.."); } }
486
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
IncomingTextSMSReplyActionBroadcastReceiver.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/BroadcastReceivers/IncomingTextSMSReplyActionBroadcastReceiver.java
package com.afkanerd.deku.DefaultSMS.BroadcastReceivers; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.SMS_UPDATED_BROADCAST_INTENT; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.provider.Telephony; import android.service.notification.StatusBarNotification; 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.room.Room; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Contacts; 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.BuildConfig; import com.afkanerd.deku.DefaultSMS.Models.NotificationsHandler; 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; public class IncomingTextSMSReplyActionBroadcastReceiver extends BroadcastReceiver { public static String REPLY_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".REPLY_BROADCAST_ACTION"; public static String MARK_AS_READ_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".MARK_AS_READ_BROADCAST_ACTION"; public static String MUTE_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".MUTE_BROADCAST_ACTION"; public static String REPLY_ADDRESS = "REPLY_ADDRESS"; public static String REPLY_THREAD_ID = "REPLY_THREAD_ID"; public static String REPLY_SUBSCRIPTION_ID = "REPLY_SUBSCRIPTION_ID"; // Key for the string that's delivered in the action's intent. public static final String KEY_TEXT_REPLY = "KEY_TEXT_REPLY"; Datastore databaseConnector; @Override public void onReceive(Context context, Intent intent) { if(Datastore.datastore == null || !Datastore.datastore.isOpen()) { Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(), Datastore.class, Datastore.databaseName) .enableMultiInstanceInvalidation() .build(); } databaseConnector = Datastore.datastore; if (intent.getAction() != null && intent.getAction().equals(REPLY_BROADCAST_INTENT)) { Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput != null) { String address = intent.getStringExtra(REPLY_ADDRESS); String threadId = intent.getStringExtra(REPLY_THREAD_ID); int def_subscriptionId = SIMHandler.getDefaultSimSubscription(context); int subscriptionId = intent.getIntExtra(REPLY_SUBSCRIPTION_ID, def_subscriptionId); CharSequence reply = remoteInput.getCharSequence(KEY_TEXT_REPLY); if (reply == null || reply.toString().isEmpty()) return; Conversation conversation = new Conversation(); final String messageId = String.valueOf(System.currentTimeMillis()); conversation.setAddress(address); conversation.setSubscription_id(subscriptionId); conversation.setThread_id(threadId); conversation.setText(reply.toString()); conversation.setMessage_id(messageId); conversation.setDate(String.valueOf(System.currentTimeMillis())); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_OUTBOX); conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_PENDING); ThreadingPoolExecutor.executorService.execute(new Runnable() { @Override public void run() { try { databaseConnector.conversationDao().insert(conversation); SMSDatabaseWrapper.send_text(context, conversation, null); Intent broadcastIntent = new Intent(SMS_UPDATED_BROADCAST_INTENT); broadcastIntent.putExtra(Conversation.ID, conversation.getMessage_id()); broadcastIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id()); if(intent.getExtras() != null) broadcastIntent.putExtras(intent.getExtras()); context.sendBroadcast(broadcastIntent); NotificationCompat.MessagingStyle messagingStyle = NotificationsHandler.getMessagingStyle(context, conversation, reply.toString()); Intent replyIntent = NotificationsHandler.getReplyIntent(context, conversation); PendingIntent pendingIntent = NotificationsHandler.getPendingIntent(context, conversation); NotificationCompat.Builder builder = NotificationsHandler.getNotificationBuilder(context, replyIntent, conversation, pendingIntent); builder.setStyle(messagingStyle); NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); notificationManagerCompat.notify(Integer.parseInt(threadId), builder.build()); } catch (Exception e) { e.printStackTrace(); } } }); } } else if(intent.getAction() != null && intent.getAction().equals(MARK_AS_READ_BROADCAST_INTENT)) { final String threadId = intent.getStringExtra(Conversation.THREAD_ID); final String messageId = intent.getStringExtra(Conversation.ID); try { ThreadingPoolExecutor.executorService.execute(new Runnable() { @Override public void run() { NativeSMSDB.Incoming.update_read(context, 1, threadId, null); databaseConnector.threadedConversationsDao().updateRead(1, Long.parseLong(threadId)); } }); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(Integer.parseInt(threadId)); } catch(Exception e) { e.printStackTrace(); } } else if(intent.getAction() != null && intent.getAction().equals(MUTE_BROADCAST_INTENT)) { String threadId = intent.getStringExtra(Conversation.THREAD_ID); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(Integer.parseInt(threadId)); databaseConnector.threadedConversationsDao().updateMuted(1, threadId); } } }
7,569
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
IncomingDataSMSBroadcastReceiver.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/BroadcastReceivers/IncomingDataSMSBroadcastReceiver.java
package com.afkanerd.deku.DefaultSMS.BroadcastReceivers; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.provider.Telephony; import android.util.Base64; import android.util.Log; import androidx.room.Room; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Contacts; 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.BuildConfig; import com.afkanerd.deku.DefaultSMS.Models.NotificationsHandler; import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor; import com.afkanerd.deku.E2EE.E2EEHandler; import com.google.i18n.phonenumbers.NumberParseException; //import org.bouncycastle.operator.OperatorCreationException; import org.json.JSONException; import java.io.IOException; import java.security.GeneralSecurityException; 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 IncomingDataSMSBroadcastReceiver extends BroadcastReceiver { public static String DATA_DELIVER_ACTION = BuildConfig.APPLICATION_ID + ".DATA_DELIVER_ACTION" ; public static String DATA_SENT_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".DATA_SENT_BROADCAST_INTENT"; public static String DATA_DELIVERED_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".DATA_DELIVERED_BROADCAST_INTENT"; public static String DATA_UPDATED_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".DATA_UPDATED_BROADCAST_INTENT"; ExecutorService executorService = Executors.newFixedThreadPool(4); Datastore databaseConnector; @Override public void onReceive(Context context, Intent intent) { /** * Important note: either image or dump it */ if(Datastore.datastore == null || !Datastore.datastore.isOpen()) { Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(), Datastore.class, Datastore.databaseName) .enableMultiInstanceInvalidation() .build(); } databaseConnector = Datastore.datastore; if (intent.getAction().equals(Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION)) { if (getResultCode() == Activity.RESULT_OK) { try { String[] regIncomingOutput = NativeSMSDB.Incoming.register_incoming_data(context, intent); final String threadId = regIncomingOutput[NativeSMSDB.THREAD_ID]; final String messageId = regIncomingOutput[NativeSMSDB.MESSAGE_ID]; final String data = regIncomingOutput[NativeSMSDB.BODY]; final String address = regIncomingOutput[NativeSMSDB.ADDRESS]; final String strSubscriptionId = regIncomingOutput[NativeSMSDB.SUBSCRIPTION_ID]; final String dateSent = regIncomingOutput[NativeSMSDB.DATE_SENT]; final String date = regIncomingOutput[NativeSMSDB.DATE]; int subscriptionId = Integer.parseInt(strSubscriptionId); boolean isValidKey = E2EEHandler.isValidDefaultPublicKey( Base64.decode(data, Base64.DEFAULT)); Conversation conversation = new Conversation(); conversation.setData(data); conversation.setAddress(address); conversation.setIs_key(isValidKey); conversation.setMessage_id(messageId); conversation.setThread_id(threadId); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX); conversation.setSubscription_id(subscriptionId); conversation.setDate(dateSent); conversation.setDate(date); ThreadingPoolExecutor.executorService.execute(new Runnable() { @Override public void run() { databaseConnector.conversationDao().insert(conversation); if(isValidKey) { try { processForEncryptionKey(context, conversation); } catch (NumberParseException | IOException | InterruptedException | GeneralSecurityException | JSONException e) { e.printStackTrace(); } } Intent broadcastIntent = new Intent(DATA_DELIVER_ACTION); broadcastIntent.putExtra(Conversation.ID, messageId); broadcastIntent.putExtra(Conversation.THREAD_ID, threadId); context.sendBroadcast(broadcastIntent); ThreadedConversations threadedConversations = databaseConnector.threadedConversationsDao().get(threadId); if(!threadedConversations.isIs_mute()) NotificationsHandler.sendIncomingTextMessageNotification(context, conversation); } }); } catch (IOException e) { e.printStackTrace(); } } } } void processForEncryptionKey(Context context, Conversation conversation) throws NumberParseException, GeneralSecurityException, IOException, InterruptedException, JSONException { byte[] data = Base64.decode(conversation.getData(), Base64.DEFAULT); String keystoreAlias = E2EEHandler.deriveKeystoreAlias(conversation.getAddress(), 0); byte[] extractedTransmissionKey = E2EEHandler.extractTransmissionKey(data); E2EEHandler.insertNewAgreementKeyDefault(context, extractedTransmissionKey, keystoreAlias); } }
6,416
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
IncomingTextSMSBroadcastReceiver.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/BroadcastReceivers/IncomingTextSMSBroadcastReceiver.java
package com.afkanerd.deku.DefaultSMS.BroadcastReceivers; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver.DATA_DELIVERED_BROADCAST_INTENT; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver.DATA_SENT_BROADCAST_INTENT; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingDataSMSBroadcastReceiver.DATA_UPDATED_BROADCAST_INTENT; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.provider.Telephony; import android.util.Log; import androidx.room.Room; import com.afkanerd.deku.DefaultSMS.BuildConfig; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Contacts; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ConversationHandler; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; 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.NotificationsHandler; import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor; import com.afkanerd.deku.E2EE.E2EEHandler; import com.afkanerd.deku.Router.GatewayServers.GatewayServerHandler; import com.afkanerd.deku.Router.Router.RouterItem; import com.afkanerd.deku.Router.Router.RouterHandler; import org.checkerframework.checker.units.qual.C; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class IncomingTextSMSBroadcastReceiver extends BroadcastReceiver { public static final String TAG_NAME = "RECEIVED_SMS_ROUTING"; public static final String TAG_ROUTING_URL = "swob.work.route.url,"; public static String SMS_DELIVER_ACTION = BuildConfig.APPLICATION_ID + ".SMS_DELIVER_ACTION"; public static String SMS_SENT_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".SMS_SENT_BROADCAST_INTENT"; public static String SMS_UPDATED_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".SMS_UPDATED_BROADCAST_INTENT"; public static String SMS_DELIVERED_BROADCAST_INTENT = BuildConfig.APPLICATION_ID + ".SMS_DELIVERED_BROADCAST_INTENT"; /* - address received might be different from how address is saved. - how it received is the trusted one, but won't match that which has been saved. - when message gets stored it's associated to the thread - so matching is done by android - without country code, can't know where message is coming from. Therefore best assumption is - service providers do send in country code. - How is matched to users stored without country code? */ ExecutorService executorService = Executors.newFixedThreadPool(4); Datastore databaseConnector; @Override public void onReceive(Context context, Intent intent) { if(Datastore.datastore == null || !Datastore.datastore.isOpen()) { Datastore.datastore = Room.databaseBuilder(context.getApplicationContext(), Datastore.class, Datastore.databaseName) .enableMultiInstanceInvalidation() .build(); } databaseConnector = Datastore.datastore; if (intent.getAction().equals(Telephony.Sms.Intents.SMS_DELIVER_ACTION)) { if (getResultCode() == Activity.RESULT_OK) { try { final String[] regIncomingOutput = NativeSMSDB.Incoming.register_incoming_text(context, intent); if(regIncomingOutput != null) { final String messageId = regIncomingOutput[NativeSMSDB.MESSAGE_ID]; final String body = regIncomingOutput[NativeSMSDB.BODY]; final String threadId = regIncomingOutput[NativeSMSDB.THREAD_ID]; final String address = regIncomingOutput[NativeSMSDB.ADDRESS]; final String date = regIncomingOutput[NativeSMSDB.DATE]; final String dateSent = regIncomingOutput[NativeSMSDB.DATE_SENT]; final int subscriptionId = Integer.parseInt(regIncomingOutput[NativeSMSDB.SUBSCRIPTION_ID]); insertConversation(context, address, messageId, threadId, body, subscriptionId, date, dateSent); router_activities(context, messageId); } } catch (IOException e) { e.printStackTrace(); } } } else if(intent.getAction().equals(SMS_SENT_BROADCAST_INTENT)) { executorService.execute(new Runnable() { @Override public void run() { String id = intent.getStringExtra(NativeSMSDB.ID); Conversation conversation = databaseConnector.conversationDao().getMessage(id); if(conversation == null) return; if (getResultCode() == Activity.RESULT_OK) { NativeSMSDB.Outgoing.register_sent(context, id); conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_NONE); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT); } else { try { NativeSMSDB.Outgoing.register_failed(context, id, getResultCode()); conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_FAILED); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED); conversation.setError_code(getResultCode()); } catch (Exception e) { e.printStackTrace(); } } databaseConnector.conversationDao().update(conversation); Intent broadcastIntent = new Intent(SMS_UPDATED_BROADCAST_INTENT); broadcastIntent.putExtra(Conversation.ID, conversation.getMessage_id()); broadcastIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id()); if(intent.getExtras() != null) broadcastIntent.putExtras(intent.getExtras()); context.sendBroadcast(broadcastIntent); } }); } else if(intent.getAction().equals(SMS_DELIVERED_BROADCAST_INTENT)) { executorService.execute(new Runnable() { @Override public void run() { String id = intent.getStringExtra(NativeSMSDB.ID); Conversation conversation = databaseConnector.conversationDao().getMessage(id); if(conversation == null) return; if (getResultCode() == Activity.RESULT_OK) { NativeSMSDB.Outgoing.register_delivered(context, id); conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_COMPLETE); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT); } else { conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_FAILED); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED); conversation.setError_code(getResultCode()); } databaseConnector.conversationDao().update(conversation); Intent broadcastIntent = new Intent(SMS_UPDATED_BROADCAST_INTENT); broadcastIntent.putExtra(Conversation.ID, conversation.getMessage_id()); broadcastIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id()); if(intent.getExtras() != null) broadcastIntent.putExtras(intent.getExtras()); context.sendBroadcast(broadcastIntent); } }); } else if(intent.getAction().equals(DATA_SENT_BROADCAST_INTENT)) { executorService.execute(new Runnable() { @Override public void run() { String id = intent.getStringExtra(NativeSMSDB.ID); Conversation conversation = databaseConnector.conversationDao().getMessage(id); if (getResultCode() == Activity.RESULT_OK) { conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_NONE); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT); } else { conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_FAILED); conversation.setError_code(getResultCode()); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED); } databaseConnector.conversationDao().update(conversation); Intent broadcastIntent = new Intent(DATA_UPDATED_BROADCAST_INTENT); broadcastIntent.putExtra(Conversation.ID, conversation.getMessage_id()); broadcastIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id()); context.sendBroadcast(broadcastIntent); } }); } else if(intent.getAction().equals(DATA_DELIVERED_BROADCAST_INTENT)) { executorService.execute(new Runnable() { @Override public void run() { String id = intent.getStringExtra(NativeSMSDB.ID); Conversation conversation = databaseConnector.conversationDao().getMessage(id); if (getResultCode() == Activity.RESULT_OK) { conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_COMPLETE); conversation.setType(Telephony.TextBasedSmsColumns.STATUS_COMPLETE); } else { conversation.setStatus(Telephony.TextBasedSmsColumns.STATUS_FAILED); conversation.setError_code(getResultCode()); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED); } databaseConnector.conversationDao().update(conversation); Intent broadcastIntent = new Intent(DATA_UPDATED_BROADCAST_INTENT); broadcastIntent.putExtra(Conversation.ID, conversation.getMessage_id()); broadcastIntent.putExtra(Conversation.THREAD_ID, conversation.getThread_id()); context.sendBroadcast(broadcastIntent); } }); } } public void insertThreads(Context context, Conversation conversation) { ThreadedConversations threadedConversations = ThreadedConversations.build(context, conversation); String contactName = Contacts.retrieveContactName(context, conversation.getAddress()); threadedConversations.setContact_name(contactName); databaseConnector.threadedConversationsDao().insert(threadedConversations); } public void insertConversation(Context context, String address, String messageId, String threadId, String body, int subscriptionId, String date, String dateSent) { Conversation conversation = new Conversation(); conversation.setMessage_id(messageId); conversation.setThread_id(threadId); conversation.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX); conversation.setAddress(address); conversation.setSubscription_id(subscriptionId); conversation.setDate(date); conversation.setDate_sent(dateSent); ThreadingPoolExecutor.executorService.execute(new Runnable() { @Override public void run() { String text = body; try { text = processEncryptedIncoming(context, address, body); } catch (Throwable e) { e.printStackTrace(); } conversation.setText(text); try { databaseConnector.conversationDao().insert(conversation); insertThreads(context, conversation); } catch (Exception e) { e.printStackTrace(); } Intent broadcastIntent = new Intent(SMS_DELIVER_ACTION); broadcastIntent.putExtra(Conversation.ID, messageId); context.sendBroadcast(broadcastIntent); // String defaultRegion = Helpers.getUserCountry(context); // String e16Address = Helpers.getFormatCompleteNumber(address, defaultRegion); ThreadedConversations threadedConversations = databaseConnector.threadedConversationsDao().get(threadId); if(!threadedConversations.isIs_mute()) NotificationsHandler.sendIncomingTextMessageNotification(context, conversation); } }); } public String processEncryptedIncoming(Context context, String address, String text) throws Throwable { if(E2EEHandler.isValidDefaultText(text)) { String keystoreAlias = E2EEHandler.deriveKeystoreAlias(address, 0); byte[] cipherText = E2EEHandler.extractTransmissionText(text); text = new String(E2EEHandler.decrypt(context, keystoreAlias, cipherText, null, null)); } return text; } public void router_activities(Context context, String messageId) { try { Cursor cursor = NativeSMSDB.fetchByMessageId(context, messageId); if(cursor.moveToFirst()) { GatewayServerHandler gatewayServerHandler = new GatewayServerHandler(context); RouterItem routerItem = new RouterItem(cursor); RouterHandler.route(context, routerItem, gatewayServerHandler); cursor.close(); } } catch (Exception e) { e.printStackTrace(); } } }
14,829
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
Helpers.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Commons/Helpers.java
package com.afkanerd.deku.DefaultSMS.Commons; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.Uri; import android.telephony.PhoneNumberUtils; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.BackgroundColorSpan; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.util.Base64; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.TextView; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.R; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber; import java.security.SecureRandom; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Helpers { public static Spannable highlightSubstringYellow(Context context, String text, String searchString, boolean sent) { // Find all occurrences of the substring in the text. List<Integer> startIndices = new ArrayList<>(); int index = text.toLowerCase().indexOf(searchString.toLowerCase()); while (index >= 0) { startIndices.add(index); index = text.indexOf(searchString, index + searchString.length()); } // Create a SpannableString object. SpannableString spannableString = new SpannableString(text); // Set the foreground color of the substring to yellow. BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan( context.getColor(sent ? R.color.highlight_yellow_send : R.color.highlight_yellow_received)); for (int startIndex : startIndices) { spannableString.setSpan(backgroundColorSpan, startIndex, startIndex + searchString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannableString; } public static long generateRandomNumber() { Random random = new Random(); return random.nextInt(Integer.MAX_VALUE); } public static int dpToPixel(float dpValue) { float density = Resources.getSystem().getDisplayMetrics().density; return (int) (dpValue * density); } public static int getRandomColor() { Random random = new Random(); int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); int color = r << 16 | g << 8 | b; return generateColor(color); } public static String[] convertSetToStringArray(Set<String> setOfString) { // Create String[] of size of setOfString String[] arrayOfString = new String[setOfString.size()]; // Copy elements from set to string array // using advanced for loop int index = 0; for (String str : setOfString) arrayOfString[index++] = str; // return the formed String[] return arrayOfString; } public static boolean isShortCode(ThreadedConversations threadedConversations) { if(threadedConversations.getAddress().length() < 4) return true; Pattern pattern = Pattern.compile("[a-zA-Z]"); Matcher matcher = pattern.matcher(threadedConversations.getAddress()); return !PhoneNumberUtils.isWellFormedSmsAddress(threadedConversations.getAddress()) || matcher.find(); } public static byte[] generateRandomBytes(int length) { SecureRandom random = new SecureRandom(); byte[] bytes = new byte[length]; random.nextBytes(bytes); return bytes; } public static boolean isShortCode(String address) { if(address.length() < 4) return true; Pattern pattern = Pattern.compile("[a-zA-Z]"); Matcher matcher = pattern.matcher(address); return matcher.find(); } public static String getFormatCompleteNumber(String data, String defaultRegion) { data = data.replaceAll("%2B", "+") .replaceAll("-", "") .replaceAll("%20", "") .replaceAll(" ", ""); if(data.length() < 5) return data; PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String outputNumber = data; try { Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(data, defaultRegion); long nationalNumber = phoneNumber.getNationalNumber(); long countryCode = phoneNumber.getCountryCode(); return "+" + countryCode + nationalNumber; } catch(NumberParseException e) { // e.printStackTrace(); if(e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) { data = outputNumber.replaceAll("sms[to]*:", ""); if (data.startsWith(defaultRegion)) { outputNumber = "+" + data; } else { outputNumber = "+" + defaultRegion + data; } return outputNumber; } } catch(Exception e) { e.printStackTrace(); } return data; } public static String[] getCountryNationalAndCountryCode(String data) throws NumberParseException { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(data, ""); long nationNumber = phoneNumber.getNationalNumber(); long countryCode = phoneNumber.getCountryCode(); return new String[]{String.valueOf(countryCode), String.valueOf(nationNumber)}; } public static String getFormatForTransmission(String data, String defaultRegion){ data = data.replaceAll("%2B", "+") .replaceAll("%20", "") .replaceAll("sms[to]*:", ""); // Remove any non-digit characters except the plus sign at the beginning of the string String strippedNumber = data.replaceAll("[^0-9+;]", ""); if(strippedNumber.length() > 6) { // If the stripped number starts with a plus sign followed by one or more digits, return it as is if (!strippedNumber.matches("^\\+\\d+")) { strippedNumber = "+" + defaultRegion + strippedNumber; } return strippedNumber; } // If the stripped number is not a valid phone number, return an empty string return data; } public static String getFormatNationalNumber(String data, String defaultRegion) { data = data.replaceAll("%2B", "+") .replaceAll("%20", ""); PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String outputNumber = data; try { try { Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(data, defaultRegion); return String.valueOf(phoneNumber.getNationalNumber()); } catch(NumberParseException e) { if(e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) { data = data.replaceAll("sms[to]*:", ""); if (data.startsWith(defaultRegion)) { outputNumber = "+" + data; } else { outputNumber = "+" + defaultRegion + data; } return getFormatNationalNumber(outputNumber, defaultRegion); } } } catch (Exception e) { e.printStackTrace(); } return data; } // public static String formatDateExtended(Context context, long epochTime) { // long currentTime = System.currentTimeMillis(); // long diff = currentTime - epochTime; // // Date currentDate = new Date(currentTime); // Date targetDate = new Date(epochTime); // // SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault()); // SimpleDateFormat fullDayFormat = new SimpleDateFormat("EEEE", Locale.getDefault()); // SimpleDateFormat shortDayFormat = new SimpleDateFormat("EEE", Locale.getDefault()); // SimpleDateFormat shortMonthDayFormat = new SimpleDateFormat("MMM d", Locale.getDefault()); // //// if (diff < DateUtils.HOUR_IN_MILLIS) { // less than 1 hour //// return DateUtils.getRelativeTimeSpanString(epochTime, currentTime, DateUtils.MINUTE_IN_MILLIS).toString(); //// } // if (diff < DateUtils.DAY_IN_MILLIS) { // less than 1 day // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_TIME); // } else if (isSameDay(currentDate, targetDate)) { // today // return timeFormat.format(targetDate); // } else if (isYesterday(currentDate, targetDate)) { // yesterday // return context.getString(R.string.single_message_thread_yesterday) + " • " + timeFormat.format(targetDate); // } else if (isSameWeek(currentDate, targetDate)) { // within the same week // return fullDayFormat.format(targetDate) + " • " + timeFormat.format(targetDate); // } else { // greater than 1 week // return shortDayFormat.format(targetDate) + ", " + shortMonthDayFormat.format(targetDate) // + " • " + timeFormat.format(targetDate); // } // } public static String formatDateExtended(Context context, long epochTime) { long currentTime = System.currentTimeMillis(); long diff = currentTime - epochTime; Date currentDate = new Date(currentTime); Date targetDate = new Date(epochTime); SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a", Locale.getDefault()); SimpleDateFormat fullDayFormat = new SimpleDateFormat("EEEE", Locale.getDefault()); SimpleDateFormat shortDayFormat = new SimpleDateFormat("EEE", Locale.getDefault()); SimpleDateFormat shortMonthDayFormat = new SimpleDateFormat("MMM d", Locale.getDefault()); if (isYesterday(currentDate, targetDate)) { // yesterday return context.getString(R.string.single_message_thread_yesterday) + " • " + timeFormat.format(targetDate); } else if (diff < DateUtils.DAY_IN_MILLIS) { // today return timeFormat.format(targetDate); } else if (isSameWeek(currentDate, targetDate)) { // within the same week return fullDayFormat.format(targetDate) + " • " + timeFormat.format(targetDate); } else { // greater than 1 week return shortDayFormat.format(targetDate) + ", " + shortMonthDayFormat.format(targetDate) + " • " + timeFormat.format(targetDate); } } private static boolean isSameDay(Date date1, Date date2) { SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyDDD", Locale.getDefault()); String day1 = dayFormat.format(date1); String day2 = dayFormat.format(date2); return day1.equals(day2); } private static boolean isYesterday(Date date1, Date date2) { SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyDDD", Locale.getDefault()); String day1 = dayFormat.format(date1); String day2 = dayFormat.format(date2); int dayOfYear1 = Integer.parseInt(day1.substring(4)); int dayOfYear2 = Integer.parseInt(day2.substring(4)); int year1 = Integer.parseInt(day1.substring(0, 4)); int year2 = Integer.parseInt(day2.substring(0, 4)); return (year1 == year2 && dayOfYear1 - dayOfYear2 == 1) || (year1 - year2 == 1 && dayOfYear1 == 1 && dayOfYear2 == 365); } private static boolean isSameWeek(Date date1, Date date2) { SimpleDateFormat weekFormat = new SimpleDateFormat("yyyyww", Locale.getDefault()); String week1 = weekFormat.format(date1); String week2 = weekFormat.format(date2); return week1.equals(week2); } // public static String formatDate(Context context, long epochTime) { // long currentTime = System.currentTimeMillis(); // long diff = currentTime - epochTime; // // if (diff < DateUtils.HOUR_IN_MILLIS) { // less than 1 hour // return DateUtils.getRelativeTimeSpanString(epochTime, currentTime, DateUtils.MINUTE_IN_MILLIS).toString(); // } else if (diff < DateUtils.DAY_IN_MILLIS) { // less than 1 day // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_TIME); // } else if (diff < DateUtils.WEEK_IN_MILLIS) { // less than 1 week // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY); // } else { // greater than 1 week // return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE); // } // } public static String formatDate(Context context, long epochTime) { long currentTime = System.currentTimeMillis(); long diff = currentTime - epochTime; Calendar now = Calendar.getInstance(); now.setTimeInMillis(currentTime); Calendar dateCal = Calendar.getInstance(); dateCal.setTimeInMillis(epochTime); // Check if the date is today if (dateCal.get(Calendar.YEAR) == now.get(Calendar.YEAR) && dateCal.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR)) { // Use relative time or time if less than a day if (diff < DateUtils.HOUR_IN_MILLIS) { return DateUtils.getRelativeTimeSpanString(epochTime, currentTime, DateUtils.MINUTE_IN_MILLIS).toString(); } else if (diff < DateUtils.DAY_IN_MILLIS) { return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_SHOW_TIME); } } else if (dateCal.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR) - 1) { // Show "yesterday" if the date is yesterday return context.getString(R.string.thread_conversation_timestamp_yesterday); } else { // Use standard formatting for other dates return DateUtils.formatDateTime(context, epochTime, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE); } return null; } public static String formatLongDate(long epochTime) { // Create a date object from the epoch time Date date = new Date(epochTime); // Create a SimpleDateFormat object with the desired format SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, h:mm a", Locale.getDefault()); // Format the date and return the string return formatter.format(date); } public static String getUserCountry(Context context) { String countryCode = null; // Check if network information is available ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { // Get the TelephonyManager to access network-related information TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm != null) { // Get the ISO country code from the network countryCode = tm.getNetworkCountryIso().toUpperCase(Locale.US); } } return String.valueOf(PhoneNumberUtil.getInstance().getCountryCodeForRegion(countryCode)); } public static int getColor(Context context, String input) { int sDefaultColor = context.getColor(R.color.letter_tile_default_color); if (TextUtils.isEmpty(input)) { return sDefaultColor; } TypedArray sColors = context.getResources().obtainTypedArray(R.array.letter_tile_colors); // String.hashCode() implementation is not supposed to change across java versions, so // this should guarantee the same email address always maps to the same color. // The email should already have been normalized by the ContactRequest. final int color = Math.abs(input.hashCode()) % sColors.length(); return sColors.getColor(color, sDefaultColor); } public static int generateColor(int input) { int hue; int saturation = 100; int value = 60; // Reduced value component for darker colors hue = Math.abs(input * 31 % 360); // Convert the HSV color to RGB and return the color as an int float[] hsv = {hue, saturation, value}; int color = Color.HSVToColor(hsv); return color; } public static int generateColor(String input) { int hue; int saturation = 100; int value = 60; // Reduced value component for darker colors if (input.length() == 0) { // Return a default color if the input is empty hue = 0; } else if (input.length() == 1) { // Use the first character of the input to generate the hue char firstChar = input.charAt(0); hue = Math.abs(firstChar * 31 % 360); } else { // Use the first and second characters of the input to generate the hue char firstChar = input.charAt(0); char secondChar = input.charAt(1); hue = Math.abs((firstChar + secondChar) * 31 % 360); } // Convert the HSV color to RGB and return the color as an int float[] hsv = {hue, saturation, value}; int color = Color.HSVToColor(hsv); return color; } public static boolean isBase64Encoded(String input) { try { byte[] decodedBytes = Base64.decode(input, Base64.DEFAULT); // String decodedString = new String(decodedBytes, StandardCharsets.UTF_8); String reencodedString = Base64.encodeToString(decodedBytes, Base64.DEFAULT) .replaceAll("\\n", ""); return input.replaceAll("\\n", "").equals(reencodedString); } catch (Exception e) { return false; } } public static void highlightLinks(TextView textView, String text, int color) { if(text == null) return; // Regular expression to find URLs in the text // String urlPattern = "((mailto:)?[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)" + // "|((\\+?[0-9]{1,3}?)[ \\-]?)?([\\(]{1}[0-9]{3}[\\)])?[ \\-]?[0-9]{3}[ \\-]?[0-9]{4}" + // "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*" + // "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*(/\\S*)*(\\?[^ ]*#[^ ]*)/?"; SpannableString spannableString = new SpannableString(text); String[] splitString = text.split("\\s"); for(int i=0, length =0; i<splitString.length; ++i){ final String _string = splitString[i]; length += _string.length() + 1; // one for the space removed final int start = length - _string.length()-1; final int end = length -1; if(Patterns.WEB_URL.matcher(_string).matches()) { ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse((_string.startsWith("http://") || _string.startsWith("https://")) ? _string : "https://" + _string)); intent.setFlags(FLAG_ACTIVITY_NEW_TASK); widget.getContext().startActivity(intent); } }; spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (Patterns.EMAIL_ADDRESS.matcher(_string).matches()) { ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setFlags(FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("mailto:" + _string)); widget.getContext().startActivity(intent); } }; spannableString.setSpan(clickableSpan, start, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (_string.matches( "\\(*\\+*[1-9]{0,3}\\)*-*[1-9]{0,3}[-. \\/]*\\(*[2-9]\\d{2}\\)*[-. \\/]*\\d{3}[-. \\/]*\\d{4} *e*x*t*\\.* *\\d{0,4}" + "|[*#][\\d\\*]*[*#]")) { ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { Uri phoneNumberUri = Uri.parse("tel:" + _string); Intent dialIntent = new Intent(Intent.ACTION_DIAL, phoneNumberUri); dialIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); widget.getContext().startActivity(dialIntent); } }; spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setText(spannableString); } public static boolean isSameMinute(Long date1, Long date2) { java.util.Date date = new java.util.Date(date1); Calendar currentCalendar = Calendar.getInstance(); currentCalendar.setTime(date); String previousDateString = String.valueOf(date2); java.util.Date previousDate = new java.util.Date(Long.parseLong(previousDateString)); Calendar prevCalendar = Calendar.getInstance(); prevCalendar.setTime(previousDate); return !((prevCalendar.get(Calendar.HOUR_OF_DAY) != currentCalendar.get(Calendar.HOUR_OF_DAY) || (prevCalendar.get(Calendar.MINUTE) != currentCalendar.get(Calendar.MINUTE)) || (prevCalendar.get(Calendar.DATE) != currentCalendar.get(Calendar.DATE)))); } public static boolean isSameHour(Long date1, Long date2) { java.util.Date date = new java.util.Date(date1); Calendar currentCalendar = Calendar.getInstance(); currentCalendar.setTime(date); String previousDateString = String.valueOf(date2); java.util.Date previousDate = new java.util.Date(Long.parseLong(previousDateString)); Calendar prevCalendar = Calendar.getInstance(); prevCalendar.setTime(previousDate); return !((prevCalendar.get(Calendar.HOUR_OF_DAY) != currentCalendar.get(Calendar.HOUR_OF_DAY) || (prevCalendar.get(Calendar.DATE) != currentCalendar.get(Calendar.DATE)))); } }
24,328
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
DataHelper.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/Commons/DataHelper.java
package com.afkanerd.deku.DefaultSMS.Commons; import java.nio.ByteBuffer; public class DataHelper { public static String arrayToString(int[] intArray) { StringBuilder stringBuilder = new StringBuilder(); if (intArray.length > 0) { stringBuilder.append(intArray[0]); for (int i = 1; i < intArray.length; i++) { stringBuilder.append(intArray[i]); } } return stringBuilder.toString(); } public static String byteToBinary(byte[] bytes) { String binary = ""; for(byte b: bytes) binary += Integer.toBinaryString(b); return binary; } public static int[] getNibbleFromByte(byte b) { return new int[]{(b & 0x0F), ((b >> 4) & 0x0F)}; } public static String getHexOfByte(byte[] bytes) { StringBuilder buffer = new StringBuilder(); for (byte aByte : bytes) { buffer.append(Character.forDigit((aByte >> 4) & 0xF, 16)); buffer.append(Character.forDigit((aByte & 0xF), 16)); } return buffer.toString(); } public static int[] bytesToNibbleArray(byte[] bytes) { int ints[] = new int[bytes.length * 2]; for(int i=0, j=0;i<bytes.length; ++i, j+=2) { int[] data = getNibbleFromByte(bytes[i]); ints[j] = data[0]; ints[j+1] = data[1]; } return ints; } public static byte intToByte(int data) { return (byte) (data & 0xFF); } public static byte[] intArrayToByteArray(int[] intArray) { ByteBuffer byteBuffer = ByteBuffer.allocate(intArray.length * 4); // 4 bytes per int for (int i = 0; i < intArray.length; i++) { byteBuffer.putInt(intArray[i]); } return byteBuffer.array(); } }
1,826
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationsRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ConversationsRecyclerAdapter.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.graphics.Color; import android.provider.Telephony; import android.text.Spannable; import android.text.SpannableString; import android.text.Spanned; import android.text.style.BackgroundColorSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import androidx.paging.PagingDataAdapter; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ConversationReceivedViewHandler; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ConversationSentViewHandler; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ConversationTemplateViewHandler; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.E2EE.E2EEHandler; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; public class ConversationsRecyclerAdapter extends PagingDataAdapter<Conversation, ConversationTemplateViewHandler> { public MutableLiveData<HashMap<Long, ConversationTemplateViewHandler>> mutableSelectedItems; public MutableLiveData<Conversation> retryFailedMessage = new MutableLiveData<>(); public MutableLiveData<Conversation> retryFailedDataMessage = new MutableLiveData<>(); final int MESSAGE_TYPE_INBOX = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX; final int MESSAGE_TYPE_OUTBOX = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_OUTBOX; final int MESSAGE_KEY_INBOX = 400; final int MESSAGE_START_TYPE_INBOX = 401; final int MESSAGE_MIDDLE_TYPE_INBOX = 402; final int MESSAGE_END_TYPE_INBOX = 403; final int TIMESTAMP_MESSAGE_START_TYPE_INBOX = 601; final int TIMESTAMP_MESSAGE_TYPE_INBOX = 600; final int TIMESTAMP_KEY_TYPE_INBOX = 800; final int MESSAGE_KEY_OUTBOX = 500; final int TIMESTAMP_MESSAGE_TYPE_OUTBOX = 700; final int TIMESTAMP_KEY_TYPE_OUTBOX = 900; final int TIMESTAMP_MESSAGE_START_TYPE_OUTBOX = 504; final int MESSAGE_START_TYPE_OUTBOX = 501; final int MESSAGE_MIDDLE_TYPE_OUTBOX = 502; final int MESSAGE_END_TYPE_OUTBOX = 503; public String searchString; ConversationSentViewHandler lastSentItem; ConversationReceivedViewHandler lastReceivedItem; ThreadedConversations threadedConversations; public ConversationsRecyclerAdapter(ThreadedConversations threadedConversations) { super(Conversation.DIFF_CALLBACK); this.mutableSelectedItems = new MutableLiveData<>(); this.threadedConversations = threadedConversations; // Thread thread = new Thread(new Runnable() { // @Override // public void run() { // try { // String keystoreAlias = E2EEHandler.deriveKeystoreAlias(address, 0); // secured = E2EEHandler.canCommunicateSecurely(context, keystoreAlias); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // thread.start(); // try { // thread.join(); // }catch (Exception e) { // e.printStackTrace(); // } } @NonNull @Override public ConversationTemplateViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // https://developer.android.com/reference/android/provider/Telephony.TextBasedSmsColumns#MESSAGE_TYPE_OUTBOX LayoutInflater inflater = LayoutInflater.from(parent.getContext()); ConversationTemplateViewHandler returnView; switch(viewType) { case TIMESTAMP_MESSAGE_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.TimestampConversationReceivedViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case MESSAGE_TYPE_INBOX : returnView = new ConversationReceivedViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case TIMESTAMP_MESSAGE_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.TimestampConversationSentViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; case MESSAGE_KEY_OUTBOX: View view = inflater.inflate(R.layout.conversations_sent_layout, parent, false); returnView = new ConversationSentViewHandler.KeySentViewHandler(view); break; case TIMESTAMP_KEY_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.TimestampKeySentViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; case MESSAGE_KEY_INBOX: returnView = new ConversationReceivedViewHandler.KeyReceivedViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case TIMESTAMP_KEY_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.TimestampKeyReceivedViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case TIMESTAMP_MESSAGE_START_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.TimestampKeyReceivedStartViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case MESSAGE_START_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.ConversationReceivedStartViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case MESSAGE_END_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.ConversationReceivedEndViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case MESSAGE_MIDDLE_TYPE_INBOX: returnView = new ConversationReceivedViewHandler.ConversationReceivedMiddleViewHandler( inflater.inflate(R.layout.conversations_received_layout, parent, false)); break; case TIMESTAMP_MESSAGE_START_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.TimestampKeySentStartGroupViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; case MESSAGE_START_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.ConversationSentStartViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; case MESSAGE_END_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.ConversationSentEndViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; case MESSAGE_MIDDLE_TYPE_OUTBOX: returnView = new ConversationSentViewHandler.ConversationSentMiddleViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); break; default: returnView = new ConversationSentViewHandler( inflater.inflate(R.layout.conversations_sent_layout, parent, false)); } return returnView; } @Override public void onBindViewHolder(@NonNull ConversationTemplateViewHandler holder, int position) { // Log.d(getClass().getName(), "Binding: " + holder.getAbsoluteAdapterPosition()); final Conversation conversation = getItem(position); if(conversation == null) { return; } setOnLongClickListeners(holder); setOnClickListeners(holder, conversation); if(holder instanceof ConversationReceivedViewHandler) { ConversationReceivedViewHandler conversationReceivedViewHandler = (ConversationReceivedViewHandler) holder; conversationReceivedViewHandler.bind(conversation, searchString); if(holder.getAbsoluteAdapterPosition() == 0) { if(lastReceivedItem != null) lastReceivedItem.hideDetails(); lastReceivedItem = conversationReceivedViewHandler; lastReceivedItem.date.setVisibility(View.VISIBLE); } } else if(holder instanceof ConversationSentViewHandler){ ConversationSentViewHandler conversationSentViewHandler = (ConversationSentViewHandler) holder; conversationSentViewHandler.bind(conversation, searchString); if(holder.getAbsoluteAdapterPosition() == 0 ) { if(lastSentItem != null) lastSentItem.hideDetails(); lastSentItem = conversationSentViewHandler; lastSentItem.messageStatusLinearLayoutCompact.setVisibility(View.VISIBLE); } } } private void addSelectedItems(ConversationTemplateViewHandler holder) { HashMap<Long, ConversationTemplateViewHandler> selectedItems = mutableSelectedItems.getValue(); if(selectedItems == null) selectedItems = new HashMap<>(); selectedItems.put(holder.getId(), holder); holder.itemView.setActivated(true); holder.activate(); mutableSelectedItems.setValue(selectedItems); } private void removeSelectedItems(ConversationTemplateViewHandler holder) { HashMap<Long, ConversationTemplateViewHandler> selectedItems = mutableSelectedItems.getValue(); if(selectedItems != null) { selectedItems.remove(holder.getId()); holder.itemView.setActivated(false); holder.deactivate(); mutableSelectedItems.setValue(selectedItems); } } private void setOnClickListeners(ConversationTemplateViewHandler holder, Conversation conversation) { holder.getContainerLayout().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mutableSelectedItems != null && mutableSelectedItems.getValue() != null) { if(mutableSelectedItems.getValue().containsKey(holder.getId())) { Log.d(getClass().getName(), "Removing item"); removeSelectedItems(holder); } else if(!mutableSelectedItems.getValue().isEmpty()){ addSelectedItems(holder); } } else if(conversation.getStatus() == Telephony.TextBasedSmsColumns.STATUS_FAILED) { if(conversation.getData() != null) retryFailedDataMessage.setValue(conversation); else retryFailedMessage.setValue(conversation); } else { holder.toggleDetails(); } } }); } private void setOnLongClickListeners(ConversationTemplateViewHandler holder) { holder.getContainerLayout().setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if(holder.itemView.isActivated()) { removeSelectedItems(holder); } else { addSelectedItems(holder); } return true; } }); } @Override public int getItemViewType(int position) { Conversation conversation = peek(position); if(conversation == null) return super.getItemViewType(position); int oldestItemPos = snapshot().getSize() - 1; int newestItemPos = 0; if(conversation.isIs_key()) { if(position == oldestItemPos || snapshot().size() < 2 || (position > (oldestItemPos -1) && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(peek(position -1).getDate())))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_KEY_TYPE_INBOX : TIMESTAMP_KEY_TYPE_OUTBOX; } else { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_KEY_INBOX : MESSAGE_KEY_OUTBOX; } } if(snapshot().getSize() < 2) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_TYPE_INBOX : TIMESTAMP_MESSAGE_TYPE_OUTBOX; } if(position == oldestItemPos) { // - minus Conversation secondMessage = (Conversation) peek(position - 1); if(conversation.getType() == secondMessage.getType() && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { Log.d(getClass().getName(), "Yes oldest timestamp"); return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_START_TYPE_INBOX : TIMESTAMP_MESSAGE_START_TYPE_OUTBOX; } else { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_TYPE_INBOX : TIMESTAMP_MESSAGE_TYPE_OUTBOX; } } if(position > 0) { Conversation secondMessage = (Conversation) peek(position + 1); Conversation thirdMessage = (Conversation) peek(position - 1); if(secondMessage == null || thirdMessage == null) return super.getItemViewType(position); if(!Helpers.isSameHour(Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { if(conversation.getType() == thirdMessage.getType() && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(thirdMessage.getDate()))) return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_START_TYPE_INBOX : TIMESTAMP_MESSAGE_START_TYPE_OUTBOX; else return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_TYPE_INBOX : TIMESTAMP_MESSAGE_TYPE_OUTBOX; } if(conversation.getType() == thirdMessage.getType() && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(thirdMessage.getDate()))) { if(conversation.getType() != secondMessage.getType() || !Helpers.isSameMinute( Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_START_TYPE_INBOX : MESSAGE_START_TYPE_OUTBOX; } } if(conversation.getType() == secondMessage.getType() && conversation.getType() == thirdMessage.getType()) { if(Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate())) && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(thirdMessage.getDate()))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_MIDDLE_TYPE_INBOX : MESSAGE_MIDDLE_TYPE_OUTBOX; } } if(conversation.getType() == secondMessage.getType() && Helpers.isSameMinute(Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { if(conversation.getType() != thirdMessage.getType() || !Helpers.isSameMinute( Long.parseLong(conversation.getDate()), Long.parseLong(thirdMessage.getDate()))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_END_TYPE_INBOX : MESSAGE_END_TYPE_OUTBOX; } } } if(position == newestItemPos) { // - minus Conversation secondMessage = (Conversation) peek(position + 1); if(secondMessage == null) return super.getItemViewType(position); if(!Helpers.isSameHour(Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? TIMESTAMP_MESSAGE_TYPE_INBOX : TIMESTAMP_MESSAGE_TYPE_OUTBOX; } if(conversation.getType() == secondMessage.getType() && Helpers.isSameMinute( Long.parseLong(conversation.getDate()), Long.parseLong(secondMessage.getDate()))) { return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_END_TYPE_INBOX : MESSAGE_END_TYPE_OUTBOX; } } return (conversation.getType() == MESSAGE_TYPE_INBOX) ? MESSAGE_TYPE_INBOX : MESSAGE_TYPE_OUTBOX; } public void resetAllSelectedItems() { for(Map.Entry<Long, ConversationTemplateViewHandler> entry : mutableSelectedItems.getValue().entrySet()) { entry.getValue().itemView.setActivated(false); entry.getValue().deactivate(); notifyItemChanged(entry.getValue().getAbsoluteAdapterPosition()); } mutableSelectedItems.setValue(null); } public void getForce(int position) { getItem(position); } public void resetSearchItems(List<Integer> positions) { if(positions != null) for(Integer position : positions) { notifyItemChanged(position); } } }
18,705
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ContactsRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ContactsRecyclerAdapter.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.AsyncListDiffer; import androidx.recyclerview.widget.RecyclerView; 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.Models.Conversations.ViewHolders.ThreadedConversationsTemplateViewHolder; import com.afkanerd.deku.DefaultSMS.ConversationActivity; import com.afkanerd.deku.DefaultSMS.R; import java.util.List; public class ContactsRecyclerAdapter extends RecyclerView.Adapter{ Context context; String sharedMessage; private final AsyncListDiffer<Contacts> mDiffer = new AsyncListDiffer(this, Contacts.DIFF_CALLBACK); public ContactsRecyclerAdapter(Context context) { this.context = context; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(this.context); View view = inflater.inflate(R.layout.conversations_threads_layout, parent, false); return new ContactsViewHolderThreadedConversations(view, true); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { Contacts contacts = mDiffer.getCurrentList().get(holder.getAbsoluteAdapterPosition()); ContactsViewHolderThreadedConversations viewHolder = (ContactsViewHolderThreadedConversations) holder; viewHolder.bind(contacts, sharedMessage); } public void setSharedMessage(String sharedMessage) { this.sharedMessage = sharedMessage; } @Override public int getItemCount() { return mDiffer.getCurrentList().size(); } public void submitList(List<Contacts> contactsList) { mDiffer.submitList(contactsList); } public static class ContactsViewHolderThreadedConversations extends ThreadedConversationsTemplateViewHolder { View itemView; public ContactsViewHolderThreadedConversations(@NonNull View itemView, boolean isContact) { super(itemView); this.itemView = itemView; snippet.setMaxLines(1); address.setMaxLines(1); date.setVisibility(View.GONE); contactAvatar.setVisibility(View.GONE); } public void bind(Contacts contacts, final String sharedConversation) { // final int color = Helpers.generateColor(contacts.contactName); int color = Helpers.getColor(itemView.getContext(), contacts.number); address.setText(contacts.contactName); contactInitials.setAvatarInitials(contacts.contactName.substring(0, 1)); contactInitials.setAvatarInitialsBackgroundColor(color); snippet.setText(contacts.number); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent singleMessageThreadIntent = new Intent(itemView.getContext(), ConversationActivity.class); singleMessageThreadIntent.putExtra(Conversation.ADDRESS, contacts.number); if(sharedConversation != null && !sharedConversation.isEmpty()) singleMessageThreadIntent.putExtra(Conversation.SHARED_SMS_BODY, sharedConversation); itemView.getContext().startActivity(singleMessageThreadIntent); } }); } } }
3,785
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ThreadedConversationRecyclerAdapter.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.content.Intent; import android.provider.Telephony; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.lifecycle.MutableLiveData; import androidx.paging.PagingDataAdapter; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; 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.Conversations.ViewHolders.ThreadedConversationsReceivedViewHandler; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ThreadedConversationsSentViewHandler; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ViewHolders.ThreadedConversationsTemplateViewHolder; import com.afkanerd.deku.DefaultSMS.ConversationActivity; import com.afkanerd.deku.DefaultSMS.R; import java.util.HashMap; public class ThreadedConversationRecyclerAdapter extends PagingDataAdapter<ThreadedConversations, ThreadedConversationsTemplateViewHolder> { public String searchString = ""; public MutableLiveData<HashMap<Long, ThreadedConversationsTemplateViewHolder>> selectedItems = new MutableLiveData<>(); public final static int RECEIVED_VIEW_TYPE = 1; public final static int RECEIVED_UNREAD_VIEW_TYPE = 2; public final static int RECEIVED_ENCRYPTED_UNREAD_VIEW_TYPE = 3; public final static int SENT_VIEW_TYPE = 5; public final static int SENT_UNREAD_VIEW_TYPE = 6; public final static int SENT_ENCRYPTED_UNREAD_VIEW_TYPE = 7; public final static int SENT_ENCRYPTED_VIEW_TYPE = 8; ThreadedConversationsDao threadedConversationsDao; public ThreadedConversationRecyclerAdapter() { super(ThreadedConversations.DIFF_CALLBACK); } public ThreadedConversationRecyclerAdapter(ThreadedConversationsDao threadedConversationsDao) { super(ThreadedConversations.DIFF_CALLBACK); this.threadedConversationsDao = threadedConversationsDao; } @NonNull @Override public ThreadedConversationsTemplateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.conversations_threads_layout, parent, false); // View view = viewCacheExtension.getViewForPositionAndType(parent, 0, viewType); if(viewType == (RECEIVED_UNREAD_VIEW_TYPE)) return new ThreadedConversationsReceivedViewHandler.ReceivedViewHolderUnreadThreadedConversations(view); else if(viewType == (SENT_UNREAD_VIEW_TYPE)) return new ThreadedConversationsSentViewHandler.SentViewHolderUnreadThreadedConversations(view); else if(viewType == (RECEIVED_ENCRYPTED_UNREAD_VIEW_TYPE )) return new ThreadedConversationsReceivedViewHandler.ReceivedViewHolderEncryptedUnreadThreadedConversations(view); else if(viewType == (SENT_ENCRYPTED_UNREAD_VIEW_TYPE )) return new ThreadedConversationsSentViewHandler.SentViewHolderEncryptedUnreadThreadedConversations(view); else if(viewType == (RECEIVED_VIEW_TYPE)) return new ThreadedConversationsReceivedViewHandler.ReceivedViewHolderReadThreadedConversations(view); else if(viewType == (SENT_VIEW_TYPE)) return new ThreadedConversationsSentViewHandler.SentViewHolderReadThreadedConversations(view); else if(viewType == (SENT_ENCRYPTED_VIEW_TYPE)) return new ThreadedConversationsSentViewHandler.SentViewHolderEncryptedReadThreadedConversations(view); return new ThreadedConversationsReceivedViewHandler.ReceivedViewHolderEncryptedReadThreadedConversations(view); } @Override public int getItemViewType(int position) { return ThreadedConversationsTemplateViewHolder.getViewType(position, snapshot().getItems()); } @Override public void onBindViewHolder(@NonNull ThreadedConversationsTemplateViewHolder holder, int position) { ThreadedConversations threadedConversations = getItem(position); if(threadedConversations == null) return; String threadId = String.valueOf(threadedConversations.getThread_id()); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { HashMap<Long, ThreadedConversationsTemplateViewHolder> _selectedItems = selectedItems.getValue(); if(_selectedItems != null) { if(_selectedItems.containsKey(Long.parseLong(holder.id))) { ThreadedConversationsTemplateViewHolder templateViewHolder = _selectedItems.remove(Long.parseLong(holder.id)); selectedItems.setValue(_selectedItems); if(templateViewHolder != null) templateViewHolder.unHighlight(); return; } else if(!_selectedItems.isEmpty()){ _selectedItems.put(Long.valueOf(holder.id), holder); selectedItems.setValue(_selectedItems); holder.highlight(); return; } } Intent singleMessageThreadIntent = new Intent(holder.itemView.getContext(), ConversationActivity.class); singleMessageThreadIntent.putExtra(Conversation.THREAD_ID, threadId); holder.itemView.getContext().startActivity(singleMessageThreadIntent); } }; // View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { HashMap<Long, ThreadedConversationsTemplateViewHolder> _selectedItems = selectedItems.getValue() == null ? new HashMap<>() : selectedItems.getValue(); _selectedItems.put(Long.valueOf(holder.id), holder); selectedItems.setValue(_selectedItems); holder.highlight(); return true; } }; String defaultRegion = Helpers.getUserCountry(holder.itemView.getContext()); holder.bind(threadedConversations, onClickListener, onLongClickListener, defaultRegion); } public void resetAllSelectedItems() { HashMap<Long, ThreadedConversationsTemplateViewHolder> items = selectedItems.getValue(); if(items != null) { for(ThreadedConversationsTemplateViewHolder viewHolder : items.values()){ viewHolder.unHighlight(); } } selectedItems.setValue(null); } }
6,970
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ThreadedConversationsViewModel.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.database.Cursor; import android.provider.BlockedNumberContract; import android.provider.Telephony; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import androidx.paging.Pager; import androidx.paging.PagingConfig; import androidx.paging.PagingData; import androidx.paging.PagingLiveData; import androidx.paging.PagingSource; import com.afkanerd.deku.DefaultSMS.Models.Archive; import com.afkanerd.deku.DefaultSMS.Models.Contacts; 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.SMSDatabaseWrapper; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryption; import com.afkanerd.deku.E2EE.E2EEHandler; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.List; public class ThreadedConversationsViewModel extends ViewModel { int pageSize = 20; int prefetchDistance = 3 * pageSize; boolean enablePlaceholder = false; int initialLoadSize = 2 * pageSize; int maxSize = PagingConfig.MAX_SIZE_UNBOUNDED; public Datastore databaseConnector; public LiveData<PagingData<ThreadedConversations>> getArchived(){ Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getArchived()); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public LiveData<PagingData<ThreadedConversations>> getDrafts(){ Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getThreadedDrafts( Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT)); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public LiveData<PagingData<ThreadedConversations>> getBlocked(){ Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getBlocked()); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public LiveData<PagingData<ThreadedConversations>> getMuted(){ Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getMuted()); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } PagingSource<Integer, ThreadedConversations> mutedPagingSource; public LiveData<PagingData<ThreadedConversations>> getUnread(){ Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getAllUnreadWithoutArchived()); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public LiveData<PagingData<ThreadedConversations>> get(){ try { Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize, maxSize ), ()-> databaseConnector.threadedConversationsDao().getAllWithoutArchived()); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } catch(Exception e) { e.printStackTrace(); } return null; } public String getAllExport() { List<Conversation> conversations = databaseConnector.conversationDao().getComplete(); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting().serializeNulls(); Gson gson = gsonBuilder.create(); return gson.toJson(conversations); } public LiveData<PagingData<ThreadedConversations>> getEncrypted() throws InterruptedException { List<String> address = new ArrayList<>(); Thread thread = new Thread(new Runnable() { @Override public void run() { List<ConversationsThreadsEncryption> conversationsThreadsEncryptionList = Datastore.datastore.conversationsThreadsEncryptionDao().getAll(); for(ConversationsThreadsEncryption conversationsThreadsEncryption : conversationsThreadsEncryptionList) { String derivedAddress = E2EEHandler.getAddressFromKeystore( conversationsThreadsEncryption.getKeystoreAlias()); address.add(derivedAddress); } } }); thread.start(); thread.join(); Pager<Integer, ThreadedConversations> pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize ), ()-> databaseConnector.threadedConversationsDao().getByAddress(address)); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public void insert(ThreadedConversations threadedConversations) { databaseConnector.threadedConversationsDao().insert(threadedConversations); } public void reset(Context context) { Cursor cursor = NativeSMSDB.fetchAll(context); List<Conversation> conversationList = new ArrayList<>(); if(cursor != null && cursor.moveToFirst()) { do { conversationList.add(Conversation.build(cursor)); } while(cursor.moveToNext()); cursor.close(); } databaseConnector.conversationDao().insertAll(conversationList); databaseConnector.threadedConversationsDao().deleteAll(); refresh(context); } public void archive(List<Archive> archiveList) { databaseConnector.threadedConversationsDao().archive(archiveList); } public void delete(Context context, List<String> ids) { databaseConnector.conversationDao().deleteAll(ids); databaseConnector.threadedConversationsDao().delete(ids); NativeSMSDB.deleteThreads(context, ids.toArray(new String[0])); } private void refresh(Context context) { List<ThreadedConversations> newThreadedConversationsList = new ArrayList<>(); Cursor cursor = context.getContentResolver().query( Telephony.Threads.CONTENT_URI, null, null, null, "date DESC" ); List<ThreadedConversations> threadedDraftsList = databaseConnector.threadedConversationsDao().getThreadedDraftsList( Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT); List<String> archivedThreads = databaseConnector.threadedConversationsDao().getArchivedList(); List<String> threadsIdsInDrafts = new ArrayList<>(); for(ThreadedConversations threadedConversations : threadedDraftsList) threadsIdsInDrafts.add(threadedConversations.getThread_id()); /* [date, rr, sub, subject, ct_t, read_status, reply_path_present, body, type, msg_box, thread_id, sub_cs, resp_st, retr_st, text_only, locked, exp, m_id, retr_txt_cs, st, date_sent, read, ct_cls, m_size, rpt_a, address, sub_id, pri, tr_id, resp_txt, ct_l, m_cls, d_rpt, v, person, service_center, error_code, _id, m_type, status] */ List<ThreadedConversations> threadedConversationsList = databaseConnector.threadedConversationsDao().getAll(); if(cursor != null && cursor.moveToFirst()) { do { ThreadedConversations threadedConversations = new ThreadedConversations(); int recipientIdIndex = cursor.getColumnIndex("address"); int snippetIndex = cursor.getColumnIndex("body"); int dateIndex = cursor.getColumnIndex("date"); int threadIdIndex = cursor.getColumnIndex("thread_id"); int typeIndex = cursor.getColumnIndex("type"); int readIndex = cursor.getColumnIndex("read"); threadedConversations.setIs_read(cursor.getInt(readIndex) == 1); threadedConversations.setAddress(cursor.getString(recipientIdIndex)); if(threadedConversations.getAddress() == null || threadedConversations.getAddress().isEmpty()) continue; threadedConversations.setThread_id(cursor.getString(threadIdIndex)); if(threadsIdsInDrafts.contains(threadedConversations.getThread_id())) { ThreadedConversations tc = threadedDraftsList.get( threadsIdsInDrafts.indexOf(threadedConversations.getThread_id())); threadedConversations.setSnippet(tc.getSnippet()); threadedConversations.setType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT); threadedConversations.setDate( Long.parseLong(tc.getDate()) > Long.parseLong(cursor.getString(dateIndex)) ? tc.getDate() : cursor.getString(dateIndex)); } else { threadedConversations.setSnippet(cursor.getString(snippetIndex)); threadedConversations.setType(cursor.getInt(typeIndex)); threadedConversations.setDate(cursor.getString(dateIndex)); } if(BlockedNumberContract.isBlocked(context, threadedConversations.getAddress())) threadedConversations.setIs_blocked(true); threadedConversations.setIs_archived( archivedThreads.contains(threadedConversations.getThread_id())); String contactName = Contacts.retrieveContactName(context, threadedConversations.getAddress()); threadedConversations.setContact_name(contactName); /** * Check things that change first * - Read status * - Drafts */ if(!threadedConversationsList.contains(threadedConversations)) { newThreadedConversationsList.add(threadedConversations); } } while(cursor.moveToNext()); cursor.close(); } databaseConnector.threadedConversationsDao().insertAll(newThreadedConversationsList); getCount(context); } public void unarchive(List<Archive> archiveList) { databaseConnector.threadedConversationsDao().unarchive(archiveList); } public void unblock(Context context, List<String> threadIds) { List<ThreadedConversations> threadedConversationsList = databaseConnector.threadedConversationsDao().getList(threadIds); for(ThreadedConversations threadedConversations : threadedConversationsList) { BlockedNumberContract.unblock(context, threadedConversations.getAddress()); } refresh(context); } public void clearDrafts(Context context) { SMSDatabaseWrapper.deleteAllDraft(context); databaseConnector.threadedConversationsDao() .clearDrafts(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT); refresh(context); } public boolean hasUnread(List<String> ids) { return databaseConnector.threadedConversationsDao().getCountUnread(ids) > 0; } public void markUnRead(Context context, List<String> threadIds) { NativeSMSDB.Incoming.update_all_read(context, 0, threadIds.toArray(new String[0])); databaseConnector.threadedConversationsDao().updateRead(0, threadIds); refresh(context); } public void markRead(Context context, List<String> threadIds) { NativeSMSDB.Incoming.update_all_read(context, 1, threadIds.toArray(new String[0])); databaseConnector.threadedConversationsDao().updateRead(1, threadIds); refresh(context); } public void markAllRead(Context context) { NativeSMSDB.Incoming.update_all_read(context, 1); databaseConnector.threadedConversationsDao().updateRead(1); refresh(context); } public MutableLiveData<List<Integer>> folderMetrics = new MutableLiveData<>(); public void getCount(Context context) { int draftsListCount = databaseConnector.threadedConversationsDao() .getThreadedDraftsListCount( Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT); int encryptedCount = databaseConnector.threadedConversationsDao().getCountEncrypted(); int unreadCount = databaseConnector.threadedConversationsDao().getCountUnread(); int blockedCount = databaseConnector.threadedConversationsDao().getCountBlocked(); int mutedCount = databaseConnector.threadedConversationsDao().getCountMuted(); List<Integer> list = new ArrayList<>(); list.add(draftsListCount); list.add(encryptedCount); list.add(unreadCount); list.add(blockedCount); list.add(mutedCount); folderMetrics.postValue(list); } public void unMute(List<String> threadIds) { databaseConnector.threadedConversationsDao().updateMuted(0, threadIds); } public void mute(List<String> threadIds) { databaseConnector.threadedConversationsDao().updateMuted(1, threadIds); } public void unMuteAll() { databaseConnector.threadedConversationsDao().updateUnMuteAll(); } }
14,792
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationPagingSource.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ConversationPagingSource.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.provider.Telephony; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.paging.PagingSource; import androidx.paging.PagingState; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryption; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryptionDao; import com.afkanerd.deku.E2EE.E2EEHandler; import com.google.i18n.phonenumbers.NumberParseException; import java.util.ArrayList; import java.util.List; import kotlin.coroutines.Continuation; public class ConversationPagingSource extends PagingSource<Integer, Conversation> { String threadId; ConversationDao conversationDao; Integer initialKey; Context context; public ConversationPagingSource(Context context, ConversationDao conversationDao, String threadId, Integer initialKey) { this.conversationDao = conversationDao; this.threadId = threadId; this.initialKey = initialKey; this.context = context; } @Nullable @Override public Integer getRefreshKey(@NonNull PagingState<Integer, Conversation> state) { // Try to find the page key of the closest page to anchorPosition from // either the prevKey or the nextKey; you need to handle nullability // here. // * prevKey == null -> anchorPage is the first page. // * nextKey == null -> anchorPage is the last page. // * both prevKey and nextKey are null -> anchorPage is the // initial page, so return null. // Integer anchorPosition = state.getAnchorPosition(); Integer anchorPosition = initialKey; if (anchorPosition == null) { anchorPosition = state.getAnchorPosition(); if(anchorPosition == null) return null; } LoadResult.Page<Integer, Conversation> anchorPage = state.closestPageToPosition(anchorPosition); if (anchorPage == null) { return null; } Integer prevKey = anchorPage.getPrevKey(); if (prevKey != null) { return prevKey + 1; } Integer nextKey = anchorPage.getNextKey(); if (nextKey != null) { return nextKey - 1; } return null; } @Nullable @Override public LoadResult<Integer, Conversation> load( @NonNull LoadParams<Integer> loadParams, @NonNull Continuation<? super LoadResult<Integer, Conversation>> continuation) { final List<Conversation>[] list = new List[]{new ArrayList<>()}; Thread thread = new Thread(new Runnable() { @Override public void run() { list[0] = conversationDao.getDefault(threadId); // /** // * Decrypt encrypted messages using their key // */ // String address = ""; // if(list[0].size() > 0) // address = list[0].get(0).getAddress(); // for(int i=0;i<list[0].size(); ++i) { // try { // if ((list[0].get(i).getType() == // Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT || // list[0].get(i).getType() == // Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED ) && // E2EEHandler.isValidDefaultText(list[0].get(i).getText())) { // try { // byte[] cipherText = // E2EEHandler.extractTransmissionText(list[0].get(i).getText()); // byte[] mk = Base64.decode(list[0].get(i).get_mk(), Base64.NO_WRAP); // // String keystoreAlias = E2EEHandler.deriveKeystoreAlias( address, // 0); // // ConversationsThreadsEncryption conversationsThreadsEncryption = // new ConversationsThreadsEncryption(); // ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao = // conversationsThreadsEncryption.getDaoInstance(context); // conversationsThreadsEncryption = // conversationsThreadsEncryptionDao.findByKeystoreAlias(keystoreAlias); // // byte[] AD = Base64.decode(conversationsThreadsEncryption.getPublicKey(), // Base64.NO_WRAP); // // list[0].get(i).setText(new String(E2EEHandler.decrypt(context, // keystoreAlias, cipherText, mk, AD))); // } catch (Throwable e) { // e.printStackTrace(); // } // } // } catch(Exception e) { // e.printStackTrace(); // } // } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return new LoadResult.Page<>(list[0], null, null, LoadResult.Page.COUNT_UNDEFINED, LoadResult.Page.COUNT_UNDEFINED); } }
5,778
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
SearchConversationRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/SearchConversationRecyclerAdapter.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.AsyncListDiffer; 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.Models.Conversations.ViewHolders.ThreadedConversationsTemplateViewHolder; public class SearchConversationRecyclerAdapter extends ThreadedConversationRecyclerAdapter { public Integer searchIndex; public final AsyncListDiffer<ThreadedConversations> mDiffer = new AsyncListDiffer(this, ThreadedConversations.DIFF_CALLBACK); public SearchConversationRecyclerAdapter() { super(); } @Override public int getItemCount() { return mDiffer.getCurrentList().size(); } @Override public int getItemViewType(int position) { return ThreadedConversationsTemplateViewHolder.getViewType(position, mDiffer.getCurrentList()); } @Override public void onBindViewHolder(@NonNull ThreadedConversationsTemplateViewHolder holder, int position) { // super.onBindViewHolder(holder, position); ThreadedConversations threadedConversations = mDiffer.getCurrentList().get(position); if(threadedConversations == null) return; String threadId = threadedConversations.getThread_id(); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { Intent singleMessageThreadIntent = new Intent(holder.itemView.getContext(), ConversationActivity.class); singleMessageThreadIntent.putExtra(Conversation.THREAD_ID, threadId); singleMessageThreadIntent.putExtra(ConversationActivity.SEARCH_STRING, searchString); singleMessageThreadIntent.putExtra(ConversationActivity.SEARCH_INDEX, searchIndex); singleMessageThreadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); holder.itemView.getContext().startActivity(singleMessageThreadIntent); } }; View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { return false; } }; String defaultRegion = Helpers.getUserCountry(holder.itemView.getContext()); holder.bind(threadedConversations, onClickListener, onLongClickListener, defaultRegion); } }
2,798
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ContactsViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ContactsViewModel.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.telephony.PhoneNumberUtils; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.afkanerd.deku.DefaultSMS.Models.Contacts; import com.google.i18n.phonenumbers.NumberParseException; import java.util.ArrayList; import java.util.List; public class ContactsViewModel extends ViewModel { Context context; MutableLiveData<List<Contacts>> contactsMutableLiveData; public MutableLiveData<List<Contacts>> getContacts(Context context) { this.context = context; if(contactsMutableLiveData == null) { contactsMutableLiveData = new MutableLiveData<>(); loadContacts(); } return contactsMutableLiveData; } public void filterContact(String details) throws NumberParseException { List<Contacts> contactsList = new ArrayList<>(); if(details.isEmpty()) { loadContacts(); return; } Cursor cursor = Contacts.filterContacts(context, details); if(cursor.moveToFirst()) { do { int idIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone._ID); int displayNameIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); int numberIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER); String displayName = String.valueOf(cursor.getString(displayNameIndex)); long id = cursor.getLong(idIndex); String number = String.valueOf(cursor.getString(numberIndex)); contactsList.add(new Contacts(context, id, displayName, number)); } while(cursor.moveToNext()); } cursor.close(); if(contactsList.isEmpty() && PhoneNumberUtils.isWellFormedSmsAddress(details)) { Contacts contacts = new Contacts(); contacts.contactName = "Send to " + details; contacts.number = details; contacts.type = Contacts.TYPE_NEW_CONTACT; contactsList.add(contacts); } contactsMutableLiveData.postValue(contactsList); } public void loadContacts(){ Cursor cursor = Contacts.getPhonebookContacts(context); List<Contacts> contactsList = new ArrayList<>(); if(cursor.moveToFirst()) { do { int idIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone._ID); int displayNameIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); int numberIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER); String displayName = String.valueOf(cursor.getString(displayNameIndex)); long id = cursor.getLong(idIndex); String number = String.valueOf(cursor.getString(numberIndex)); contactsList.add(new Contacts(context, id, displayName, number)); } while(cursor.moveToNext()); } cursor.close(); contactsMutableLiveData.postValue(contactsList); } }
3,340
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationsViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/ConversationsViewModel.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.database.Cursor; import android.provider.Telephony; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; import androidx.paging.Pager; import androidx.paging.PagingConfig; import androidx.paging.PagingData; import androidx.paging.PagingLiveData; import androidx.paging.PagingSource; 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.SMSDatabaseWrapper; import java.util.ArrayList; import java.util.List; public class ConversationsViewModel extends ViewModel { public Datastore datastore; public String threadId; public String address; public int pageSize = 10; int prefetchDistance = 3 * pageSize; boolean enablePlaceholder = false; int initialLoadSize = pageSize * 2; public Integer initialKey = null; List<Integer> positions = new ArrayList<>(); int pointer = 0; Pager<Integer, Conversation> pager; public LiveData<PagingData<Conversation>> getSearch(Context context, String threadId, List<Integer> positions) { int pageSize = 5; int prefetchDistance = 3 * pageSize; boolean enablePlaceholder = false; int initialLoadSize = 10; this.threadId = threadId; this.positions = positions; pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize ), initialKey, ()-> getNewConversationPagingSource(context)); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } PagingSource<Integer, Conversation> customPagingSource; public PagingSource<Integer, Conversation> getNewConversationPagingSource(Context context) { customPagingSource = new ConversationPagingSource(context, datastore.conversationDao(), threadId, pointer >= this.positions.size()-1 ? null : this.positions.get(++pointer)); return customPagingSource; } public LiveData<PagingData<Conversation>> get(String threadId) throws InterruptedException { this.threadId = threadId; pager = new Pager<>(new PagingConfig( pageSize, prefetchDistance, enablePlaceholder, initialLoadSize ), null, ()->datastore.conversationDao().get(threadId)); return PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), this); } public Conversation fetch(String messageId) throws InterruptedException { return datastore.conversationDao().getMessage(messageId); } public long insert(Context context, Conversation conversation) throws InterruptedException { long id = datastore.conversationDao().insert(conversation); ThreadedConversations threadedConversations = ThreadedConversations.build(context, conversation); threadedConversations.setIs_read(true); datastore.threadedConversationsDao().update(threadedConversations); if(customPagingSource != null) customPagingSource.invalidate(); return id; } public void update(Conversation conversation) { datastore.conversationDao().update(conversation); customPagingSource.invalidate(); } public List<Integer> search(String input) throws InterruptedException { List<Integer> positions = new ArrayList<>(); List<Conversation> list = datastore.conversationDao().getAll(threadId); for(int i=0;i<list.size();++i) { if(list.get(i).getText() != null) if(list.get(i).getText().toLowerCase().contains(input.toLowerCase())) positions.add(i); } return positions; } public void updateToRead(Context context) { if(threadId != null && !threadId.isEmpty()) { List<Conversation> conversations = datastore.conversationDao().getAll(threadId); List<Conversation> updateList = new ArrayList<>(); for(Conversation conversation : conversations) { if(!conversation.isRead()) { conversation.setRead(true); updateList.add(conversation); } } datastore.conversationDao().update(updateList); } } public void deleteItems(Context context, List<Conversation> conversations) { datastore.conversationDao().delete(conversations); String[] ids = new String[conversations.size()]; for(int i=0;i<conversations.size(); ++i) ids[i] = conversations.get(i).getMessage_id(); NativeSMSDB.deleteMultipleMessages(context, ids); } public Conversation fetchDraft() throws InterruptedException { return datastore.conversationDao().fetchTypedConversation( Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT, threadId); } public void clearDraft(Context context) { datastore.conversationDao() .deleteAllType(Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT, threadId); SMSDatabaseWrapper.deleteDraft(context, threadId); } public void unMute() { datastore.threadedConversationsDao().updateMuted(0, threadId); } public void mute() { datastore.threadedConversationsDao().updateMuted(1, threadId); } }
5,751
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
SearchViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/DefaultSMS/AdaptersViewModels/SearchViewModel.java
package com.afkanerd.deku.DefaultSMS.AdaptersViewModels; import android.content.Context; import android.util.Pair; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.DAO.ConversationDao; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ThreadedConversations; import com.afkanerd.deku.DefaultSMS.DAO.ThreadedConversationsDao; import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore; import com.afkanerd.deku.DefaultSMS.Models.ThreadingPoolExecutor; import java.util.ArrayList; import java.util.List; public class SearchViewModel extends ViewModel { MutableLiveData<Pair<List<ThreadedConversations>, Integer>> liveData; String threadId; public Datastore databaseConnector; public LiveData<Pair<List<ThreadedConversations>,Integer>> get(){ if(this.liveData == null) { liveData = new MutableLiveData<>(); } return liveData; } public LiveData<Pair<List<ThreadedConversations>,Integer>> getByThreadId(String threadId){ if(this.liveData == null) { liveData = new MutableLiveData<>(); this.threadId = threadId; } return liveData; } public void search(Context context, String input) throws InterruptedException { ThreadingPoolExecutor.executorService.execute(new Runnable() { @Override public void run() { List<Conversation> conversations = new ArrayList<>(); Integer index = null; if(threadId == null || threadId.isEmpty()) conversations = databaseConnector.threadedConversationsDao().findAddresses(input); else { conversations = databaseConnector.threadedConversationsDao() .findByThread(input, threadId); List<Conversation> conversationList = databaseConnector.conversationDao() .getAll(threadId); if(!conversationList.isEmpty()) { index = conversationList.indexOf(conversationList.get(0)); } } List<ThreadedConversations> threadedConversations = ThreadedConversations.buildRaw(context, conversations); liveData.postValue(new Pair<>(threadedConversations, index)); } }); } }
2,556
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerAddActivity.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerAddActivity.java
package com.afkanerd.deku.Router.GatewayServers; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; 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.afkanerd.deku.Router.Router.RouterHandler; import com.google.android.material.button.MaterialButton; import com.google.android.material.checkbox.MaterialCheckBox; import com.google.android.material.textfield.TextInputEditText; public class GatewayServerAddActivity extends AppCompatActivity { MaterialCheckBox all, base64; GatewayServerHandler gatewayServerHandler; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gateway_server_add); toolbar = findViewById(R.id.gateway_server_add_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.add_new_gateway_server_toolbar_title); gatewayServerHandler = new GatewayServerHandler(getApplicationContext()); dataTypeFilter(); MaterialButton materialButton = findViewById(R.id.gateway_client_customization_save_btn); materialButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onSaveGatewayServer(v); } }); populateForUpdates(); } private void populateForUpdates() { TextInputEditText textInputEditTextUrl = findViewById(R.id.new_gateway_client_url_input); RadioGroup radioGroup = findViewById(R.id.add_gateway_server_protocol_group); TextInputEditText textInputEditTextTag = findViewById(R.id.new_gateway_client_tag_input); if(getIntent().hasExtra(GatewayServer.GATEWAY_SERVER_URL)) { textInputEditTextUrl.setText(getIntent().getStringExtra(GatewayServer.GATEWAY_SERVER_URL)); } if(getIntent().hasExtra(GatewayServer.GATEWAY_SERVER_TAG)) { textInputEditTextTag.setText(getIntent().getStringExtra(GatewayServer.GATEWAY_SERVER_TAG)); } if(getIntent().hasExtra(GatewayServer.GATEWAY_SERVER_FORMAT)) { String format = getIntent().getStringExtra(GatewayServer.GATEWAY_SERVER_FORMAT); if(format != null && format.equals(GatewayServer.BASE64_FORMAT)) base64.setChecked(true); } } private void dataTypeFilter(){ all = findViewById(R.id.add_gateway_data_format_all); base64 = findViewById(R.id.add_gateway_data_format_base64); all.addOnCheckedStateChangedListener(new MaterialCheckBox.OnCheckedStateChangedListener() { @Override public void onCheckedStateChangedListener(@NonNull MaterialCheckBox checkBox, int state) { if(state == 1) { base64.setChecked(false); } } }); base64.addOnCheckedStateChangedListener(new MaterialCheckBox.OnCheckedStateChangedListener() { @Override public void onCheckedStateChangedListener(@NonNull MaterialCheckBox checkBox, int state) { if(state == 1) { all.setChecked(false); } } }); } public void onSaveGatewayServer(View view) { TextInputEditText textInputEditTextUrl = findViewById(R.id.new_gateway_client_url_input); String gatewayServerUrl = textInputEditTextUrl.getText().toString(); TextInputEditText textInputEditTextTag = findViewById(R.id.new_gateway_client_tag_input); String gatewayServerTag = textInputEditTextTag.getText().toString(); String formats = ""; String protocol = GatewayServer.POST_PROTOCOL; if(base64.isChecked()) formats = GatewayServer.BASE64_FORMAT; RadioGroup radioGroup = findViewById(R.id.add_gateway_server_protocol_group); int checkedRadioId = radioGroup.getCheckedRadioButtonId(); if(checkedRadioId == R.id.add_gateway_protocol_GET) protocol = GatewayServer.GET_PROTOCOL; // Important: test if valid url GatewayServer gatewayServer = new GatewayServer(gatewayServerUrl); gatewayServer.setTag(gatewayServerTag); gatewayServer.setFormat(formats); gatewayServer.setProtocol(protocol); try { if(getIntent().hasExtra(GatewayServer.GATEWAY_SERVER_ID)) { gatewayServer.setId(getIntent().getLongExtra(GatewayServer.GATEWAY_SERVER_ID, -1)); gatewayServerHandler.update(gatewayServer); } else gatewayServerHandler.add(gatewayServer); Intent gatewayServerListIntent = new Intent(this, GatewayServerListingActivity.class); startActivity(gatewayServerListIntent); finish(); } catch(InterruptedException e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if(getIntent().hasExtra(GatewayServer.GATEWAY_SERVER_ID)) { getMenuInflater().inflate(R.menu.gateway_server_add_menu, menu); } return super.onCreateOptionsMenu(menu); } private void deleteGatewayServer() throws InterruptedException { gatewayServerHandler.delete(getIntent().getLongExtra(GatewayServer.GATEWAY_SERVER_ID, -1)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.gateway_client_delete) { try { long gatewayServerId = getIntent().getLongExtra(GatewayServer.GATEWAY_SERVER_ID, -1); GatewayServer gatewayServer = gatewayServerHandler.get(gatewayServerId); deleteGatewayServer(); RouterHandler.removeWorkForGatewayServers(getApplicationContext(), gatewayServer.getURL()); Intent gatewayServerListIntent = new Intent(this, GatewayServerListingActivity.class); gatewayServerListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(gatewayServerListIntent); return true; } catch (InterruptedException e) { e.printStackTrace(); } } return false; } }
6,620
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerRecyclerAdapter.java
package com.afkanerd.deku.Router.GatewayServers; import android.content.Context; import android.content.Intent; 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.R; import org.jetbrains.annotations.NotNull; import java.util.List; public class GatewayServerRecyclerAdapter extends RecyclerView.Adapter<GatewayServerRecyclerAdapter.ViewHolder> { private final AsyncListDiffer<GatewayServer> mDiffer = new AsyncListDiffer(this, GatewayServer.DIFF_CALLBACK); Context context; public GatewayServerRecyclerAdapter(Context context) { this.context = context; } public GatewayServerRecyclerAdapter() {} @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(this.context); View view = inflater.inflate(R.layout.gateway_server_listing_layout, parent, false); return new GatewayServerRecyclerAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { // GatewayServer gatewayServer = gatewayServerList.get(position); GatewayServer gatewayServer = mDiffer.getCurrentList().get(position); holder.url.setText(gatewayServer.getURL()); holder.protocol.setText(gatewayServer.getProtocol()); String dataFormat = (gatewayServer.getFormat() == null || gatewayServer.getFormat().isEmpty()) ? "All" : gatewayServer.getFormat(); holder.format.setText(dataFormat); String date = Helpers.formatDate(context, gatewayServer.getDate()); holder.date.setText(date); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, GatewayServerAddActivity.class); intent.putExtra(GatewayServer.GATEWAY_SERVER_ID, gatewayServer.getId()); intent.putExtra(GatewayServer.GATEWAY_SERVER_TAG, gatewayServer.getTag()); intent.putExtra(GatewayServer.GATEWAY_SERVER_URL, gatewayServer.getURL()); intent.putExtra(GatewayServer.GATEWAY_SERVER_PROTOCOL, gatewayServer.getProtocol()); intent.putExtra(GatewayServer.GATEWAY_SERVER_FORMAT, gatewayServer.getFormat()); context.startActivity(intent); } }); } @Override public int getItemCount() { return mDiffer.getCurrentList().size(); } public void submitList(List<GatewayServer> list) { mDiffer.submitList(list); } public class ViewHolder extends RecyclerView.ViewHolder { TextView date, format, protocol, url; CardView cardView; public ViewHolder(@NonNull @NotNull View itemView) { super(itemView); this.url = itemView.findViewById(R.id.gateway_server_url); this.protocol = itemView.findViewById(R.id.gateway_server_protocol); this.date = itemView.findViewById(R.id.gateway_server_date); this.format = itemView.findViewById(R.id.gateway_server_data_format); this.cardView = itemView.findViewById(R.id.gateway_server_card_view); } } }
3,593
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerHandler.java
package com.afkanerd.deku.Router.GatewayServers; import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.room.Room; import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore; import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations; import java.util.ArrayList; import java.util.List; public class GatewayServerHandler { Datastore databaseConnector; public GatewayServerHandler(Context context){ if(Datastore.datastore == null || !Datastore.datastore.isOpen()) { Datastore.datastore = Room.databaseBuilder(context, Datastore.class, Datastore.databaseName) .enableMultiInstanceInvalidation() .build(); } databaseConnector = Datastore.datastore; } public LiveData<List<GatewayServer>> getAllLiveData() throws InterruptedException { final LiveData<List<GatewayServer>>[] liveData = new LiveData[]{new MutableLiveData<>()}; Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); liveData[0] = gatewayServerDAO.getAll(); } }); thread.start(); thread.join(); return liveData[0]; } public synchronized List<GatewayServer> getAll() throws InterruptedException { final List<GatewayServer>[] gatewayServerList = new List[]{new ArrayList<>()}; Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); gatewayServerList[0] = gatewayServerDAO.getAllList(); } }); thread.start(); thread.join(); return gatewayServerList[0]; } public GatewayServer get(long id) throws InterruptedException { final GatewayServer[] gatewayServer = {new GatewayServer()}; Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); gatewayServer[0] = gatewayServerDAO.get(id); } }); thread.start(); thread.join(); return gatewayServer[0]; } public void delete(long id) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); GatewayServer gatewayServer = new GatewayServer(); gatewayServer.setId(id); gatewayServerDAO.delete(gatewayServer); } }); thread.start(); thread.join(); } public void add(GatewayServer gatewayServer) throws InterruptedException { gatewayServer.setDate(System.currentTimeMillis()); Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); gatewayServerDAO.insert(gatewayServer); } }); thread.start(); thread.join(); } public void update(GatewayServer gatewayServer) throws InterruptedException { gatewayServer.setDate(System.currentTimeMillis()); Thread thread = new Thread(new Runnable() { @Override public void run() { GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); gatewayServerDAO.update(gatewayServer); } }); thread.start(); thread.join(); } // public static List<GatewayServer> fetchAll(Context context) throws InterruptedException { // Datastore databaseConnector = Room.databaseBuilder(context, Datastore.class, // Datastore.databaseName).build(); // // final List<GatewayServer>[] encryptedContentList = new List[]{new ArrayList<>()}; // // Thread fetchEncryptedMessagesThread = new Thread(new Runnable() { // @Override // public void run() { // GatewayServerDAO gatewayServerDAO = databaseConnector.gatewayServerDAO(); // encryptedContentList[0] = gatewayServerDAO.getAll(); // } // }); // // fetchEncryptedMessagesThread.start(); // fetchEncryptedMessagesThread.join(); // // return encryptedContentList[0]; // } }
4,718
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerDAO.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerDAO.java
package com.afkanerd.deku.Router.GatewayServers; 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 GatewayServerDAO { @Query("SELECT * FROM GatewayServer") LiveData<List<GatewayServer>> getAll(); @Query("SELECT * FROM GatewayServer") List<GatewayServer> getAllList(); @Query("SELECT * FROM GatewayServer WHERE id=:id") GatewayServer get(long id); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(GatewayServer gatewayServer); @Update void update(GatewayServer gatewayServer); @Delete void delete(GatewayServer gatewayServer); }
809
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerViewModel.java
package com.afkanerd.deku.Router.GatewayServers; import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import java.util.List; public class GatewayServerViewModel extends ViewModel { private LiveData<List<GatewayServer>> gatewayServersList; public LiveData<List<GatewayServer>> get(Context context) throws InterruptedException { if(gatewayServersList == null) { gatewayServersList = new MutableLiveData<>(); loadGatewayServers(context); } return gatewayServersList; } private void loadGatewayServers(Context context) throws InterruptedException { GatewayServerHandler gatewayServerHandler = new GatewayServerHandler(context); gatewayServersList = gatewayServerHandler.getAllLiveData(); } }
874
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServer.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServer.java
package com.afkanerd.deku.Router.GatewayServers; import android.content.Context; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.DiffUtil; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.Room; import androidx.room.RoomDatabase; import com.afkanerd.deku.DefaultSMS.Models.Database.Datastore; import com.afkanerd.deku.DefaultSMS.Models.Database.Migrations; @Entity public class GatewayServer { public static String BASE64_FORMAT = "base_64"; public static String ALL_FORMAT = "all"; public static String POST_PROTOCOL = "POST"; public static String GET_PROTOCOL = "GET"; public static String GATEWAY_SERVER_ID = "GATEWAY_SERVER_ID"; public static String GATEWAY_SERVER_TAG = "GATEWAY_SERVER_TAG"; public static String GATEWAY_SERVER_URL = "GATEWAY_SERVER_URL"; public static String GATEWAY_SERVER_PROTOCOL = "GATEWAY_SERVER_PROTOCOL"; public static String GATEWAY_SERVER_FORMAT = "GATEWAY_SERVER_FORMAT"; @ColumnInfo(name="URL") public String URL; public String getURL() { return URL; } public void setURL(String URL) { this.URL = URL; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Long getDate() { return date; } public void setDate(Long date) { this.date = date; } @ColumnInfo(name="protocol") public String protocol = POST_PROTOCOL; @ColumnInfo(name="tag") public String tag = ""; public String getTag() { return this.tag; } public void setTag(String tag) { this.tag = tag; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } @ColumnInfo(name="format") public String format = ALL_FORMAT; @ColumnInfo(name="date") public Long date; public GatewayServer(String url) { this.URL = url; } public GatewayServer() {} @PrimaryKey(autoGenerate = true) public long id; public long getId(){ return this.id; } public void setId(long id) { this.id = id; } @Ignore Datastore databaseConnector; public GatewayServerDAO getDaoInstance(Context context) { databaseConnector = Room.databaseBuilder(context, Datastore.class, Datastore.databaseName) .addMigrations(new Migrations.Migration8To9()) .addMigrations(new Migrations.Migration9To10()) .enableMultiInstanceInvalidation() .build(); return databaseConnector.gatewayServerDAO(); } // public void close() { // if(databaseConnector != null) // databaseConnector.close(); // } @Override public boolean equals(@Nullable Object obj) { // return super.equals(obj); if(obj instanceof GatewayServer) { GatewayServer gatewayServer = (GatewayServer) obj; return gatewayServer.id == this.id && gatewayServer.URL.equals(this.URL) && gatewayServer.protocol.equals(this.protocol) && gatewayServer.date.equals(this.date); } return false; } public static final DiffUtil.ItemCallback<GatewayServer> DIFF_CALLBACK = new DiffUtil.ItemCallback<GatewayServer>() { @Override public boolean areItemsTheSame(@NonNull GatewayServer oldItem, @NonNull GatewayServer newItem) { return oldItem.id == newItem.id; } @Override public boolean areContentsTheSame(@NonNull GatewayServer oldItem, @NonNull GatewayServer newItem) { return oldItem.equals(newItem); } }; }
4,123
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
GatewayServerListingActivity.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/GatewayServers/GatewayServerListingActivity.java
package com.afkanerd.deku.Router.GatewayServers; 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 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.R; import java.util.List; public class GatewayServerListingActivity extends AppCompatActivity { Handler mHandler = new Handler(); SharedPreferences sharedPreferences; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gateway_servers_listing_activitiy); toolbar = findViewById(R.id.gateway_servers_listing_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(getString(R.string.gateway_server_listing_toolbar_title)); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); RecyclerView recentsRecyclerView = findViewById(R.id.gateway_server_listing_recycler_view); recentsRecyclerView.setLayoutManager(linearLayoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getApplicationContext(), linearLayoutManager.getOrientation()); recentsRecyclerView.addItemDecoration(dividerItemDecoration); GatewayServerRecyclerAdapter gatewayServerRecyclerAdapter = new GatewayServerRecyclerAdapter(this); recentsRecyclerView.setAdapter(gatewayServerRecyclerAdapter); GatewayServerViewModel gatewayServerViewModel = new ViewModelProvider(this).get( GatewayServerViewModel.class); try { gatewayServerViewModel.get(getApplicationContext()).observe(this, new Observer<List<GatewayServer>>() { @Override public void onChanged(List<GatewayServer> gatewayServerList) { Log.d(getLocalClassName(), "Changed happening...."); if(gatewayServerList.size() < 1 ) findViewById(R.id.no_gateway_server_added).setVisibility(View.VISIBLE); gatewayServerRecyclerAdapter.submitList(gatewayServerList); } }); } catch (InterruptedException e) { e.printStackTrace(); } setRefreshTimer(gatewayServerRecyclerAdapter); } private void setRefreshTimer(GatewayServerRecyclerAdapter 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(), GatewayServerAddActivity.class); startActivity(addGatewayIntent); return true; } return false; } @Override protected void onResume() { super.onResume(); } }
3,975
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterRecyclerAdapter.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterRecyclerAdapter.java
package com.afkanerd.deku.Router.Router; import android.content.Context; 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.lifecycle.MutableLiveData; import androidx.recyclerview.widget.AsyncListDiffer; import androidx.recyclerview.widget.RecyclerView; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.DefaultSMS.R; import com.google.android.material.card.MaterialCardView; import java.util.HashMap; import java.util.List; import java.util.Map; public class RouterRecyclerAdapter extends RecyclerView.Adapter<RouterRecyclerAdapter.ViewHolder> { public final AsyncListDiffer<RouterItem> mDiffer = new AsyncListDiffer<>(this, RouterItem.DIFF_CALLBACK); Context context; public MutableLiveData<HashMap<Long, ViewHolder>> selectedItems; public RouterRecyclerAdapter(Context context) { this.context = context; this.selectedItems = new MutableLiveData<>(); } @Override public long getItemId(int position) { return position; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(this.context); View view = inflater.inflate(R.layout.routed_messages_layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { RouterItem routerItem = mDiffer.getCurrentList().get(position); holder.bind(routerItem); setOnLongClickListener(holder); setOnClickListener(holder); } private void setOnClickListener(ViewHolder holder) { holder.materialCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HashMap<Long, ViewHolder> items = selectedItems.getValue(); if(items != null && !items.isEmpty()){ if(items.containsKey(holder.getItemId())) { ViewHolder viewHolder = items.remove(holder.getItemId()); viewHolder.unhighlight(); } else { Log.d(getClass().getName(), "Item id: " + holder.getItemId()); items.put(holder.getItemId(), holder); holder.highlight(); } selectedItems.setValue(items); } } }); } private void setOnLongClickListener(ViewHolder holder) { holder.materialCardView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { HashMap<Long, ViewHolder> items = selectedItems.getValue(); if(items == null) items = new HashMap<>(); Log.d(getClass().getName(), "Item id: " + holder.getItemId()); items.put(holder.getItemId(), holder); selectedItems.setValue(items); holder.highlight(); return true; } }); } public void resetAllSelected() { for(Map.Entry<Long, ViewHolder> entry : selectedItems.getValue().entrySet()) { entry.getValue().unhighlight(); } selectedItems.setValue(null); } @Override public int getItemCount() { return mDiffer.getCurrentList().size(); } public void submitList(List<RouterItem> list) { mDiffer.submitList(list); } public static class ViewHolder extends RecyclerView.ViewHolder { MaterialCardView materialCardView; TextView address, url, body, status, date; public ViewHolder(@NonNull View itemView) { super(itemView); this.address = itemView.findViewById(R.id.routed_messages_address); this.url = itemView.findViewById(R.id.routed_messages_url); this.body = itemView.findViewById(R.id.routed_messages_body); this.status = itemView.findViewById(R.id.routed_messages_status); this.date = itemView.findViewById(R.id.routed_messages_date); this.materialCardView = itemView.findViewById(R.id.routed_messages_material_cardview); } public void bind(RouterItem routerItem) { this.address.setText(routerItem.getAddress()); this.url.setText(routerItem.url); this.body.setText(routerItem.getText()); this.status.setText(routerItem.routingStatus); this.date.setText(Helpers.formatDate(itemView.getContext(), routerItem.routingDate)); } public void highlight() { this.materialCardView.setBackgroundResource(R.drawable.received_messages_drawable); } public void unhighlight() { this.materialCardView.setBackgroundResource(0); } } }
5,068
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterHandler.java
package com.afkanerd.deku.Router.Router; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.TAG_NAME; import static com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver.TAG_ROUTING_URL; import android.content.Context; import android.util.Log; import androidx.work.BackoffPolicy; import androidx.work.Constraints; import androidx.work.Data; import androidx.work.ExistingWorkPolicy; import androidx.work.NetworkType; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkInfo; import androidx.work.WorkManager; import androidx.work.WorkQuery; import com.afkanerd.deku.DefaultSMS.Commons.Helpers; import com.afkanerd.deku.Router.GatewayServers.GatewayServerHandler; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.RequestFuture; import com.android.volley.toolbox.Volley; import com.afkanerd.deku.DefaultSMS.BroadcastReceivers.IncomingTextSMSBroadcastReceiver; import com.afkanerd.deku.Router.GatewayServers.GatewayServer; import com.afkanerd.deku.Router.GatewayServers.GatewayServerDAO; import com.google.common.util.concurrent.ListenableFuture; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class RouterHandler { public static final String TAG_WORKER_ID = "swob.work.id."; public static int MESSAGE_ID = 0; public static int WORK_NAME = 1; public static int ROUTING_URL = 2; public static int ROUTING_ID = 3; protected static ExecutorService executorService = Executors.newFixedThreadPool(4); public static void routeJsonMessages(Context context, String jsonStringBody, String gatewayServerUrl) throws ExecutionException, InterruptedException, TimeoutException, JSONException { try{ Log.d(RouterHandler.class.getName(), "Request to router: " + jsonStringBody); JSONObject jsonBody = new JSONObject(jsonStringBody); RequestFuture<JSONObject> future = RequestFuture.newFuture(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, gatewayServerUrl, jsonBody, future, future); RequestQueue requestQueue = Volley.newRequestQueue(context); jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy( 0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(jsonObjectRequest); future.get(30, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException | InterruptedException e){ // Hit the server and came back with error code throw e; } // Because the server could return a string... } public static void route(Context context, RouterItem routerItem, GatewayServerHandler gatewayServerHandler) throws InterruptedException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting().serializeNulls(); Gson gson = gsonBuilder.create(); Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build(); boolean isBase64 = Helpers.isBase64Encoded(routerItem.getText()); // GatewayServer gatewayServer = new GatewayServer(); // GatewayServerDAO gatewayServerDAO = gatewayServer.getDaoInstance(context); // List<GatewayServer> gatewayServerList = gatewayServerDAO.getAllList(); List<GatewayServer> gatewayServerList = gatewayServerHandler.getAll(); for (GatewayServer gatewayServer1 : gatewayServerList) { if(gatewayServer1.getFormat() != null && gatewayServer1.getFormat().equals(GatewayServer.BASE64_FORMAT) && !isBase64) continue; routerItem.tag = gatewayServer1.getTag(); final String jsonStringBody = gson.toJson(routerItem); try { OneTimeWorkRequest routeMessageWorkRequest = new OneTimeWorkRequest.Builder(RouterWorkManager.class) .setConstraints(constraints) .setBackoffCriteria( BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS ) .addTag(TAG_NAME) .addTag(getTagForMessages(routerItem.getMessage_id())) .addTag(getTagForGatewayServers(gatewayServer1.getURL())) .setInputData( new Data.Builder() .putString(RouterWorkManager.SMS_JSON_OBJECT, jsonStringBody) .putString(RouterWorkManager.SMS_JSON_ROUTING_URL, gatewayServer1.getURL()) .build() ) .build(); String uniqueWorkName = routerItem.getMessage_id() + ":" + gatewayServer1.getURL(); WorkManager workManager = WorkManager.getInstance(context); workManager.enqueueUniqueWork( uniqueWorkName, ExistingWorkPolicy.KEEP, routeMessageWorkRequest); } catch (Exception e) { e.printStackTrace(); } } } private static String getTagForMessages(String messageId) { return TAG_WORKER_ID + messageId; } private static String getTagForGatewayServers(String gatewayClientUrl) { return TAG_ROUTING_URL + gatewayClientUrl; } public static void removeWorkForMessage(Context context, String messageId) { String tag = getTagForMessages(messageId); WorkManager workManager = WorkManager.getInstance(context); workManager.cancelAllWorkByTag(tag); } public static void removeWorkForGatewayServers(Context context, String gatewayClientUrl) { String tag = getTagForGatewayServers(gatewayClientUrl); WorkManager workManager = WorkManager.getInstance(context); workManager.cancelAllWorkByTag(tag); } public static ArrayList<String[]> getMessageIdsFromWorkManagers(Context context) { WorkQuery workQuery = WorkQuery.Builder .fromTags(Collections.singletonList( TAG_NAME)) .addStates(Arrays.asList( WorkInfo.State.SUCCEEDED, WorkInfo.State.ENQUEUED, WorkInfo.State.FAILED, WorkInfo.State.RUNNING, WorkInfo.State.CANCELLED)) .build(); WorkManager workManager = WorkManager.getInstance(context); ListenableFuture<List<WorkInfo>> worksInfo = workManager.getWorkInfos(workQuery); ArrayList<String[]> workerIds = new ArrayList<>(); try { List<WorkInfo> workInfoList = worksInfo.get(); for(WorkInfo workInfo : workInfoList) { String messageId = ""; String gatewayServerUrl = ""; for(String tag : workInfo.getTags()) { if (tag.contains(RouterHandler.TAG_WORKER_ID)) { String[] tags = tag.split("\\."); messageId = tags[tags.length - 1]; } if (tag.contains(IncomingTextSMSBroadcastReceiver.TAG_ROUTING_URL)) { String[] tags = tag.split(","); gatewayServerUrl = tags[tags.length - 1]; } } // ArrayList<String> routeJobState = new ArrayList<>(); String[] routeJobState = new String[4]; if(!messageId.isEmpty() && !gatewayServerUrl.isEmpty()) { routeJobState[MESSAGE_ID] = messageId; routeJobState[WORK_NAME] = workInfo.getState().name(); routeJobState[ROUTING_URL] = gatewayServerUrl; routeJobState[ROUTING_ID] = workInfo.getId().toString(); } workerIds.add(routeJobState); } } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } return workerIds; } }
9,025
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterViewModel.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterViewModel.java
package com.afkanerd.deku.Router.Router; import android.content.Context; import android.database.Cursor; import android.provider.Telephony; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.afkanerd.deku.DefaultSMS.Models.NativeSMSDB; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class RouterViewModel extends ViewModel { private MutableLiveData<List<RouterItem>> messagesList; public LiveData<List<RouterItem>> getMessages(Context context){ if(messagesList == null) { messagesList = new MutableLiveData<>(); loadSMSThreads(context); } return messagesList; } public void informChanges(Context context) { loadSMSThreads(context); } private void loadSMSThreads(Context context) { ArrayList<String[]> routerJobs = RouterHandler.getMessageIdsFromWorkManagers(context); if(routerJobs.isEmpty()) return; Thread thread = new Thread(new Runnable() { @Override public void run() { ListMultimap<Long, RouterItem> routerMessagesListMultimap = ArrayListMultimap.create(); for(String[] workerList : routerJobs) { String messageId = workerList[0]; Cursor cursor = NativeSMSDB.fetchByMessageId(context, messageId); if(cursor.moveToFirst()) { int threadIdIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.THREAD_ID); int addressIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.ADDRESS); int dateTimeIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.DATE); int bodyIndex = cursor.getColumnIndex(Telephony.TextBasedSmsColumns.BODY); String threadId = cursor.getString(threadIdIndex); String address = cursor.getString(addressIndex); String body = cursor.getString(bodyIndex); String date = cursor.getString(dateTimeIndex); String routerStatus = workerList[1]; String url = workerList[2]; RouterItem routerMessage = new RouterItem(cursor); cursor.close(); routerMessage.routingStatus = routerStatus; routerMessage.url = url; routerMessage.routingDate = Long.parseLong(date); routerMessage.setMessage_id(messageId); routerMessage.setText(body); routerMessage.setAddress(address); routerMessagesListMultimap.put(Long.parseLong(date), routerMessage); } } List<RouterItem> sortedList = new ArrayList<>(); List<Long> keys = new ArrayList<>(routerMessagesListMultimap.keySet()); keys.sort(Collections.reverseOrder()); for(Long date : keys) { sortedList.addAll(routerMessagesListMultimap.get(date)); } messagesList.postValue(sortedList); } }); thread.start(); } }
3,477
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterItem.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterItem.java
package com.afkanerd.deku.Router.Router; import android.database.Cursor; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DiffUtil; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; public class RouterItem extends Conversation { public String url; public String tag; public String MSISDN; public long routingDate; public String routingStatus; public String sid; public String reportedStatus; public RouterItem(Cursor cursor) { super(cursor); this.MSISDN = this.getAddress(); this.text = this.getText(); } public RouterItem() { } public static RouterItem build(Cursor cursor) { return (RouterItem) Conversation.build(cursor); } public static final DiffUtil.ItemCallback<RouterItem> DIFF_CALLBACK = new DiffUtil.ItemCallback<RouterItem>() { @Override public boolean areItemsTheSame(@NonNull RouterItem oldItem, @NonNull RouterItem newItem) { return oldItem.getMessage_id().equals(newItem.getMessage_id()); } @Override public boolean areContentsTheSame(@NonNull RouterItem oldItem, @NonNull RouterItem newItem) { return oldItem.equals(newItem); } }; @Override public boolean equals(@Nullable Object obj) { if(obj instanceof RouterItem) { RouterItem routerItem = (RouterItem) obj; return routerItem.getMessage_id().equals(this.getMessage_id()) && routerItem.getText().equals(this.getText()) && routerItem.url.equals(this.url) && routerItem.routingDate == this.routingDate; } return false; } }
1,773
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterWorkManager.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterWorkManager.java
package com.afkanerd.deku.Router.Router; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.android.volley.ParseError; import com.android.volley.ServerError; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; public class RouterWorkManager extends Worker { public static final String SMS_JSON_OBJECT = "SMS_JSON_OBJECT"; public static final String SMS_JSON_ROUTING_URL = "SMS_JSON_ROUTING_URL"; // https://developer.android.com/topic/libraries/architecture/workmanager/basics public RouterWorkManager(@NonNull Context context, @NonNull WorkerParameters workerParams) { super(context, workerParams); } @NonNull @Override public Result doWork() { try { String gatewayServerUrl = getInputData().getString(SMS_JSON_ROUTING_URL); String jsonBody = getInputData().getString(SMS_JSON_OBJECT); if(jsonBody != null) RouterHandler.routeJsonMessages(getApplicationContext(), jsonBody, gatewayServerUrl); } catch (ExecutionException | TimeoutException | InterruptedException e) { e.printStackTrace(); Throwable cause = e.getCause(); if (cause instanceof ServerError) { ServerError error = (ServerError) cause; int statusCode = error.networkResponse.statusCode; if (statusCode >= 400) return Result.failure(); } else if(cause instanceof ParseError) { return Result.success(); } return Result.retry(); } catch (Exception e ) { e.printStackTrace(); return Result.failure(); } return Result.success(); } }
1,864
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RouterActivity.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Router/Router/RouterActivity.java
package com.afkanerd.deku.Router.Router; import androidx.appcompat.app.ActionBar; 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.util.Log; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.afkanerd.deku.DefaultSMS.CustomAppCompactActivity; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.Router.GatewayServers.GatewayServerAddActivity; import com.afkanerd.deku.Router.GatewayServers.GatewayServerListingActivity; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class RouterActivity extends CustomAppCompactActivity { RouterViewModel routerViewModel; RecyclerView routedMessageRecyclerView; RouterRecyclerAdapter routerRecyclerAdapter; ActionMode actionMode; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_router); toolbar = findViewById(R.id.router_activity_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(getString(R.string.settings_SMS_routing_title)); routedMessageRecyclerView = findViewById(R.id.routed_messages_recycler_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); routedMessageRecyclerView.setLayoutManager(linearLayoutManager); routerRecyclerAdapter = new RouterRecyclerAdapter(getApplicationContext()); routerRecyclerAdapter.setHasStableIds(true); routedMessageRecyclerView.setAdapter(routerRecyclerAdapter); routerViewModel = new ViewModelProvider(this).get( RouterViewModel.class); routerViewModel.getMessages(getApplicationContext()).observe(this, new Observer<List<RouterItem>>() { @Override public void onChanged(List<RouterItem> smsList) { routerRecyclerAdapter.submitList(smsList); if(!smsList.isEmpty()) findViewById(R.id.router_no_showable_messages_text).setVisibility(View.GONE); else { findViewById(R.id.router_no_showable_messages_text).setVisibility(View.VISIBLE); routedMessageRecyclerView.smoothScrollToPosition(0); } } }); routerRecyclerAdapter.selectedItems.observe(this, new Observer<HashMap<Long, RouterRecyclerAdapter.ViewHolder>>() { @Override public void onChanged(HashMap<Long, RouterRecyclerAdapter.ViewHolder> longs) { if(longs == null || longs.isEmpty()) { if(actionMode != null) { actionMode.finish(); } return; } else if(actionMode == null) { actionMode = startActionMode(actionModeCallback); } if(actionMode != null) actionMode.setTitle(String.valueOf(longs.size())); } }); } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.routing_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.router_list_gateways_menu_item) { startActivity(new Intent(this, GatewayServerListingActivity.class)); return true; } if(item.getItemId() == R.id.router_add_gateways_menu_item) { startActivity(new Intent(this, GatewayServerAddActivity.class)); return true; } return false; } private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.routing_menu_items_selected, menu); 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) { if (item.getItemId() == R.id.router_cancel_menu_item) { if(routerRecyclerAdapter.selectedItems.getValue() != null) { for (Map.Entry<Long, RouterRecyclerAdapter.ViewHolder>entry : routerRecyclerAdapter.selectedItems.getValue().entrySet()) { RouterItem routerItem = routerRecyclerAdapter.mDiffer .getCurrentList() .get(Math.toIntExact(entry.getKey())); String messageId = String.valueOf(routerItem.getMessage_id()); RouterHandler.removeWorkForMessage(getApplicationContext(), messageId); routerRecyclerAdapter.notifyItemChanged(Math.toIntExact(entry.getKey())); } return true; } return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; routerRecyclerAdapter.resetAllSelected(); } }; }
5,942
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ImageViewActivity.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Images/Images/ImageViewActivity.java
package com.afkanerd.deku.Images.Images; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Base64; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import com.afkanerd.deku.DefaultSMS.ConversationActivity; import com.afkanerd.deku.DefaultSMS.Models.Compression; import com.afkanerd.deku.DefaultSMS.Models.NativeSMSDB; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.DefaultSMS.Models.Contacts; import com.afkanerd.deku.E2EE.Security.SecurityAES; import com.afkanerd.deku.E2EE.Security.SecurityECDH; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.zip.DataFormatException; public class ImageViewActivity extends AppCompatActivity { Uri imageUri; ImageView imageView; TextView imageDescription; byte[] compressedBytes; String address = ""; String threadId = ""; ImageHandler imageHandler; final int MAX_RESOLUTION = 400; final int MIN_RESOLUTION = MAX_RESOLUTION / 2; int COMPRESSION_RATIO = 5; public double changedResolution; public static final String IMAGE_INTENT_EXTRA = "image_sms_id"; public static final String SMS_IMAGE_PENDING_LOCATION = "SMS_IMAGE_PENDING_LOCATION"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_view); Toolbar myToolbar = (Toolbar) findViewById(R.id.image_view_toolbar); // myToolbar.inflateMenu(R.menu.default_menu); setSupportActionBar(myToolbar); // Get a support ActionBar corresponding to this toolbar ActionBar ab = getSupportActionBar(); // Enable the Up button ab.setDisplayHomeAsUpEnabled(true); imageView = findViewById(R.id.compressed_image_holder); imageDescription = findViewById(R.id.image_details_size); address = getIntent().getStringExtra(ConversationHandler.ADDRESS); threadId = getIntent().getStringExtra(ConversationHandler.THREAD_ID); String contactName = Contacts.retrieveContactName(getApplicationContext(), address); contactName = (contactName.equals("null") || contactName.isEmpty()) ? address: contactName; ab.setTitle(contactName); if(getIntent().hasExtra(IMAGE_INTENT_EXTRA)) { String smsId = getIntent().getStringExtra(IMAGE_INTENT_EXTRA); Cursor cursor = NativeSMSDB.fetchByMessageId(getApplicationContext(), smsId); if(cursor.moveToFirst()) { SMS sms = new SMS(cursor); byte[] body = Base64.decode(sms.getBody() .replace(ImageHandler.IMAGE_HEADER, ""), Base64.DEFAULT); try { buildImage(body); } catch (IOException e) { throw new RuntimeException(e); } } cursor.close(); } else { imageUri = Uri.parse(getIntent().getStringExtra(ConversationActivity.IMAGE_URI)); try { imageHandler = new ImageHandler(getApplicationContext(), imageUri); ((TextView)findViewById(R.id.image_details_original_resolution)) .setText("Original resolution: " + imageHandler.bitmap.getWidth() + " x " + imageHandler.bitmap.getHeight()); } catch (IOException e) { throw new RuntimeException(e); } try { // changedResolution = getMaxResolution(); changedResolution = MAX_RESOLUTION; buildImage(); changeResolution(getMaxResolution()); } catch (Throwable e) { throw new RuntimeException(e); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home ) { Intent intent = new Intent(this, ConversationActivity.class); intent.putExtra(ConversationHandler.ADDRESS, address); if(!threadId.isEmpty()) intent.putExtra(ConversationHandler.THREAD_ID, threadId); startActivity(intent); finish(); return true; } return super.onOptionsItemSelected(item); } private void changeResolution(final int maxResolution) { final double resDifference = maxResolution - MAX_RESOLUTION; final double changeConstant = resDifference / 100; SeekBar seekBar = findViewById(R.id.image_view_change_resolution_seeker); TextView seekBarProgress = findViewById(R.id.image_details_seeker_progress); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { final int resChangeRatio = Math.round(MIN_RESOLUTION / seekBar.getMax()); @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { double calculatedResolution = progress == 0 ? MAX_RESOLUTION : MAX_RESOLUTION - (resChangeRatio * progress); // // if(calculatedResolution > MIN_RESOLUTION) { // changedResolution = calculatedResolution; // COMPRESSION_RATIO = 0; // } else { // changedResolution = MIN_RESOLUTION; // COMPRESSION_RATIO = seekBar.getMax() - progress; // } changedResolution = calculatedResolution; COMPRESSION_RATIO = progress; seekBarProgress.setText(String.valueOf(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { try { buildImage(); } catch (Throwable e) { throw new RuntimeException(e); } } }); } private void buildImage(byte[] data ) throws IOException { TextView imageResolutionOriginal = findViewById(R.id.image_details_original_resolution); imageResolutionOriginal.setVisibility(View.GONE); TextView imageResolution = findViewById(R.id.image_details_resolution); imageResolution.setVisibility(View.GONE); TextView imageSize = findViewById(R.id.image_details_size); imageSize.setVisibility(View.GONE); TextView imageQuality = findViewById(R.id.image_details_quality); imageQuality.setVisibility(View.GONE); TextView imageSMSCount = findViewById(R.id.image_details_sms_count); imageSMSCount.setVisibility(View.GONE); TextView seekBarText = findViewById(R.id.image_details_seeker_progress); seekBarText.setVisibility(View.GONE); SeekBar seekBar = findViewById(R.id.image_view_change_resolution_seeker); seekBar.setVisibility(View.GONE); Button button = findViewById(R.id.image_send_btn); button.setVisibility(View.GONE); Bitmap compressedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(compressedBitmap); // compressedBitmap.recycle(); } private int getMaxResolution() { return imageHandler.getMaxResolution(); } private byte[] compress(byte[] input) { // byte[] compressGzip = Compression.compressLZ4(compressDeflate); // Log.d(getLocalClassName(), "Gzip compression: " + compressGzip.length); // for(int i=0;i<decompressGZIP.length; ++i) { // if(decompressGZIP[i] != c[i]) { // Log.d(getLocalClassName(), "Different things came back!"); // break; // } // } // return compressGzip; return Compression.compressDeflate(input); // return input; } private byte[] decompress(byte[] input) throws DataFormatException { // byte[] decompressGZIP = Compression.decompressGZIP(input); // Log.d(getLocalClassName(), "Gzip decompressed: " + decompressGZIP.length); // // return Compression.decompressDeflate(decompressGZIP); return input; } private void buildImage() throws Throwable { SmsManager smsManager = Build.VERSION.SDK_INT > Build.VERSION_CODES.R ? getSystemService(SmsManager.class) : SmsManager.getDefault(); Bitmap imageBitmap = imageHandler.resizeImage(changedResolution); imageBitmap = ImageHandler.removeAlpha(imageBitmap); compressedBytes = imageHandler.compressImage(COMPRESSION_RATIO, imageBitmap); Log.d(getLocalClassName(), "Before ICCP extraction: " + compressedBytes.length); compressedBytes = ImageHandler.extractContainerInformation(compressedBytes); Log.d(getLocalClassName(), "After ICCP extraction: " + compressedBytes.length); Bitmap compressedBitmap = BitmapFactory.decodeByteArray(compressedBytes, 0, compressedBytes.length); imageView.setImageBitmap(compressedBitmap); SecurityECDH securityECDH = new SecurityECDH(getApplicationContext()); int numberOfmessages = -1; String content = ImageHandler.IMAGE_HEADER + Base64.encodeToString(compressedBytes, Base64.DEFAULT); byte[] c = content.getBytes(StandardCharsets.UTF_8); if(securityECDH.hasSecretKey(address)){ String secretKeyB64 = securityECDH.securelyFetchSecretKey(address); c = SecurityAES.encrypt_256_cbc(c, Base64.decode(secretKeyB64, Base64.DEFAULT), null); content = Base64.encodeToString(c, Base64.DEFAULT); c = EncryptionHandlers.putEncryptedMessageWaterMark(content) .getBytes(StandardCharsets.UTF_8); Log.d(getLocalClassName(), "Original no compression: " + c.length); // c = compress(c); } numberOfmessages = smsManager.divideMessage( Base64.encodeToString(c, Base64.DEFAULT)).size(); TextView imageResolution = findViewById(R.id.image_details_resolution); imageResolution.setText("New resolution: " + imageBitmap.getWidth() + " x " + imageBitmap.getHeight()); TextView imageSize = findViewById(R.id.image_details_size); imageSize.setText("Size " + (compressedBytes.length / 1024) + " KB"); TextView imageQuality = findViewById(R.id.image_details_quality); imageQuality.setText("Quality " + COMPRESSION_RATIO + "%"); TextView imageSMSCount = findViewById(R.id.image_details_sms_count); imageSMSCount.setText(numberOfmessages + " Messages"); } public void sendImage(View view) throws InterruptedException { // Intent intent = new Intent(this, ConversationActivity.class); // intent.putExtra(ConversationHandler.ADDRESS, address); // // long messageId = Helpers.generateRandomNumber(); // // int subscriptionId = SIMHandler.getDefaultSimSubscription(getApplicationContext()); // // String content = ImageHandler.IMAGE_HEADER + // Base64.encodeToString(compressedBytes, Base64.DEFAULT); // //// content = Base64.encodeToString(compress(content.getBytes(StandardCharsets.UTF_8)), //// Base64.DEFAULT); // // String threadIdRx = SMSHandler.registerPendingMessage(getApplicationContext(), // address, // content, // messageId, // subscriptionId); // // intent.putExtra(ConversationHandler.THREAD_ID, threadIdRx); // intent.putExtra(SMS_IMAGE_PENDING_LOCATION, messageId); // // startActivity(intent); // finish(); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, ConversationActivity.class); intent.putExtra(ConversationHandler.ADDRESS, address); if (!threadId.isEmpty()) intent.putExtra(ConversationHandler.THREAD_ID, threadId); startActivity(intent); finish(); } }
12,702
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ImageHandler.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/main/java/com/afkanerd/deku/Images/Images/ImageHandler.java
package com.afkanerd.deku.Images.Images; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import com.afkanerd.deku.E2EE.Security.SecurityAES; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ImageHandler { Uri imageUri; Context context; public Bitmap bitmap; String iv = "1234567890123456"; String secretKey = "12345678901234561234567890123456"; public static final String IMAGE_HEADER = "--DEKU_IMAGE_HEADER--"; public static final String IMAGE_TRANSMISSION_HEADER = "[[DTH"; static final int MAX_NUMBER_SMS = 39; boolean edited = false; public ImageHandler(Context context, Uri imageUri) throws IOException { this.imageUri = imageUri; this.context = context; this.bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), this.imageUri); } public boolean isEdited() { return this.edited; } public static byte[] buildImage(byte[][] unstructuredImageBytes ) throws IOException { // return SMSHandler.rebuildStructuredSMSMessage(unstructuredImageBytes); return null; } public static boolean canComposeImage(Context context, String RIL) { Cursor cursor = getImagesCursor(context, RIL); boolean canCompose = false; if(cursor != null) { canCompose = true; cursor.close(); } return canCompose; } public byte[] compressImage(int compressionRatio, Bitmap.CompressFormat compressFormat) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); this.bitmap.compress(compressFormat, compressionRatio, byteArrayOutputStream); byte[] compressedBitmapBytes = byteArrayOutputStream.toByteArray(); return compressedBitmapBytes; } public byte[] compressImage(int compressionRatio) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap.CompressFormat bitmapCompressionFormat = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ? Bitmap.CompressFormat.WEBP_LOSSY : Bitmap.CompressFormat.WEBP; this.bitmap.compress(bitmapCompressionFormat, compressionRatio, byteArrayOutputStream); byte[] compressedBitmapBytes = byteArrayOutputStream.toByteArray(); return compressedBitmapBytes; } public byte[] compressImage(int compressionRatio, Bitmap imageBitmap) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap.CompressFormat bitmapCompressionFormat = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ? Bitmap.CompressFormat.WEBP_LOSSY : Bitmap.CompressFormat.WEBP; imageBitmap.compress(bitmapCompressionFormat, compressionRatio, byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } public static long composeAppendDeleteImages(Context context, String RIL, int ref) throws IOException { Cursor cursor = getImagesCursor(context, RIL); String defaultRIL = IMAGE_HEADER + ref; Cursor headerCursor = getImagesCursorAtIndex(context, RIL , 0); int len = 0; String headerMessageId = ""; if(headerCursor != null) { SMS sms = new SMS(headerCursor); headerMessageId = sms.getId(); String body = sms.getBody().replace(defaultRIL + 0, ""); Log.d(ImageHandler.class.getName(), "Data image compose first body: " + body); len = Byte.toUnsignedInt(Base64.decode(body, Base64.DEFAULT)[2]); headerCursor.close(); } Log.d(ImageHandler.class.getName(), "Data image compose len: " + len); byte[][] imageData = new byte[len][]; String[] ids = new String[len]; if(cursor.moveToFirst()) { do { // remove header SMS sms = new SMS(cursor); Log.d(ImageHandler.class.getName(), "Data image compose raw: " + sms.getBody()); String body = sms.getBody(); if(sms.getBody().contains(defaultRIL + "0" + len)) { body = body.replace(defaultRIL + "0" + len, ""); } else { for (int i = len -1; i > -1; --i) { if(sms.getBody().contains(defaultRIL + i)) { body = sms.getBody().replace(defaultRIL + i, ""); break; } } } Log.d(ImageHandler.class.getName(), "Data image compose formatted: " + body); byte[] data = Base64.decode(body, Base64.DEFAULT); int index = Byte.toUnsignedInt(data[1]); Log.d(ImageHandler.class.getName(), "Data image compose index: " + index); Log.d(ImageHandler.class.getName(), "Data image compose data: " + data); imageData[index] = data; if(index != 0 ) ids[index] = sms.getId(); } while(cursor.moveToNext()); } cursor.close(); byte[] imageBytes = buildImage(imageData); Bitmap bitmap = getImageFromBytes(imageBytes); if(bitmap == null) Log.d(ImageHandler.class.getName(), "Data image is not a real image!"); else Log.d(ImageHandler.class.getName(), "Data image is a real image!"); String appendedBody = IMAGE_HEADER + Base64.encodeToString(imageBytes, Base64.DEFAULT); SMSHandler.updateMessage(context, headerMessageId, appendedBody); // SMSHandler.deleteMultipleMessages(context, ids); return Long.parseLong(headerMessageId); } public byte[] encryptImage(byte[] imageBytes) throws Throwable { SecurityAES aes = new SecurityAES(); byte[] bytesJpegEncryption = aes.encrypt_256_cbc( imageBytes, secretKey.getBytes(StandardCharsets.UTF_8), null); return bytesJpegEncryption; } public static String getImageMetaRIL(byte[] data) { return String.valueOf(Byte.toUnsignedInt(data[0])) + String.valueOf(Byte.toUnsignedInt(data[1])); } public static Cursor getImagesCursor(Context context, String RIL) { // RIL = IMAGE_HEADER + RIL; // // Cursor cursorImageCursor = SMSHandler.fetchSMSForImagesByRIL(context, RIL); // Log.d(ImageHandler.class.getName(), "Data image header RIL: " + RIL); // Log.d(ImageHandler.class.getName(), "Data image header counter: " + cursorImageCursor.getCount()); // if(cursorImageCursor.moveToFirst()) { // // SMS sms = new SMS(cursorImageCursor); // cursorImageCursor.close(); // // String body = sms.getBody().replace(RIL, ""); // // byte[] data = Base64.decode(body, Base64.DEFAULT); // // Log.d(ImageHandler.class.getName(), "Data image ref: " + Byte.toUnsignedInt(data[0])); // int len = Byte.toUnsignedInt(data[2]); // // StringBuilder query = new StringBuilder(); // String[] parameters = new String[len]; // // for(Integer i=0; i<len; ++i ) { // if(i + 1 == len) // query.append(Telephony.TextBasedSmsColumns.BODY + " like ?"); // else // query.append(Telephony.TextBasedSmsColumns.BODY + " like ? OR "); // // parameters[i] = IMAGE_HEADER + Byte.toUnsignedInt(data[0]) + i + "%"; // } // // Cursor cursor = SMSHandler.fetchSMSForImages(context, query.toString(), parameters, sms.getThreadId()); // Log.d(ImageHandler.class.getName(), "Data image founder counter: " + cursor.getCount() + "/" + len); // if(cursor.getCount() >= len) { // cursor.close(); // return cursor; // } // cursor.close(); // } return null; } public static Cursor getImagesCursorAtIndex(Context context, String RIL, int index) { RIL = IMAGE_HEADER + RIL; Log.d(ImageHandler.class.getName(), "Data image compose first index: " + RIL); Cursor cursorImageCursor = SMSHandler.fetchSMSForImagesByRIL(context, RIL); if(cursorImageCursor.moveToFirst()) { return cursorImageCursor; } return null; } public static byte[] getBitmapBytes(Bitmap bitmap) { int size = bitmap.getRowBytes() * bitmap.getHeight(); ByteBuffer buffer = ByteBuffer.allocate(size); bitmap.copyPixelsToBuffer(buffer); return buffer.array(); } public static Bitmap getImageFromBytes(byte[] bytes) { return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } public int[] getDimension(int width, int height, double ratio) { double wr = (double) width / height; double hr = (double) height / width; if(wr > hr) { width = (int) Math.round(ratio); height = (int) Math.round(ratio * hr); } else if(hr > wr) { height = (int) Math.round(ratio); width = (int) Math.round(ratio * wr); } else { width = (int) Math.round(ratio); height = (int) Math.round(ratio); } return new int[]{width, height}; } public static boolean isImageBody(byte[] data) { /** * 0 = Reference ID * 1 = Message ID * 2 = Total number of messages */ return data.length > 2 && Byte.toUnsignedInt(data[0]) >= ASCII_MAGIC_NUMBER && Byte.toUnsignedInt(data[1]) >= 0; } private boolean isImageHeader(SMS sms) { byte[] data = Base64.decode(sms.getBody(), Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); return bitmap != null || (data.length > 3 && Byte.toUnsignedInt(data[0]) >= ASCII_MAGIC_NUMBER && Byte.toUnsignedInt(data[1]) >= 0 && Byte.toUnsignedInt(data[2]) <= MAX_NUMBER_SMS); } public Bitmap resizeImage(double resValue) throws IOException { // use ratios for compressions rather than just raw values Log.d(getClass().getName(), "Resizing value: " + resValue); if(this.bitmap.getWidth() < resValue && this.bitmap.getHeight() < resValue) return this.bitmap; int[] dimensions = getDimension(this.bitmap.getWidth(), this.bitmap.getHeight(), resValue); int width = dimensions[0]; int height = dimensions[1]; this.edited = true; return Bitmap.createScaledBitmap(this.bitmap, width, height, true); } /** * Bitmap.Config.ARGB_8888 will produce the best quality image. * This is because it uses 32 bits per pixel, which allows for a wider range of colors and more detail. * createScaledBitmap will produce a lower quality image, because it uses a lower bit depth. * However, it will use less memory and be faster to render. * * Here is a table that summarizes the differences between the two methods: * * | Method | Bit depth | Quality | Memory usage | Speed | * |---|---|---|---|---| * | Bitmap.Config.ARGB_8888 | 32 bits | Best | High | Slow | * | createScaledBitmap | Lower bit depth | Lower | Low | Fast | * * Ultimately, the best method to use depends on your specific needs. * If you need the best possible quality image, then use Bitmap.Config.ARGB_8888. * If you need a lower quality image that uses less memory and is faster to render, then use createScaledBitmap. */ // public Bitmap resizeImage(double resValue) { // // Create a new bitmap with the desired width and height // if(this.bitmap.getWidth() < resValue && this.bitmap.getHeight() < resValue) // return this.bitmap; // // int[] dimensions = getDimension(this.bitmap.getWidth(), this.bitmap.getHeight(), resValue); // int width = dimensions[0]; // int height = dimensions[1]; // // Bitmap resizedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // // // Create a canvas and draw the original bitmap onto it at the desired size // Canvas canvas = new Canvas(resizedBitmap); // RectF destRect = new RectF(0, 0, width, height); // canvas.drawBitmap(bitmap, null, destRect, null); // // // Return the resized bitmap // return resizedBitmap; // } public static Bitmap removeAlpha(Bitmap bitmap) { if(bitmap.hasAlpha()) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap.Config config = Bitmap.Config.RGB_565; // or Bitmap.Config.ARGB_8888 for higher quality Bitmap newBitmap = Bitmap.createBitmap(width, height, config); Canvas canvas = new Canvas(newBitmap); canvas.drawColor(Color.WHITE); // set background color Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); paint.setFilterBitmap(true); canvas.drawBitmap(bitmap, 0, 0, paint); // bitmap.recycle(); // release original bitmap memory return newBitmap; } return bitmap; } public int getMaxResolution() { return Math.max(this.bitmap.getHeight(), this.bitmap.getWidth()); } public double shannonEntropy(byte[] values) { Map<Byte, Integer> map = new HashMap<Byte, Integer>(); // count the occurrences of each value for (Byte sequence : values) { if (!map.containsKey(sequence)) { map.put(sequence, 0); } map.put(sequence, map.get(sequence) + 1); } // calculate the entropy double result = 0.0; for (Byte sequence : map.keySet()) { double frequency = (double) map.get(sequence) / values.length; result -= frequency * (Math.log(frequency) / Math.log(2)); } return result; } public static boolean hasICCProfile(byte[] imageBytes) { return false; } public static byte[] extractContainerInformation(byte[] data) throws IOException { try { // Read the RIFF header byte[] riffHeader = new byte[4]; int iterator = riffHeader.length; System.arraycopy(data, 0, riffHeader, 0, riffHeader.length); if (!new String(riffHeader, StandardCharsets.US_ASCII).equals("RIFF")) { throw new IOException("Not a WebP file: missing RIFF header"); } // Read the file size (total size of the WebP container) byte[] fileSize = new byte[4]; System.arraycopy(data, iterator, fileSize, 0, fileSize.length); Log.d(ImageHandler.class.getName(), "File size: " + ByteBuffer.wrap(fileSize).order(ByteOrder.LITTLE_ENDIAN).getInt()); iterator += 4; // Read the file type (should be "WEBP") byte[] webpHeader = new byte[4]; System.arraycopy(data, iterator, webpHeader, 0, webpHeader.length); iterator += webpHeader.length; if (!new String(webpHeader, StandardCharsets.US_ASCII).equals("WEBP")) { throw new IOException("Not a WebP file: missing WEBP header: " + new String(webpHeader, StandardCharsets.US_ASCII)); } // Read the VP8 sub-chunk header byte[] vp8Header = new byte[8]; System.arraycopy(data, iterator, vp8Header, 0, vp8Header.length); String vp8HeaderId = new String(vp8Header, 0, 4, StandardCharsets.US_ASCII); int vp8HeaderSize = ByteBuffer.wrap(vp8Header, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); if (!vp8HeaderId.equals("VP8X") && !vp8HeaderId.equals("VP8 ")) { throw new IOException("Not a WebP file: missing VP8 sub-chunk: " + vp8HeaderId); } Log.d(ImageHandler.class.getName(), vp8HeaderId + " - " + vp8HeaderSize); // Skip the VP8 sub-chunk data iterator += vp8HeaderSize; List<String> subChunkHeaders = new ArrayList<String>(); subChunkHeaders.add("VP8X"); subChunkHeaders.add("VP8 "); subChunkHeaders.add("ICCP"); subChunkHeaders.add("ANIM"); subChunkHeaders.add("EXIF"); subChunkHeaders.add("XMP "); subChunkHeaders.add("ALPH"); while (iterator < data.length) { byte[] subChunkHeader = new byte[8]; System.arraycopy(data, iterator, subChunkHeader, 0, subChunkHeader.length); String subChunkId = new String(subChunkHeader, 0, 4, StandardCharsets.US_ASCII); int subChunkSize = ByteBuffer.wrap(subChunkHeader, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); iterator += subChunkHeader.length; if (subChunkHeaders.contains(subChunkId)) { Log.d(ImageHandler.class.getName(), subChunkId + ":" + subChunkSize); // byte[] subChunkData = new byte[subChunkSize]; // System.arraycopy(data, iterator, subChunkData, 0, subChunkData.length); if(subChunkId.equals("ICCP")) { byte[] dataMinusICCP = new byte[data.length - (subChunkSize + subChunkHeader.length)]; System.arraycopy(data, 0, dataMinusICCP, 0, iterator - subChunkHeader.length); System.arraycopy(data, iterator + subChunkSize, dataMinusICCP, iterator - subChunkHeader.length, data.length - (iterator + subChunkSize)); data = dataMinusICCP; iterator -= subChunkHeader.length; } else iterator += subChunkSize; } } } catch(Exception e) { e.printStackTrace(); } return data; } }
18,637
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RoomMigrationTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/RoomMigrationTest.java
package java.com.afkanerd.deku; import android.content.Context; import android.database.sqlite.SQLiteStatement; import androidx.room.testing.MigrationTestHelper; import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.sqlite.db.SupportSQLiteStatement; import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; 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 org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; @RunWith(AndroidJUnit4.class) public class RoomMigrationTest { private static final String TEST_DB = Datastore.databaseName; @Rule public MigrationTestHelper helper; Context context; public RoomMigrationTest() { this.context = InstrumentationRegistry.getInstrumentation().getTargetContext(); helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(), Datastore.class.getCanonicalName(), new FrameworkSQLiteOpenHelperFactory()); } @Test public void migrate11To12Test() throws IOException { SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 11); String tableName = "ThreadedConversations"; String sql = "INSERT INTO " + tableName + " (" + "thread_id, " + "address, " + "msg_count, " + "type, " + "date, " + "is_archived, " + "is_blocked, " + "is_shortcode, " + "is_read, " + "snippet, " + "contact_name, " + "formatted_datetime, " + "is_read" + ") VALUES "; // Add each row as a separate VALUES clause sql += "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"; // Prepare the SQL statement with placeholders SupportSQLiteStatement statement = db.compileStatement(sql); // Bind values for each row statement.bindString(1, "test_thread_id_1"); statement.bindString(2, "test_address_1"); statement.bindLong(3, 5); statement.bindLong(13, 5); statement.bindString(4, "test_address_1"); statement.bindLong(5, 5); statement.bindLong(6, 5); statement.bindLong(7, 5); statement.bindLong(8, 5); statement.bindString(9, "test_address_1"); statement.bindString(10, "test_address_1"); statement.bindString(11, "test_address_1"); statement.bindLong(12, 5); // Execute the statement statement.execute(); // Close the statement statement.close(); db = helper.runMigrationsAndValidate(TEST_DB, 12, true, new Migrations.MIGRATION_11_12()); } }
3,034
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
RMQConnectionTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/QueueListener/RMQConnectionTest.java
package java.com.afkanerd.deku.QueueListener; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import android.content.Context; import android.telephony.SubscriptionInfo; import android.util.Log; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.afkanerd.deku.DefaultSMS.BuildConfig; import com.afkanerd.deku.DefaultSMS.Models.Conversations.Conversation; import com.afkanerd.deku.DefaultSMS.Models.Conversations.ConversationHandler; import com.afkanerd.deku.DefaultSMS.Models.Database.SemaphoreManager; import com.afkanerd.deku.DefaultSMS.Models.SIMHandler; import com.afkanerd.deku.DefaultSMS.Models.SMSDatabaseWrapper; import com.afkanerd.deku.DefaultSMS.R; import com.afkanerd.deku.QueueListener.GatewayClients.GatewayClient; import com.afkanerd.deku.QueueListener.RMQ.RMQConnection; import com.afkanerd.deku.QueueListener.RMQ.RMQMonitor; import com.rabbitmq.client.CancelCallback; import com.rabbitmq.client.Channel; 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.ShutdownListener; import com.rabbitmq.client.ShutdownSignalException; import com.rabbitmq.client.impl.DefaultExceptionHandler; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; @RunWith(AndroidJUnit4.class) public class RMQConnectionTest { Context context; Properties properties = new Properties(); ExecutorService consumerExecutorService = Executors.newFixedThreadPool(1); // Create a pool of 5 worker threads public RMQConnectionTest() throws IOException { this.context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream inputStream = this.context.getResources() .openRawResource(R.raw.app); properties.load(inputStream); } @Test public void connectionTest() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername(properties.getProperty("username")); factory.setPassword(properties.getProperty("password")); factory.setVirtualHost(properties.getProperty("virtualhost")); factory.setHost(properties.getProperty("host")); factory.setPort(Integer.parseInt(properties.getProperty("port"))); factory.setAutomaticRecoveryEnabled(true); factory.setNetworkRecoveryInterval(10000); factory.setExceptionHandler(new DefaultExceptionHandler()); Connection connection = factory.newConnection(consumerExecutorService, "android-studio-test-case"); RMQConnection rmqConnection = new RMQConnection(connection); final Channel channel = rmqConnection.createChannel(); channel.basicRecover(true); String defaultExchange = properties.getProperty("exchange"); String defaultQueueName = "android_studio_testing_queue"; String defaultQueueName1 = "android_studio_testing_queue1"; String defaultBindingKey = "#.62401"; String defaultBindingKey1 = "*.routing.62401"; String defaultRoutingKey = "testing.routing.62401"; rmqConnection.createQueue(defaultExchange, defaultBindingKey, channel, defaultQueueName); rmqConnection.createQueue(defaultExchange, defaultBindingKey1, channel, defaultQueueName1); channel.queuePurge(defaultQueueName); channel.queuePurge(defaultQueueName1); long messageCount = channel.messageCount(defaultQueueName); assertEquals(0, messageCount); messageCount = channel.messageCount(defaultQueueName1); assertEquals(0, messageCount); String basicMessage = "hello world 0"; channel.basicPublish(defaultExchange, defaultRoutingKey, null, basicMessage.getBytes(StandardCharsets.UTF_8)); Set<String> consumerTags = new HashSet<>(); final boolean[] shutdownDown = {false}; ConsumerShutdownSignalCallback consumerShutdownSignalCallback = new ConsumerShutdownSignalCallback() { @Override public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { shutdownDown[0] = true; consumerTags.remove(consumerTag); rmqConnection.removeChannel(channel); } }; final boolean[] delivered = {false}; DeliverCallback deliverCallback = new DeliverCallback() { @Override public void handle(String consumerTag, Delivery message) throws IOException { delivered[0] = true; channel.basicAck(message.getEnvelope().getDeliveryTag(), false); } }; DeliverCallback deliverCallback1 = new DeliverCallback() { @Override public void handle(String consumerTag, Delivery message) throws IOException { } }; String consumerTag = channel.basicConsume(defaultQueueName, false, deliverCallback, consumerShutdownSignalCallback); consumerTags.add(consumerTag); /** * This causes an error which forces the channel to close. * This behaviour can then be observed. */ try { String nonExistentExchangeName = "nonExistentExchangeName"; String nonExistentBindingName = "nonExistentBindingName"; rmqConnection.createQueue(nonExistentExchangeName, nonExistentBindingName, channel, null); } catch (Exception e) { e.printStackTrace(); } finally { assertTrue(connection.isOpen()); assertFalse(channel.isOpen()); } assertTrue(delivered[0]); assertTrue(shutdownDown[0]); assertFalse(consumerTags.contains(consumerTag)); assertEquals(0, rmqConnection.channelList.size()); Channel channel1 = rmqConnection.createChannel(); messageCount = channel1.messageCount(defaultQueueName); assertEquals(0, messageCount); messageCount = channel1.messageCount(defaultQueueName1); assertEquals(1, messageCount); channel1.basicConsume(defaultQueueName1, false, deliverCallback1, consumerShutdownSignalCallback); messageCount = channel1.messageCount(defaultQueueName1); assertEquals(0, messageCount); try { String nonExistentExchangeName = "nonExistentExchangeName"; String nonExistentBindingName = "nonExistentBindingName"; rmqConnection.createQueue(nonExistentExchangeName, nonExistentBindingName, channel1, null); } catch (Exception e) { e.printStackTrace(); } finally { assertTrue(connection.isOpen()); assertFalse(channel1.isOpen()); } connection.abort(); assertFalse(connection.isOpen()); assertFalse(channel1.isOpen()); } @Test public void semaphoreTest() throws InterruptedException { final long[] startTime = {0}; final long[] endTime = {0}; final long[] startTime1 = {0}; final long[] endTime1 = {0}; Thread thread = new Thread(new Runnable() { @Override public void run() { try { SemaphoreManager.acquireSemaphore(); Log.d(getClass().getName(), "Thread 1 acquired!"); startTime[0] = System.currentTimeMillis(); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { SemaphoreManager.releaseSemaphore(); Log.d(getClass().getName(), "Thread 1 released!: " + System.currentTimeMillis()); endTime[0] = System.currentTimeMillis(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { Log.d(getClass().getName(), "Thread 2 requested!: " + System.currentTimeMillis()); SemaphoreManager.acquireSemaphore(); Log.d(getClass().getName(), "Thread 2 acquired!: " + System.currentTimeMillis()); startTime1[0] = System.currentTimeMillis(); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { SemaphoreManager.releaseSemaphore(); Log.d(getClass().getName(), "Thread 2 released!: " + System.currentTimeMillis()); endTime1[0] = System.currentTimeMillis(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); thread.start(); thread1.start(); thread1.join(); thread.join(); assertTrue(endTime[0] <= startTime1[0]); } }
9,945
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ConversationsThreadsEncryptionTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/E2EE/ConversationsThreadsEncryptionTest.java
package java.com.afkanerd.deku.E2EE; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import android.content.Context; import android.util.Base64; import android.util.Log; import android.util.Pair; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryption; import com.afkanerd.deku.E2EE.ConversationsThreadsEncryptionDao; import com.afkanerd.deku.E2EE.E2EEHandler; import com.afkanerd.smswithoutborders.libsignal_doubleratchet.CryptoHelpers; import com.afkanerd.smswithoutborders.libsignal_doubleratchet.KeystoreHelpers; import com.afkanerd.smswithoutborders.libsignal_doubleratchet.SecurityAES; import com.google.i18n.phonenumbers.NumberParseException; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.CertificateException; import javax.crypto.SecretKey; @RunWith(AndroidJUnit4.class) public class ConversationsThreadsEncryptionTest { Context context; public ConversationsThreadsEncryptionTest() throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, InterruptedException { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); KeystoreHelpers.removeAllFromKeystore(context); } @Test public void getKeyStoreAliasTest() throws NumberParseException { String address = "+237111111111"; int sessionNumber = 0; String keystoreAlias = "MjM3MTExMTExMTExXzA="; String outputKeystoreAlias = E2EEHandler.deriveKeystoreAlias(address, sessionNumber); assertEquals(keystoreAlias, outputKeystoreAlias); } @Test public void getAddressFromKeystore() throws NumberParseException { String address = "+237222222222"; String keystoreAlias = E2EEHandler.deriveKeystoreAlias(address, 0); String derivedAddress = E2EEHandler.getAddressFromKeystore(keystoreAlias); assertEquals(address, derivedAddress); } @Test public void testCanCreateAndRemoveKeyPair() throws GeneralSecurityException, IOException, InterruptedException { String keystoreAlias = "MjM3NjEyMzQ1Njc4XzA="; E2EEHandler.createNewKeyPair(context, keystoreAlias); assertTrue(E2EEHandler.isAvailableInKeystore(keystoreAlias)); E2EEHandler.removeFromKeystore(context, keystoreAlias); assertFalse(E2EEHandler.isAvailableInKeystore(keystoreAlias)); KeystoreHelpers.removeAllFromKeystore(context); } @Test public void testSize() throws GeneralSecurityException, IOException, InterruptedException { String keystoreAlias = "MjM3NjEyMzQ1Njc4XzA=TS"; PublicKey publicKey = E2EEHandler.createNewKeyPair(context, keystoreAlias); int length = publicKey.getEncoded().length; assertEquals(91, length); KeystoreHelpers.removeAllFromKeystore(context); } @Test public void testIsValidAgreementPubKey() throws GeneralSecurityException, IOException, InterruptedException { String keystoreAlias = "MjM3NjEyMzQ1Njc4XzA=VA"; PublicKey publicKey = E2EEHandler.createNewKeyPair(context, keystoreAlias); byte[] dekuPublicKey = E2EEHandler.buildDefaultPublicKey(publicKey.getEncoded()); assertTrue(E2EEHandler.isValidDefaultPublicKey(dekuPublicKey)); SecretKey secretKey = SecurityAES.generateSecretKey(91); byte[] invalidPublicKey = E2EEHandler.buildDefaultPublicKey(secretKey.getEncoded()); assertFalse(E2EEHandler.isValidDefaultPublicKey(invalidPublicKey)); KeystoreHelpers.removeAllFromKeystore(context); } @Test public void testBuildForEncryptionRequest() throws Exception { String address = "+237333333333"; byte[] transmissionRequest = E2EEHandler.buildForEncryptionRequest(context, address).second; assertTrue(E2EEHandler.isValidDefaultPublicKey(transmissionRequest)); } @Test public void canBeTransmittedAsData() throws Exception { String address = "+237444444444"; byte[] transmissionRequest = E2EEHandler.buildForEncryptionRequest(context, address).second; assertTrue(transmissionRequest.length < 120); } @Test public void canDoubleRatchet() throws Throwable { ConversationsThreadsEncryption conversationsThreadsEncryption = new ConversationsThreadsEncryption(); ConversationsThreadsEncryptionDao conversationsThreadsEncryptionDao = conversationsThreadsEncryption.getDaoInstance(context); String aliceAddress = "+237555555555"; String bobAddress = "+237666666666"; // Initial request String aliceKeystoreAlias = E2EEHandler.deriveKeystoreAlias(bobAddress, 0); Pair<String, byte[]> keystorePairAlice = E2EEHandler.buildForEncryptionRequest(context, bobAddress); // String aliceKeystoreAlias = keystorePairAlice.first; byte[] aliceTransmissionKey = keystorePairAlice.second; // bob received alice's key assertTrue(E2EEHandler.isValidDefaultPublicKey(aliceTransmissionKey)); String bobKeystoreAlias = E2EEHandler.deriveKeystoreAlias(aliceAddress, 0); byte[] aliceExtractedTransmissionKey = E2EEHandler.extractTransmissionKey(aliceTransmissionKey); E2EEHandler.insertNewAgreementKeyDefault(context, aliceExtractedTransmissionKey, bobKeystoreAlias); // Agreement request Pair<String, byte[]> keystorePairBob = E2EEHandler.buildForEncryptionRequest(context, aliceAddress); // String bobKeystoreAlias = keystorePairBob.first; byte[] bobTransmissionKey = keystorePairBob.second; // alice received bob's key assertTrue(E2EEHandler.isValidDefaultPublicKey(bobTransmissionKey)); byte[] bobExtractedTransmissionKey = E2EEHandler.extractTransmissionKey(bobTransmissionKey); E2EEHandler.insertNewAgreementKeyDefault(context, bobExtractedTransmissionKey, aliceKeystoreAlias); assertTrue(E2EEHandler.isAvailableInKeystore(aliceKeystoreAlias)); assertTrue(E2EEHandler.isAvailableInKeystore(bobKeystoreAlias)); assertTrue(E2EEHandler.canCommunicateSecurely(context, aliceKeystoreAlias)); assertTrue(E2EEHandler.canCommunicateSecurely(context, bobKeystoreAlias)); // ----> alice sends the message byte[] aliceText = CryptoHelpers.generateRandomBytes(130); byte[][] aliceCipherText = E2EEHandler.encrypt(context, aliceKeystoreAlias, aliceText); String aliceTransmissionText = E2EEHandler.buildTransmissionText(aliceCipherText[0]); // <----- bob receives the message assertTrue(E2EEHandler.isValidDefaultText(aliceTransmissionText)); byte[] aliceExtractedText = E2EEHandler.extractTransmissionText(aliceTransmissionText); byte[] alicePlainText = E2EEHandler.decrypt(context, bobKeystoreAlias, aliceExtractedText, null, null); assertArrayEquals(aliceText, alicePlainText); // <---- bob sends a message byte[] bobText = CryptoHelpers.generateRandomBytes(130); byte[][] bobCipherText = E2EEHandler.encrypt(context, bobKeystoreAlias, bobText); String bobTransmissionText = E2EEHandler.buildTransmissionText(bobCipherText[0]); // <----- bob receives the message again - as would be on mobile devices aliceExtractedText = E2EEHandler.extractTransmissionText(aliceTransmissionText); alicePlainText = E2EEHandler.decrypt(context, bobKeystoreAlias, aliceExtractedText, aliceCipherText[1], null); assertArrayEquals(aliceText, alicePlainText); // <---- alice receives bob's message assertTrue(E2EEHandler.isValidDefaultText(bobTransmissionText)); byte[] bobExtractedText = E2EEHandler.extractTransmissionText(bobTransmissionText); byte[] bobPlainText = E2EEHandler.decrypt(context, aliceKeystoreAlias, bobExtractedText, null, null); assertArrayEquals(bobText, bobPlainText); // <---- bob sends a message bobText = CryptoHelpers.generateRandomBytes(130); bobCipherText = E2EEHandler.encrypt(context, bobKeystoreAlias, bobText); bobTransmissionText = E2EEHandler.buildTransmissionText(bobCipherText[0]); // <---- then bob sends another byte[] bobText1 = CryptoHelpers.generateRandomBytes(130); byte[][] bobCipherText1 = E2EEHandler.encrypt(context, bobKeystoreAlias, bobText1); String bobTransmissionText1 = E2EEHandler.buildTransmissionText(bobCipherText1[0]); // ----> alice sends the message aliceText = CryptoHelpers.generateRandomBytes(130); aliceCipherText = E2EEHandler.encrypt(context, aliceKeystoreAlias, aliceText); aliceTransmissionText = E2EEHandler.buildTransmissionText(aliceCipherText[0]); // <----- bob receives the message assertTrue(E2EEHandler.isValidDefaultText(aliceTransmissionText)); aliceExtractedText = E2EEHandler.extractTransmissionText(aliceTransmissionText); alicePlainText = E2EEHandler.decrypt(context, bobKeystoreAlias, aliceExtractedText, null, null); assertArrayEquals(aliceText, alicePlainText); // <---- alice receives bob's message - this message is out of order assertTrue(E2EEHandler.isValidDefaultText(bobTransmissionText1)); bobExtractedText = E2EEHandler.extractTransmissionText(bobTransmissionText1); bobPlainText = E2EEHandler.decrypt(context, aliceKeystoreAlias, bobExtractedText, null, null); assertArrayEquals(bobText1, bobPlainText); // <---- alice receives bob's message assertTrue(E2EEHandler.isValidDefaultText(bobTransmissionText)); bobExtractedText = E2EEHandler.extractTransmissionText(bobTransmissionText); bobPlainText = E2EEHandler.decrypt(context, aliceKeystoreAlias, bobExtractedText, null, null); assertArrayEquals(bobText, bobPlainText); } }
10,429
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
DatabaseTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/DefaultSMS/DatabaseTest.java
package java.com.afkanerd.deku.DefaultSMS; import android.content.Context; import android.database.Cursor; import android.provider.Telephony; import android.util.Log; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; @RunWith(AndroidJUnit4.class) public class DatabaseTest { Context context; public DatabaseTest() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); } @Test public void testThreads() { Cursor cursor = context.getContentResolver().query( Telephony.Threads.CONTENT_URI, null, null, null, null ); String[] columnNames = cursor.getColumnNames(); Log.d(getClass().getName(), Arrays.toString(columnNames)); if(cursor.moveToFirst()) { do { for(String columnName : columnNames) Log.d(getClass().getName(), columnName + ": " + cursor.getString(cursor.getColumnIndex(columnName))); Log.d(getClass().getName(), "\n"); } while(cursor.moveToNext()); } } }
1,302
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
ThreadedConversationsTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/DefaultSMS/ThreadedConversationsTest.java
package java.com.afkanerd.deku.DefaultSMS; import static org.junit.Assert.assertEquals; import android.content.Context; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; 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 org.junit.Test; import org.junit.runner.RunWith; import java.util.List; @RunWith(AndroidJUnit4.class) public class ThreadedConversationsTest { Context context; public ThreadedConversationsTest() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); } }
816
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
HelpersTest.java
/FileExtraction/Java_unseen/deku-messaging_Deku-SMS-Android/app/src/androidTest/java/java/com/afkanerd/deku/DefaultSMS/Commons/HelpersTest.java
package java.com.afkanerd.deku.DefaultSMS.Commons; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import android.telephony.PhoneNumberUtils; import android.text.SpannableString; import android.util.Log; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @RunWith(AndroidJUnit4.class) public class HelpersTest { @Test public void testRegexForConversations() { String phoneNumber1 = "+237612345678"; String website1 = "website.com"; String website2 = "https://sub.site.website"; String website3 = "sub.second.website/"; String website4 = "sub.second.website/main.php"; String website5 = "sub.second.website/main"; String website6 = "sub.second.website/main/test/site.com"; String website7 = "sub.second.website/main/test/site.com?page=0"; String website8 = "https://github.com/simple-login/app/blob/master/docs/api.md#get-apialiasesalias_idcontacts"; String website9 = "http://website.com"; String email1 = "[email protected]"; String testString = "Hello world! Now, let's encode " + website1 + " to communicate through " + "emails using " + email1 + " This should call " + phoneNumber1 +". Then another website " + "such as " + website2 + " and " + website3 + " and " + website4 + " and " + website5 + " and " + website6 + " and " + website7 + " and " + website8 + " and to see about long queries. " + website9; String urlPattern = "((mailto:)?[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+)" + "|((\\+?[0-9]{1,3}?)[ \\-]?)?([\\(]{1}[0-9]{3}[\\)])?[ \\-]?[0-9]{3}[ \\-]?[0-9]{4}" + // "|((https?|ftp|file)://)?[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*(/\\S*)"+ "|(https?://)?([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}(/[\\w\\.-]+)*"; SpannableString spannableString = new SpannableString(testString); Pattern pattern = Pattern.compile(urlPattern); Matcher matcher = pattern.matcher(spannableString); List<String> isPhoneCount = new ArrayList<>(); List<String> isEmailCount = new ArrayList<>(); List<String> isWebsiteCount = new ArrayList<>(); List<String> isPhoneCountExpected = new ArrayList<>(); isPhoneCountExpected.add(phoneNumber1); List<String> isEmailCountExpected = new ArrayList<>(); isEmailCountExpected.add(email1); List<String> isWebsiteCountExpected = new ArrayList<>(); isWebsiteCountExpected.add(website1); isWebsiteCountExpected.add(website2); isWebsiteCountExpected.add(website3); isWebsiteCountExpected.add(website4); isWebsiteCountExpected.add(website5); isWebsiteCountExpected.add(website6); isWebsiteCountExpected.add(website7); isWebsiteCountExpected.add(website8); isWebsiteCountExpected.add(website9); while (matcher.find()) { String tmp_url = matcher.group(); if (PhoneNumberUtils.isWellFormedSmsAddress(tmp_url)) { isPhoneCount.add(tmp_url); } else if (tmp_url.contains("@")) { isEmailCount.add(tmp_url); } else { isWebsiteCount.add(tmp_url); } } Log.d(getClass().getName(), "Websites: " + isWebsiteCountExpected); Log.d(getClass().getName(), "Websites count: " + isWebsiteCount); assertArrayEquals(isEmailCountExpected.toArray(new String[0]), isEmailCount.toArray(new String[0])); assertArrayEquals(isWebsiteCountExpected.toArray(new String[0]), isWebsiteCount.toArray(new String[0])); assertArrayEquals(isPhoneCountExpected.toArray(new String[0]), isPhoneCount.toArray(new String[0])); } }
4,167
Java
.java
deku-messaging/Deku-SMS-Android
171
11
26
2021-12-16T13:07:42Z
2024-05-06T18:37:37Z
AddFundsSheet.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/AddFundsSheet.java
package com.lako.walletcount; import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.android.material.textfield.TextInputEditText; import java.text.NumberFormat; import java.text.ParseException; import java.util.Objects; public class AddFundsSheet extends BottomSheetDialogFragment { private TextInputEditText fundsToAdd; private TextView amount; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { setStyle(STYLE_NORMAL, R.style.BottomSheet); View view = inflater.inflate(R.layout.add_funds_bottomsheet, container, false); Button addFunds = view.findViewById(R.id.add_funds_button); amount = requireActivity().findViewById(R.id.home_amountText); fundsToAdd = view.findViewById(R.id.add_funds_textEdit); fundsToAdd.requestFocus(); requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); addFunds.setOnClickListener(v -> { if(Objects.requireNonNull(fundsToAdd.getText()).toString().length() == 0){ fundsToAdd.setText("0"); } try { double num1 = Objects.requireNonNull(NumberFormat.getInstance().parse(fundsToAdd.getText().toString().replaceAll("[^\\d.,-]", ""))).doubleValue(); double num2 = Objects.requireNonNull(NumberFormat.getInstance().parse(amount.getText().toString().replaceAll("[^\\d.,-]", ""))).doubleValue(); double sum = num1 + num2; amount.setText(NumberFormat.getCurrencyInstance().format(sum)); SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, amount.getText().toString()); editor.apply(); dismiss(); }catch(NumberFormatException | ParseException exception){ new AlertDialog.Builder(v.getContext()) .setTitle("Error") .setMessage("Invalid number was entered.") .setNeutralButton("OK", null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } }); return view; } }
2,951
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
WalletCountApplication.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/WalletCountApplication.java
package com.lako.walletcount; import android.app.Application; import android.content.res.Configuration; public class WalletCountApplication extends Application { private static WalletCountApplication instance; @Override public void onCreate() { super.onCreate(); instance = this; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void onLowMemory() { super.onLowMemory(); } public static WalletCountApplication getInstance() { return instance; } }
630
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
SetBudgetSheet.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/SetBudgetSheet.java
package com.lako.walletcount; import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.android.material.textfield.TextInputEditText; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.Objects; public class SetBudgetSheet extends BottomSheetDialogFragment { private TextInputEditText inputEditText; private TextView budget; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "textbudget"; public static final String OGTEXT = "originalbudget"; public static final String MONTH = "monthOfBudget"; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { setStyle(STYLE_NORMAL, R.style.BottomSheet); View view = inflater.inflate(R.layout.budget_bottomsheet, container, false); inputEditText = view.findViewById(R.id.budget_textEdit); Button setBudget = view.findViewById(R.id.budget_button); budget = requireActivity().findViewById(R.id.budget_AmountText); inputEditText.requestFocus(); requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); setBudget.setOnClickListener(v -> { if(Objects.requireNonNull(inputEditText.getText()).toString().length() == 0){ inputEditText.setText("0"); } try { double num1 = 0; try { num1 = Objects.requireNonNull(NumberFormat.getInstance(Locale.getDefault()).parse(inputEditText.getText().toString().replaceAll("[^\\d.,-]", ""))).doubleValue(); } catch (ParseException e) { e.printStackTrace(); } budget.setText(NumberFormat.getCurrencyInstance().format(num1)); Calendar cal = Calendar.getInstance(); SimpleDateFormat month_date = new SimpleDateFormat("MMMM", Locale.getDefault()); String month_name = month_date.format(cal.getTime()); SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, budget.getText().toString()); editor.putString(OGTEXT, budget.getText().toString()); editor.putString(MONTH, month_name); editor.apply(); dismiss(); }catch(NumberFormatException exception){ new AlertDialog.Builder(v.getContext()) .setTitle("Error") .setMessage("Invalid number was entered.") .setNeutralButton("OK", null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } }); return view; } }
3,445
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
WalletWidget.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/WalletWidget.java
package com.lako.walletcount; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.SharedPreferences; import android.widget.RemoteViews; /** * Implementation of App Widget functionality. */ public class WalletWidget extends AppWidgetProvider { public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { //CharSequence widgetText = context.getString(R.string.appwidget_text); SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); CharSequence widgetText = sharedPreferences.getString(TEXT, "0.00"); // Construct the RemoteViews object RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wallet_widget); views.setTextViewText(R.id.appwidget_text, widgetText); // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple widgets active, so update all of them for (int appWidgetId : appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId); } } @Override public void onEnabled(Context context) { // Enter relevant functionality for when the first widget is created //CharSequence widgetText = context.getString(R.string.appwidget_text); SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); CharSequence widgetText = sharedPreferences.getString(TEXT, "0.00"); // Construct the RemoteViews object RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.wallet_widget); views.setTextViewText(R.id.appwidget_text, widgetText); } @Override public void onDisabled(Context context) { // Enter relevant functionality for when the last widget is disabled } }
2,260
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
MainActivity.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/MainActivity.java
package com.lako.walletcount; import android.os.Bundle; import android.view.View; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import java.util.Objects; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView navView = findViewById(R.id.nav_view); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( R.id.navigation_home, R.id.navigation_dashboard) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(navView, navController); Objects.requireNonNull(getSupportActionBar()).setElevation(0); navView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } }
1,429
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
SpendFundsSheet.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/SpendFundsSheet.java
package com.lako.walletcount; import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import com.google.android.material.textfield.TextInputEditText; import java.text.NumberFormat; import java.text.ParseException; import java.util.Objects; public class SpendFundsSheet extends BottomSheetDialogFragment { private TextInputEditText fundsToRemove; private TextView amount; private String textBudget; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; public static final String TEXTBUDGET = "textbudget"; public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { setStyle(STYLE_NORMAL, R.style.BottomSheet); View view = inflater.inflate(R.layout.spend_funds_bottomsheet, container, false); SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); Button spendFunds = view.findViewById(R.id.pay_Button); amount = requireActivity().findViewById(R.id.home_amountText); fundsToRemove = view.findViewById(R.id.pay_textEdit); fundsToRemove.requestFocus(); requireDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); textBudget = sharedPreferences.getString(TEXTBUDGET, "0.00"); spendFunds.setOnClickListener(v -> { if(Objects.requireNonNull(fundsToRemove.getText()).toString().length() == 0){ fundsToRemove.setText("0"); } try { double num1 = Objects.requireNonNull(NumberFormat.getInstance().parse(fundsToRemove.getText().toString().replaceAll("[^\\d.,-]", ""))).doubleValue(); double num2 = Objects.requireNonNull(NumberFormat.getInstance().parse(amount.getText().toString().replaceAll("[^\\d.,-]", ""))).doubleValue(); double num3 = Objects.requireNonNull(NumberFormat.getInstance().parse(textBudget.replaceAll("[^\\d.,-]", ""))).doubleValue(); double budgetSum = num3 - num1; double sum = num2 - num1; textBudget = NumberFormat.getCurrencyInstance().format(budgetSum); amount.setText(NumberFormat.getCurrencyInstance().format(sum)); SharedPreferences sharedPreferences1 = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences1.edit(); editor.putString(TEXT, amount.getText().toString()); editor.putString(TEXTBUDGET, textBudget); editor.apply(); dismiss(); }catch(NumberFormatException | ParseException exception){ new AlertDialog.Builder(v.getContext()) .setTitle("Error") .setMessage("Invalid number was entered.") .setNeutralButton("OK", null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } }); return view; } }
3,548
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
DataManager.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/utils/DataManager.java
package com.lako.walletcount.utils; import android.content.Context; import android.content.SharedPreferences; import com.lako.walletcount.WalletCountApplication; public class DataManager { private SharedPreferences sharedPreferences; private String legacyMoney = "0.00"; private double money = 0; private double budget = 0; public DataManager() { sharedPreferences = WalletCountApplication.getInstance().getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE); } private void loadData() { legacyMoney = sharedPreferences.getString("text", "0.00"); money = sharedPreferences.getFloat("money", 0); budget = sharedPreferences.getFloat("budget", 0); } private void localizeData() { //TODO - Localization with custom currency settings. Symbol and type (period,comma,nothing). } }
876
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
ExpenseAdapter.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/expenses/ExpenseAdapter.java
package com.lako.walletcount.expenses; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.lako.walletcount.R; import java.util.ArrayList; public class ExpenseAdapter extends RecyclerView.Adapter<ExpenseAdapter.ExpenseViewHolder> { private ArrayList<Expense> expenses; public ExpenseAdapter(ArrayList<Expense> expenses) { this.expenses = expenses; } public class ExpenseViewHolder extends RecyclerView.ViewHolder { private TextView expenseTitle; private TextView expenseCost; public ExpenseViewHolder(final View view) { super(view); expenseTitle = view.findViewById(R.id.expense_title); expenseCost = view.findViewById(R.id.expense_cost); } } @NonNull @Override public ExpenseAdapter.ExpenseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.expense_item, parent, false); return new ExpenseViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull ExpenseViewHolder holder, int position) { String expenseTitle = expenses.get(position).getExpenseName(); double expenseCost = expenses.get(position).getExpenseCost(); holder.expenseTitle.setText(expenseTitle); if(expenses.get(position).getIsExpensePay()) { holder.expenseCost.setText("-" + expenseCost); }else { holder.expenseCost.setText("+" + expenseCost); } } @Override public int getItemCount() { return expenses.size(); } }
1,834
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
Expense.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/expenses/Expense.java
package com.lako.walletcount.expenses; public class Expense { private String expenseName; private double expenseCost; private boolean isExpensePay; public Expense(String n, double c, boolean p) { expenseName = n; expenseCost = c; isExpensePay = p; } public String getExpenseName() { return expenseName; } public double getExpenseCost() { return expenseCost; } public boolean getIsExpensePay() { return isExpensePay; } }
533
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
HomeFragment.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/ui/home/HomeFragment.java
package com.lako.walletcount.ui.home; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.lako.walletcount.AddFundsSheet; import com.lako.walletcount.R; import com.lako.walletcount.SpendFundsSheet; import com.lako.walletcount.expenses.Expense; import com.lako.walletcount.expenses.ExpenseAdapter; import java.lang.reflect.Array; import java.sql.Struct; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Objects; public class HomeFragment extends Fragment { private String text; private TextView amount; private RecyclerView expenseRecycler; private ArrayList<Expense> expenses; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_home, container, false); amount = root.findViewById(R.id.home_amountText); //TODO - Use official M3 colors, instead of current hacky solution. //TODO - Make RecyclerView and Header scrollable at **once**, not separately. expenseRecycler = root.findViewById(R.id.expense_recycler); expenses = new ArrayList<>(); final Button addFundsButton = root.findViewById(R.id.home_addButton); addFundsButton.setOnClickListener(v -> { AddFundsSheet addFundsDialog = new AddFundsSheet(); addFundsDialog.show(requireActivity().getSupportFragmentManager(), "addFundsDialogBox"); }); final Button spendFundsButton = root.findViewById(R.id.home_payButton); spendFundsButton.setOnClickListener(v -> { SpendFundsSheet spendFundsDialog = new SpendFundsSheet(); spendFundsDialog.show(requireActivity().getSupportFragmentManager(), "spendFundsDialogBox"); }); loadData(); setAdapter(); getExpenses(); updateViews(); return root; } private void loadData(){ SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); text = sharedPreferences.getString(TEXT, "0.00"); } private void updateViews(){ double amountDouble = 0.00; try { amountDouble = Objects.requireNonNull(NumberFormat.getInstance().parse(text.replaceAll("[^\\d.,-]", ""))).doubleValue(); } catch (ParseException e) { e.printStackTrace(); } amount.setText(NumberFormat.getCurrencyInstance().format(amountDouble)); } private void setAdapter() { ExpenseAdapter adapter = new ExpenseAdapter(expenses); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext().getApplicationContext()); expenseRecycler.setLayoutManager(layoutManager); //TODO - Potentially use custom animator? expenseRecycler.setItemAnimator(new DefaultItemAnimator()); expenseRecycler.setAdapter(adapter); } private void getExpenses() { //TODO - Add saving/loading of expenses. //Placeholders expenses.add(new Expense("Test Pay", 10.00, true)); expenses.add(new Expense("Test Add", 25.00, false)); expenses.add(new Expense("Trip to mall", 250.50, true)); expenses.add(new Expense("Winning!", 5.00, false)); expenses.add(new Expense("Paycheck", 150.00, false)); expenses.add(new Expense("Rent", 250.00, true)); } }
4,011
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
DashboardFragment.java
/FileExtraction/Java_unseen/GittyMac_WalletCount/app/src/main/java/com/lako/walletcount/ui/dashboard/DashboardFragment.java
package com.lako.walletcount.ui.dashboard; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.lako.walletcount.R; import com.lako.walletcount.SetBudgetSheet; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.Objects; public class DashboardFragment extends Fragment { private TextView amountLeft; private ProgressBar progressBar; private String textBudget; private String lastMonth; private String defBudget; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "textbudget"; public static final String MONTH = "monthOfBudget"; public static final String OGTEXT = "originalbudget"; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_dashboard, container, false); amountLeft = root.findViewById(R.id.budget_AmountText); TextView message1 = root.findViewById(R.id.budget_feedbackHeading); TextView message2 = root.findViewById(R.id.budget_feedbackDetails); Button setBudget = root.findViewById(R.id.budget_adjustButton); progressBar = root.findViewById(R.id.budgetRing); Calendar cal=Calendar.getInstance(); SimpleDateFormat month_date = new SimpleDateFormat("MMMM", Locale.getDefault()); String curMonth = month_date.format(cal.getTime()); setBudget.setOnClickListener(v -> { SetBudgetSheet setBudgetSheet = new SetBudgetSheet(); setBudgetSheet.show(requireActivity().getSupportFragmentManager(), "setBudgetSheetLog"); }); loadData(); if (!lastMonth.equals("None")){ if(!curMonth.equals(lastMonth)) { SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, defBudget); editor.putString(MONTH, curMonth); editor.apply(); loadData(); } } double num1 = 0; try { num1 = Objects.requireNonNull(NumberFormat.getInstance(Locale.getDefault()).parse((textBudget.replaceAll("[^\\d.,-]", "")))).doubleValue(); } catch (ParseException e) { e.printStackTrace(); } if(num1<0){ message1.setText(R.string.NegativeBudgetTitle); message2.setText(R.string.NegativeBudgetText); }else { message1.setText(R.string.PositiveBudgetTitle); message2.setText(R.string.PositiveBudgetText); } updateViews(); return root; } public void loadData(){ SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); textBudget = sharedPreferences.getString(TEXT, "0.00"); lastMonth = sharedPreferences.getString(MONTH, "None"); defBudget = sharedPreferences.getString(OGTEXT, "0.00"); } public void updateViews(){ double defB = 0; double txtB = 0; try { defB = Objects.requireNonNull(NumberFormat.getInstance().parse(defBudget.replaceAll("[^\\d.,-]", ""))).doubleValue(); txtB = Objects.requireNonNull(NumberFormat.getInstance().parse(textBudget.replaceAll("[^\\d.,-]", ""))).doubleValue(); amountLeft.setText(NumberFormat.getCurrencyInstance().format(txtB)); } catch (ParseException e) { e.printStackTrace(); } int txtE = (int)Math.round(txtB); int defE = (int)Math.round(defB); progressBar.setMax(defE); progressBar.setProgress(txtE); } }
4,205
Java
.java
GittyMac/WalletCount
31
7
5
2020-05-05T00:58:18Z
2023-01-16T21:21:20Z
DragSortItemViewCheckable.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mobeta/android/dslv/DragSortItemViewCheckable.java
package com.mobeta.android.dslv; import android.content.Context; import android.view.View; import android.widget.Checkable; /** * Lightweight ViewGroup that wraps list items obtained from user's * ListAdapter. ItemView expects a single child that has a definite * height (i.e. the child's layout height is not MATCH_PARENT). * The width of * ItemView will always match the width of its child (that is, * the width MeasureSpec given to ItemView is passed directly * to the child, and the ItemView measured width is set to the * child's measured width). The height of ItemView can be anything; * the * * * The purpose of this class is to optimize slide * shuffle animations. */ public class DragSortItemViewCheckable extends DragSortItemView implements Checkable { public DragSortItemViewCheckable(Context context) { super(context); } @Override public boolean isChecked() { View child = getChildAt(0); if (child instanceof Checkable) return ((Checkable) child).isChecked(); else return false; } @Override public void setChecked(boolean checked) { View child = getChildAt(0); if (child instanceof Checkable) ((Checkable) child).setChecked(checked); } @Override public void toggle() { View child = getChildAt(0); if (child instanceof Checkable) ((Checkable) child).toggle(); } }
1,467
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
SimpleFloatViewManager.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mobeta/android/dslv/SimpleFloatViewManager.java
package com.mobeta.android.dslv; import android.graphics.Bitmap; import android.graphics.Point; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; /** * Simple implementation of the FloatViewManager class. Uses list * items as they appear in the ListView to create the floating View. */ public class SimpleFloatViewManager implements DragSortListView.FloatViewManager { private Bitmap mFloatBitmap; private ImageView mImageView; private int mFloatBGResource = 0; private final ListView mListView; SimpleFloatViewManager(ListView lv) { mListView = lv; } void setBackgroundResource(int res) { mFloatBGResource = res; } /** * This simple implementation creates a Bitmap copy of the * list item currently shown at ListView <code>position</code>. */ @Override public View onCreateFloatView(int position) { // Guaranteed that this will not be null? I think so. Nope, got // a NullPointerException once... View v = mListView.getChildAt(position + mListView.getHeaderViewsCount() - mListView.getFirstVisiblePosition()); if (v == null) { return null; } v.setPressed(false); // 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 //v.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); v.setDrawingCacheEnabled(true); mFloatBitmap = Bitmap.createBitmap(v.getDrawingCache()); v.setDrawingCacheEnabled(false); if (mImageView == null) { mImageView = new ImageView(mListView.getContext()); } if (mFloatBGResource > 0) { mImageView.setBackgroundResource(mFloatBGResource); } mImageView.setPadding(0, 0, 0, 0); mImageView.setImageBitmap(mFloatBitmap); mImageView.setLayoutParams(new ViewGroup.LayoutParams(v.getWidth(), v.getHeight())); return mImageView; } /** * This does nothing */ @Override public void onDragFloatView(View floatView, Point position, Point touch) { // do nothing } /** * Removes the Bitmap from the ImageView created in * onCreateFloatView() and tells the system to recycle it. */ @Override public void onDestroyFloatView(View floatView) { ((ImageView) floatView).setImageDrawable(null); mFloatBitmap.recycle(); mFloatBitmap = null; } @Override public void setSecondaryOnTouchListener(View.OnTouchListener l) { // do nothing } }
2,739
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DragSortController.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mobeta/android/dslv/DragSortController.java
package com.mobeta.android.dslv; import android.graphics.Point; import android.view.GestureDetector; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.widget.AdapterView; /** * Class that starts and stops item drags on a {@link DragSortListView} * based on touch gestures. This class also inherits from * {@link SimpleFloatViewManager}, which provides basic float View * creation. */ public class DragSortController extends SimpleFloatViewManager implements View.OnTouchListener, GestureDetector.OnGestureListener { /** * Drag init mode enum. */ static final int ON_DOWN = 0; private static final int ON_DRAG = 1; private static final int ON_LONG_PRESS = 2; private int mDragInitMode = ON_DOWN; private boolean mSortEnabled = true; /** * Remove mode enum. */ private static final int CLICK_REMOVE = 0; static final int FLING_REMOVE = 1; /** * The current remove mode. */ private int mRemoveMode; private boolean mRemoveEnabled = false; private boolean mIsRemoving = false; private final GestureDetector mDetector; private final GestureDetector mFlingRemoveDetector; private final int mTouchSlop; private static final int MISS = -1; private int mHitPos = MISS; private int mFlingHitPos = MISS; private int mClickRemoveHitPos = MISS; private final int[] mTempLoc = new int[2]; private int mItemX; private int mItemY; private int mCurrX; private int mCurrY; private boolean mDragging = false; private final float mFlingSpeed = 500f; private final int mDragHandleId; private final int mClickRemoveId; private final int mFlingHandleId; private boolean mCanDrag; private final DragSortListView mDslv; private int mPositionX; /** * Class which will receive onTouch events */ private View.OnTouchListener mSecondaryOnTouchListener; /** * By default, sorting is enabled, and removal is disabled. * * @param dslv The DSLV instance * @param dragHandleId The resource id of the View that represents * the drag handle in a list item. */ DragSortController(DragSortListView dslv, int dragHandleId, int dragInitMode, int removeMode, int clickRemoveId, int flingHandleId) { super(dslv); mDslv = dslv; mDetector = new GestureDetector(dslv.getContext(), this); mFlingRemoveDetector = new GestureDetector(dslv.getContext(), mFlingRemoveListener); mFlingRemoveDetector.setIsLongpressEnabled(false); mTouchSlop = ViewConfiguration.get(dslv.getContext()).getScaledTouchSlop(); mDragHandleId = dragHandleId; mClickRemoveId = clickRemoveId; mFlingHandleId = flingHandleId; setRemoveMode(removeMode); setDragInitMode(dragInitMode); } private void setDragInitMode(int mode) { mDragInitMode = mode; } void setSortEnabled(boolean enabled) { mSortEnabled = enabled; } private void setRemoveMode(int mode) { mRemoveMode = mode; } /** * Enable/Disable item removal without affecting remove mode. */ void setRemoveEnabled(boolean enabled) { mRemoveEnabled = enabled; } /** * Sets flags to restrict certain motions of the floating View * based on DragSortController settings (such as remove mode). * Starts the drag on the DragSortListView. * * @param position The list item position (includes headers). * @param deltaX Touch x-coord minus left edge of floating View. * @param deltaY Touch y-coord minus top edge of floating View. */ private void startDrag(int position, int deltaX, int deltaY) { int dragFlags = 0; if (mSortEnabled && !mIsRemoving) { dragFlags |= DragSortListView.DRAG_POS_Y | DragSortListView.DRAG_NEG_Y; } if (mRemoveEnabled && mIsRemoving) { dragFlags |= DragSortListView.DRAG_POS_X; dragFlags |= DragSortListView.DRAG_NEG_X; } mDragging = mDslv.startDrag(position - mDslv.getHeaderViewsCount(), dragFlags, deltaX, deltaY); } @Override public boolean onTouch(View v, MotionEvent ev) { if (mSecondaryOnTouchListener != null) { mSecondaryOnTouchListener.onTouch(v, ev); } if (!mDslv.isDragEnabled() || mDslv.listViewIntercepted()) { return false; } mDetector.onTouchEvent(ev); if (mRemoveEnabled && mDragging && mRemoveMode == FLING_REMOVE) { mFlingRemoveDetector.onTouchEvent(ev); } int action = ev.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: mCurrX = (int) ev.getX(); mCurrY = (int) ev.getY(); break; case MotionEvent.ACTION_UP: if (mRemoveEnabled && mIsRemoving) { int x = mPositionX >= 0 ? mPositionX : -mPositionX; int removePoint = mDslv.getWidth() / 2; if (x > removePoint) { mDslv.stopDragWithVelocity(true, 0); } } case MotionEvent.ACTION_CANCEL: mIsRemoving = false; mDragging = false; break; } return false; } /** * Overrides to provide fading when slide removal is enabled. */ @Override public void onDragFloatView(View floatView, Point position, Point touch) { if (mRemoveEnabled && mIsRemoving) { mPositionX = position.x; } } /** * We consume onTouch events: ALSO dispatch them to the listener * if requested. */ @Override public void setSecondaryOnTouchListener(View.OnTouchListener l) { mSecondaryOnTouchListener = l; } /** * Get the position to start dragging based on the ACTION_DOWN * MotionEvent. This function simply calls * {@link #dragHandleHitPosition(MotionEvent)}. Override * to change drag handle behavior; * this function is called internally when an ACTION_DOWN * event is detected. * * @param ev The ACTION_DOWN MotionEvent. * @return The list position to drag if a drag-init gesture is * detected; MISS if unsuccessful. */ private int startDragPosition(MotionEvent ev) { return dragHandleHitPosition(ev); } private int startFlingPosition(MotionEvent ev) { return mRemoveMode == FLING_REMOVE ? flingHandleHitPosition(ev) : MISS; } private int dragHandleHitPosition(MotionEvent ev) { return viewIdHitPosition(ev, mDragHandleId); } private int flingHandleHitPosition(MotionEvent ev) { return viewIdHitPosition(ev, mFlingHandleId); } private int viewIdHitPosition(MotionEvent ev, int id) { final int x = (int) ev.getX(); final int y = (int) ev.getY(); int touchPos = mDslv.pointToPosition(x, y); // includes headers/footers final int numHeaders = mDslv.getHeaderViewsCount(); final int numFooters = mDslv.getFooterViewsCount(); final int count = mDslv.getCount(); // Log.d("mobeta", "touch down on position " + itemnum); // We're only interested if the touch was on an // item that's not a header or footer. if (touchPos != AdapterView.INVALID_POSITION && touchPos >= numHeaders && touchPos < (count - numFooters)) { final View item = mDslv.getChildAt(touchPos - mDslv.getFirstVisiblePosition()); final int rawX = (int) ev.getRawX(); final int rawY = (int) ev.getRawY(); View dragBox = id == 0 ? item : item.findViewById(id); if (dragBox != null) { dragBox.getLocationOnScreen(mTempLoc); if (rawX > mTempLoc[0] && rawY > mTempLoc[1] && rawX < mTempLoc[0] + dragBox.getWidth() && rawY < mTempLoc[1] + dragBox.getHeight()) { mItemX = item.getLeft(); mItemY = item.getTop(); return touchPos; } } } return MISS; } @Override public boolean onDown(MotionEvent ev) { if (mRemoveEnabled && mRemoveMode == CLICK_REMOVE) { mClickRemoveHitPos = viewIdHitPosition(ev, mClickRemoveId); } mHitPos = startDragPosition(ev); if (mHitPos != MISS && mDragInitMode == ON_DOWN) { startDrag(mHitPos, (int) ev.getX() - mItemX, (int) ev.getY() - mItemY); } mIsRemoving = false; mCanDrag = true; mPositionX = 0; mFlingHitPos = startFlingPosition(ev); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // Guard against rare case of null MotionEvents on some devices if (e1 == null || e2 == null) { return false; } final int x1 = (int) e1.getX(); final int y1 = (int) e1.getY(); final int x2 = (int) e2.getX(); final int y2 = (int) e2.getY(); final int deltaX = x2 - mItemX; final int deltaY = y2 - mItemY; if (mCanDrag && !mDragging && (mHitPos != MISS || mFlingHitPos != MISS)) { if (mHitPos != MISS) { if (mDragInitMode == ON_DRAG && Math.abs(y2 - y1) > mTouchSlop && mSortEnabled) { startDrag(mHitPos, deltaX, deltaY); } else if (mDragInitMode != ON_DOWN && Math.abs(x2 - x1) > mTouchSlop && mRemoveEnabled) { mIsRemoving = true; startDrag(mFlingHitPos, deltaX, deltaY); } } else if (mFlingHitPos != MISS) { if (Math.abs(x2 - x1) > mTouchSlop && mRemoveEnabled) { mIsRemoving = true; startDrag(mFlingHitPos, deltaX, deltaY); } else if (Math.abs(y2 - y1) > mTouchSlop) { mCanDrag = false; // if started to scroll the list then // don't allow sorting nor fling-removing } } } // return whatever return false; } @Override public void onLongPress(MotionEvent e) { // Log.d("mobeta", "lift listener long pressed"); if (mHitPos != MISS && mDragInitMode == ON_LONG_PRESS) { mDslv.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); startDrag(mHitPos, mCurrX - mItemX, mCurrY - mItemY); } } // complete the OnGestureListener interface @Override public final boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } // complete the OnGestureListener interface @Override public boolean onSingleTapUp(MotionEvent ev) { if (mRemoveEnabled && mRemoveMode == CLICK_REMOVE) { if (mClickRemoveHitPos != MISS) { mDslv.removeItem(mClickRemoveHitPos - mDslv.getHeaderViewsCount()); } } return true; } // complete the OnGestureListener interface @Override public void onShowPress(MotionEvent ev) { // do nothing } private final GestureDetector.OnGestureListener mFlingRemoveListener = new GestureDetector.SimpleOnGestureListener() { @Override public final boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Log.d("mobeta", "on fling remove called"); if (mRemoveEnabled && mIsRemoving) { int w = mDslv.getWidth(); int minPos = w / 5; if (velocityX > mFlingSpeed) { if (mPositionX > -minPos) { mDslv.stopDragWithVelocity(true, velocityX); } } else if (velocityX < -mFlingSpeed) { if (mPositionX < minPos) { mDslv.stopDragWithVelocity(true, velocityX); } } mIsRemoving = false; } return false; } }; }
13,236
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DragSortListView.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mobeta/android/dslv/DragSortListView.java
/* * DragSortListView. * * A subclass of the Android ListView component that enables drag * and drop re-ordering of list items. * * Copyright 2012 Carl Bauer * * 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.mobeta.android.dslv; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.SparseIntArray; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.Checkable; import android.widget.ListAdapter; import android.widget.ListView; import com.mkulesh.onpc.R; import java.util.ArrayList; /** * ListView subclass that mediates drag and drop resorting of items. * * @author heycosmo */ public class DragSortListView extends ListView { /** * The View that floats above the ListView and represents * the dragged item. */ private View mFloatView; /** * The float View location. First based on touch location * and given deltaX and deltaY. Then restricted by callback * to FloatViewManager.onDragFloatView(). Finally restricted * by bounds of DSLV. */ private final Point mFloatLoc = new Point(); private final Point mTouchLoc = new Point(); /** * The middle (in the y-direction) of the floating View. */ private int mFloatViewMid; /** * Flag to make sure float View isn't measured twice */ private boolean mFloatViewOnMeasured = false; /** * Watch the Adapter for data changes. Cancel a drag if * coincident with a change. */ private final DataSetObserver mObserver; /** * Transparency for the floating View (XML attribute). */ private float mFloatAlpha = 1.0f; private float mCurrFloatAlpha = 1.0f; /** * While drag-sorting, the current position of the floating * View. If dropped, the dragged item will land in this position. */ private int mFloatPos; /** * The first expanded ListView position that helps represent * the drop slot tracking the floating View. */ private int mFirstExpPos; /** * The second expanded ListView position that helps represent * the drop slot tracking the floating View. This can equal * mFirstExpPos if there is no slide shuffle occurring; otherwise * it is equal to mFirstExpPos + 1. */ private int mSecondExpPos; /** * Flag set if slide shuffling is enabled. */ private boolean mAnimate = false; /** * The user dragged from this position. */ private int mSrcPos; /** * Offset (in x) within the dragged item at which the user * picked it up (or first touched down with the digitalis). */ private int mDragDeltaX; /** * Offset (in y) within the dragged item at which the user * picked it up (or first touched down with the digitalis). */ private int mDragDeltaY; /** * A listener that receives callbacks whenever the floating View * hovers over a new position. */ private DragListener mDragListener; /** * A listener that receives a callback when the floating View * is dropped. */ private DropListener mDropListener; /** * A listener that receives a callback when the floating View * (or more precisely the originally dragged item) is removed * by one of the provided gestures. */ private RemoveListener mRemoveListener; /** * Enable/Disable item dragging */ private boolean mDragEnabled = true; /** * Drag state enum. */ private final static int IDLE = 0; private final static int REMOVING = 1; private final static int DROPPING = 2; private final static int STOPPED = 3; private final static int DRAGGING = 4; private int mDragState = IDLE; /** * Height in pixels to which the originally dragged item * is collapsed during a drag-sort. Currently, this value * must be greater than zero. */ private int mItemHeightCollapsed = 1; /** * Height of the floating View. Stored for the purpose of * providing the tracking drop slot. */ private int mFloatViewHeight; /** * Convenience member. See above. */ private int mFloatViewHeightHalf; /** * Save the given width spec for use in measuring children */ private int mWidthMeasureSpec = 0; /** * Sample Views ultimately used for calculating the height * of ListView items that are off-screen. */ private View[] mSampleViewTypes = new View[1]; /** * Drag-scroll encapsulator! */ private final DragScroller mDragScroller; /** * Determines the start of the upward drag-scroll region * at the top of the ListView. Specified by a fraction * of the ListView height, thus screen resolution agnostic. */ private float mDragUpScrollStartFrac = 1.0f / 3.0f; /** * Determines the start of the downward drag-scroll region * at the bottom of the ListView. Specified by a fraction * of the ListView height, thus screen resolution agnostic. */ private float mDragDownScrollStartFrac = 1.0f / 3.0f; /** * The following are calculated from the above fracs. */ private int mUpScrollStartY; private int mDownScrollStartY; private float mDownScrollStartYF; private float mUpScrollStartYF; /** * Calculated from above above and current ListView height. */ private float mDragUpScrollHeight; /** * Calculated from above above and current ListView height. */ private float mDragDownScrollHeight; /** * Maximum drag-scroll speed in pixels per ms. Only used with * default linear drag-scroll profile. */ private float mMaxScrollSpeed = 0.5f; /** * Defines the scroll speed during a drag-scroll. User can * provide their own; this default is a simple linear profile * where scroll speed increases linearly as the floating View * nears the top/bottom of the ListView. */ private final DragScrollProfile mScrollProfile = new DragScrollProfile() { @Override public float getSpeed(float w, long t) { return mMaxScrollSpeed * w; } }; /** * Current touch x. */ private int mX; /** * Current touch y. */ private int mY; /** * Last touch y. */ private int mLastY; /** * Drag flag bit. Floating View can move in the positive * x direction. */ final static int DRAG_POS_X = 0x1; /** * Drag flag bit. Floating View can move in the negative * x direction. */ final static int DRAG_NEG_X = 0x2; /** * Drag flag bit. Floating View can move in the positive * y direction. This is subtle. What this actually means is * that, if enabled, the floating View can be dragged below its starting * position. Remove in favor of upper-bounding item position? */ final static int DRAG_POS_Y = 0x4; /** * Drag flag bit. Floating View can move in the negative * y direction. This is subtle. What this actually means is * that the floating View can be dragged above its starting * position. Remove in favor of lower-bounding item position? */ final static int DRAG_NEG_Y = 0x8; /** * Flags that determine limits on the motion of the * floating View. See flags above. */ private int mDragFlags = 0; /** * Last call to an on*TouchEvent was a call to * onInterceptTouchEvent. */ private boolean mLastCallWasIntercept = false; /** * A touch event is in progress. */ private boolean mInTouchEvent = false; /** * Let the user customize the floating View. */ private FloatViewManager mFloatViewManager = null; /** * Given to ListView to cancel its action when a drag-sort * begins. */ private final MotionEvent mCancelEvent; /** * Enum telling where to cancel the ListView action when a * drag-sort begins */ private static final int NO_CANCEL = 0; private static final int ON_TOUCH_EVENT = 1; private static final int ON_INTERCEPT_TOUCH_EVENT = 2; /** * Where to cancel the ListView action when a * drag-sort begins */ private int mCancelMethod = NO_CANCEL; /** * Determines when a slide shuffle animation starts. That is, * defines how close to the edge of the drop slot the floating * View must be to initiate the slide. */ private float mSlideRegionFrac = 0.25f; /** * Number between 0 and 1 indicating the relative location of * a sliding item (only used if drag-sort animations * are turned on). Nearly 1 means the item is * at the top of the slide region (nearly full blank item * is directly below). */ private float mSlideFrac = 0.0f; /** * Wraps the user-provided ListAdapter. This is used to wrap each * item View given by the user inside another View (currenly * a RelativeLayout) which * expands and collapses to simulate the item shuffling. */ private AdapterWrapper mAdapterWrapper; /** * Needed for adjusting item heights from within layoutChildren */ private boolean mBlockLayoutRequests = false; /** * Set to true when a down event happens during drag sort; * for example, when drag finish animations are * playing. */ private boolean mIgnoreTouchEvent = false; /** * Caches DragSortItemView child heights. Sometimes DSLV has to * know the height of an offscreen item. Since ListView virtualizes * these, DSLV must get the item from the ListAdapter to obtain * its height. That process can be expensive, but often the same * offscreen item will be requested many times in a row. Once an * offscreen item height is calculated, we cache it in this guy. * Actually, we cache the height of the child of the * DragSortItemView since the item height changes often during a * drag-sort. */ private static final int sCacheSize = 3; private final HeightCache mChildHeightCache = new HeightCache(sCacheSize); private RemoveAnimator mRemoveAnimator; private DropAnimator mDropAnimator; private boolean mUseRemoveVelocity; private float mRemoveVelocityX = 0; public DragSortListView(Context context, AttributeSet attrs) { super(context, attrs); int defaultDuration = 150; int removeAnimDuration = defaultDuration; // ms int dropAnimDuration = defaultDuration; // ms if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DragSortListView, 0, 0); mItemHeightCollapsed = Math.max(1, a.getDimensionPixelSize( R.styleable.DragSortListView_collapsed_height, 1)); // alpha between 0 and 255, 0=transparent, 255=opaque mFloatAlpha = a.getFloat(R.styleable.DragSortListView_float_alpha, mFloatAlpha); mCurrFloatAlpha = mFloatAlpha; mDragEnabled = a.getBoolean(R.styleable.DragSortListView_drag_enabled, mDragEnabled); mSlideRegionFrac = Math.max(0.0f, Math.min(1.0f, 1.0f - a.getFloat( R.styleable.DragSortListView_slide_shuffle_speed, 0.75f))); mAnimate = mSlideRegionFrac > 0.0f; float frac = a.getFloat( R.styleable.DragSortListView_drag_scroll_start, mDragUpScrollStartFrac); setDragScrollStart(frac); mMaxScrollSpeed = a.getFloat( R.styleable.DragSortListView_max_drag_scroll_speed, mMaxScrollSpeed); removeAnimDuration = a.getInt( R.styleable.DragSortListView_remove_animation_duration, removeAnimDuration); dropAnimDuration = a.getInt( R.styleable.DragSortListView_drop_animation_duration, dropAnimDuration); boolean useDefault = a.getBoolean( R.styleable.DragSortListView_use_default_controller, true); if (useDefault) { boolean removeEnabled = a.getBoolean( R.styleable.DragSortListView_remove_enabled, false); int removeMode = a.getInt( R.styleable.DragSortListView_remove_mode, DragSortController.FLING_REMOVE); boolean sortEnabled = a.getBoolean( R.styleable.DragSortListView_sort_enabled, true); int dragInitMode = a.getInt( R.styleable.DragSortListView_drag_start_mode, DragSortController.ON_DOWN); int dragHandleId = a.getResourceId( R.styleable.DragSortListView_drag_handle_id, 0); int flingHandleId = a.getResourceId( R.styleable.DragSortListView_fling_handle_id, 0); int clickRemoveId = a.getResourceId( R.styleable.DragSortListView_click_remove_id, 0); int bgResource = a.getResourceId( R.styleable.DragSortListView_float_background_id, 0); DragSortController controller = new DragSortController( this, dragHandleId, dragInitMode, removeMode, clickRemoveId, flingHandleId); controller.setRemoveEnabled(removeEnabled); controller.setSortEnabled(sortEnabled); controller.setBackgroundResource(bgResource); mFloatViewManager = controller; // must register this on ListView (super), not 'this'. super.setOnTouchListener(controller); } a.recycle(); } mDragScroller = new DragScroller(); float smoothness = 0.5f; if (removeAnimDuration > 0) { mRemoveAnimator = new RemoveAnimator(smoothness, removeAnimDuration); } if (dropAnimDuration > 0) { mDropAnimator = new DropAnimator(smoothness, dropAnimDuration); } mCancelEvent = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0f, 0f, 0f, 0f, 0, 0f, 0f, 0, 0); // construct the dataset observer mObserver = new DataSetObserver() { private void cancel() { if (mDragState == DRAGGING) { cancelDrag(); } } @Override public void onChanged() { cancel(); } @Override public void onInvalidated() { cancel(); } }; } /** * DragSortListView registers the the controler as an onTouch listener. * We implement this method to ensure that users of this listview can also * register their own onTouch listener without disabling our own registration. */ @Override public void setOnTouchListener(View.OnTouchListener l) { if (mFloatViewManager != null) { mFloatViewManager.setSecondaryOnTouchListener(l); } } /** * For each DragSortListView Listener interface implemented by * <code>adapter</code>, this method calls the appropriate * set*Listener method with <code>adapter</code> as the argument. * * @param adapter The ListAdapter providing data to back * DragSortListView. * @see android.widget.ListView#setAdapter(android.widget.ListAdapter) */ @Override public void setAdapter(ListAdapter adapter) { if (adapter != null) { mAdapterWrapper = new AdapterWrapper(adapter); adapter.registerDataSetObserver(mObserver); if (adapter instanceof DropListener) { setDropListener((DropListener) adapter); } if (adapter instanceof DragListener) { setDragListener((DragListener) adapter); } if (adapter instanceof RemoveListener) { setRemoveListener((RemoveListener) adapter); } } else { mAdapterWrapper = null; } super.setAdapter(mAdapterWrapper); } private class AdapterWrapper extends BaseAdapter { private final ListAdapter mAdapter; AdapterWrapper(ListAdapter adapter) { super(); mAdapter = adapter; mAdapter.registerDataSetObserver(new DataSetObserver() { public void onChanged() { notifyDataSetChanged(); } public void onInvalidated() { notifyDataSetInvalidated(); } }); } @Override public long getItemId(int position) { return mAdapter.getItemId(position); } @Override public Object getItem(int position) { return mAdapter.getItem(position); } @Override public int getCount() { return mAdapter.getCount(); } @Override public boolean areAllItemsEnabled() { return mAdapter.areAllItemsEnabled(); } @Override public boolean isEnabled(int position) { return mAdapter.isEnabled(position); } @Override public int getItemViewType(int position) { return mAdapter.getItemViewType(position); } @Override public int getViewTypeCount() { return mAdapter.getViewTypeCount(); } @Override public boolean hasStableIds() { return mAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { DragSortItemView v; View child; // Log.d("mobeta", // "getView: position="+position+" convertView="+convertView); if (convertView != null) { v = (DragSortItemView) convertView; View oldChild = v.getChildAt(0); child = mAdapter.getView(position, oldChild, DragSortListView.this); if (child != oldChild) { // shouldn't get here if user is reusing convertViews // properly if (oldChild != null) { v.removeViewAt(0); } v.addView(child); } } else { child = mAdapter.getView(position, null, DragSortListView.this); if (child instanceof Checkable) { v = new DragSortItemViewCheckable(getContext()); } else { v = new DragSortItemView(getContext()); } v.setLayoutParams(new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); v.addView(child); } // Set the correct item height given drag state; passed // View needs to be measured if measurement is required. adjustItem(position + getHeaderViewsCount(), v, true); return v; } } private void drawDivider(int expPosition, Canvas canvas) { final Drawable divider = getDivider(); final int dividerHeight = getDividerHeight(); // Log.d("mobeta", "div="+divider+" divH="+dividerHeight); if (divider != null && dividerHeight != 0) { final ViewGroup expItem = (ViewGroup) getChildAt(expPosition - getFirstVisiblePosition()); if (expItem != null) { final int l = getPaddingLeft(); final int r = getWidth() - getPaddingRight(); final int t; final int b; final int childHeight = expItem.getChildAt(0).getHeight(); if (expPosition > mSrcPos) { t = expItem.getTop() + childHeight; b = t + dividerHeight; } else { b = expItem.getBottom() - childHeight; t = b - dividerHeight; } // Log.d("mobeta", "l="+l+" t="+t+" r="+r+" b="+b); // Have to clip to support ColorDrawable on <= Gingerbread canvas.save(); canvas.clipRect(l, t, r, b); divider.setBounds(l, t, r, b); divider.draw(canvas); canvas.restore(); } } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mDragState != IDLE) { // draw the divider over the expanded item if (mFirstExpPos != mSrcPos) { drawDivider(mFirstExpPos, canvas); } if (mSecondExpPos != mFirstExpPos && mSecondExpPos != mSrcPos) { drawDivider(mSecondExpPos, canvas); } } if (mFloatView != null) { // draw the float view over everything final int w = mFloatView.getWidth(); final int h = mFloatView.getHeight(); int x = mFloatLoc.x; int width = getWidth(); if (x < 0) x = -x; float alphaMod; if (x < width) { alphaMod = ((float) (width - x)) / ((float) width); alphaMod *= alphaMod; } else { alphaMod = 0; } final int alpha = (int) (255f * mCurrFloatAlpha * alphaMod); canvas.save(); // Log.d("mobeta", "clip rect bounds: " + canvas.getClipBounds()); canvas.translate(mFloatLoc.x, mFloatLoc.y); canvas.clipRect(0, 0, w, h); // Log.d("mobeta", "clip rect bounds: " + canvas.getClipBounds()); canvas.saveLayerAlpha(0, 0, w, h, alpha, Canvas.ALL_SAVE_FLAG); mFloatView.draw(canvas); canvas.restore(); canvas.restore(); } } private int getItemHeight(int position) { View v = getChildAt(position - getFirstVisiblePosition()); if (v != null) { // item is onscreen, just get the height of the View return v.getHeight(); } else { // item is offscreen. get child height and calculate // item height based on current shuffle state return calcItemHeight(position, getChildHeight(position)); } } private class HeightCache { private final SparseIntArray mMap; private final ArrayList<Integer> mOrder; private final int mMaxSize; HeightCache(int size) { mMap = new SparseIntArray(size); mOrder = new ArrayList<>(size); mMaxSize = size; } /** * Add item height at position if doesn't already exist. */ void add(int position, int height) { int currHeight = mMap.get(position, -1); if (currHeight != height) { if (currHeight == -1) { if (mMap.size() == mMaxSize) { // remove oldest entry mMap.delete(mOrder.remove(0)); } } else { // move position to newest slot mOrder.remove((Integer) position); } mMap.put(position, height); mOrder.add(position); } } int get(int position) { return mMap.get(position, -1); } void clear() { mMap.clear(); mOrder.clear(); } } /** * Get the shuffle edge for item at position when top of * item is at y-coord top. Assumes that current item heights * are consistent with current float view location and * thus expanded positions and slide fraction. i.e. Should not be * called between update of expanded positions/slide fraction * and layoutChildren. */ private int getShuffleEdge(int position, int top) { final int numHeaders = getHeaderViewsCount(); final int numFooters = getFooterViewsCount(); // shuffle edges are defined between items that can be // dragged; there are N-1 of them if there are N draggable // items. if (position <= numHeaders || (position >= getCount() - numFooters)) { return top; } int divHeight = getDividerHeight(); int edge; int maxBlankHeight = mFloatViewHeight - mItemHeightCollapsed; int childHeight = getChildHeight(position); int itemHeight = getItemHeight(position); // first calculate top of item given that floating View is // centered over src position int otop = top; if (mSecondExpPos <= mSrcPos) { // items are expanded on and/or above the source position if (position == mSecondExpPos && mFirstExpPos != mSecondExpPos) { if (position == mSrcPos) { otop = top + itemHeight - mFloatViewHeight; } else { int blankHeight = itemHeight - childHeight; otop = top + blankHeight - maxBlankHeight; } } else if (position > mSecondExpPos && position <= mSrcPos) { otop = top - maxBlankHeight; } } else { // items are expanded on and/or below the source position if (position > mSrcPos && position <= mFirstExpPos) { otop = top + maxBlankHeight; } else if (position == mSecondExpPos && mFirstExpPos != mSecondExpPos) { int blankHeight = itemHeight - childHeight; otop = top + blankHeight; } } // otop is set if (position <= mSrcPos) { edge = otop + (mFloatViewHeight - divHeight - getChildHeight(position - 1)) / 2; } else { edge = otop + (childHeight - divHeight - mFloatViewHeight) / 2; } return edge; } private boolean updatePositions() { final int first = getFirstVisiblePosition(); int startPos = mFirstExpPos; View startView = getChildAt(startPos - first); if (startView == null) { startPos = first + getChildCount() / 2; startView = getChildAt(startPos - first); } int startTop = startView.getTop(); int itemHeight = startView.getHeight(); int edge = getShuffleEdge(startPos, startTop); int lastEdge = edge; int divHeight = getDividerHeight(); // Log.d("mobeta", "float mid="+mFloatViewMid); int itemPos = startPos; int itemTop = startTop; if (mFloatViewMid < edge) { // scanning up for float position // Log.d("mobeta", " edge="+edge); while (itemPos >= 0) { itemPos--; itemHeight = getItemHeight(itemPos); if (itemPos == 0) { edge = itemTop - divHeight - itemHeight; break; } itemTop -= itemHeight + divHeight; edge = getShuffleEdge(itemPos, itemTop); // Log.d("mobeta", " edge="+edge); if (mFloatViewMid >= edge) { break; } lastEdge = edge; } } else { // scanning down for float position // Log.d("mobeta", " edge="+edge); final int count = getCount(); while (itemPos < count) { if (itemPos == count - 1) { edge = itemTop + divHeight + itemHeight; break; } itemTop += divHeight + itemHeight; itemHeight = getItemHeight(itemPos + 1); edge = getShuffleEdge(itemPos + 1, itemTop); // Log.d("mobeta", " edge="+edge); // test for hit if (mFloatViewMid < edge) { break; } lastEdge = edge; itemPos++; } } final int numHeaders = getHeaderViewsCount(); final int numFooters = getFooterViewsCount(); boolean updated = false; int oldFirstExpPos = mFirstExpPos; int oldSecondExpPos = mSecondExpPos; float oldSlideFrac = mSlideFrac; if (mAnimate) { int edgeToEdge = Math.abs(edge - lastEdge); int edgeTop, edgeBottom; if (mFloatViewMid < edge) { edgeBottom = edge; edgeTop = lastEdge; } else { edgeTop = edge; edgeBottom = lastEdge; } // Log.d("mobeta", "edgeTop="+edgeTop+" edgeBot="+edgeBottom); int slideRgnHeight = (int) (0.5f * mSlideRegionFrac * edgeToEdge); float slideRgnHeightF = (float) slideRgnHeight; int slideEdgeTop = edgeTop + slideRgnHeight; int slideEdgeBottom = edgeBottom - slideRgnHeight; // Three regions if (mFloatViewMid < slideEdgeTop) { mFirstExpPos = itemPos - 1; mSecondExpPos = itemPos; mSlideFrac = 0.5f * ((float) (slideEdgeTop - mFloatViewMid)) / slideRgnHeightF; // Log.d("mobeta", // "firstExp="+mFirstExpPos+" secExp="+mSecondExpPos+" slideFrac="+mSlideFrac); } else if (mFloatViewMid < slideEdgeBottom) { mFirstExpPos = itemPos; mSecondExpPos = itemPos; } else { mFirstExpPos = itemPos; mSecondExpPos = itemPos + 1; mSlideFrac = 0.5f * (1.0f + ((float) (edgeBottom - mFloatViewMid)) / slideRgnHeightF); // Log.d("mobeta", // "firstExp="+mFirstExpPos+" secExp="+mSecondExpPos+" slideFrac="+mSlideFrac); } } else { mFirstExpPos = itemPos; mSecondExpPos = itemPos; } // correct for headers and footers if (mFirstExpPos < numHeaders) { itemPos = numHeaders; mFirstExpPos = itemPos; mSecondExpPos = itemPos; } else if (mSecondExpPos >= getCount() - numFooters) { itemPos = getCount() - numFooters - 1; mFirstExpPos = itemPos; mSecondExpPos = itemPos; } if (mFirstExpPos != oldFirstExpPos || mSecondExpPos != oldSecondExpPos || mSlideFrac != oldSlideFrac) { updated = true; } if (itemPos != mFloatPos) { if (mDragListener != null) { mDragListener.drag(mFloatPos - numHeaders, itemPos - numHeaders); } mFloatPos = itemPos; updated = true; } return updated; } private class SmoothAnimator implements Runnable { long mStartTime; private final float mDurationF; private final float mAlpha; private final float mA, mB, mC, mD; private boolean mCanceled; SmoothAnimator(float smoothness, int duration) { mAlpha = smoothness; mDurationF = (float) duration; mA = mD = 1f / (2f * mAlpha * (1f - mAlpha)); mB = mAlpha / (2f * (mAlpha - 1f)); mC = 1f / (1f - mAlpha); } float transform(float frac) { if (frac < mAlpha) { return mA * frac * frac; } else if (frac < 1f - mAlpha) { return mB + mC * frac; } else { return 1f - mD * (frac - 1f) * (frac - 1f); } } void start() { mStartTime = SystemClock.uptimeMillis(); mCanceled = false; onStart(); post(this); } void cancel() { mCanceled = true; } void onStart() { // stub } void onUpdate(float frac, float smoothFrac) { // stub } void onStop() { // stub } @Override public void run() { if (mCanceled) { return; } float fraction = ((float) (SystemClock.uptimeMillis() - mStartTime)) / mDurationF; if (fraction >= 1f) { onUpdate(1f, 1f); onStop(); } else { onUpdate(fraction, transform(fraction)); post(this); } } } /** * Centers floating View over drop slot before destroying. */ private class DropAnimator extends SmoothAnimator { private int mDropPos; private int srcPos; private float mInitDeltaY; private float mInitDeltaX; DropAnimator(float smoothness, int duration) { super(smoothness, duration); } @Override void onStart() { mDropPos = mFloatPos; srcPos = mSrcPos; mDragState = DROPPING; mInitDeltaY = mFloatLoc.y - getTargetY(); mInitDeltaX = mFloatLoc.x - getPaddingLeft(); } private int getTargetY() { final int first = getFirstVisiblePosition(); final int otherAdjust = (mItemHeightCollapsed + getDividerHeight()) / 2; View v = getChildAt(mDropPos - first); int targetY = -1; if (v != null) { if (mDropPos == srcPos) { targetY = v.getTop(); } else if (mDropPos < srcPos) { // expanded down targetY = v.getTop() - otherAdjust; } else { // expanded up targetY = v.getBottom() + otherAdjust - mFloatViewHeight; } } else { // drop position is not on screen?? no animation cancel(); } return targetY; } @Override void onUpdate(float frac, float smoothFrac) { final int targetY = getTargetY(); final int targetX = getPaddingLeft(); final float deltaY = mFloatLoc.y - targetY; final float deltaX = mFloatLoc.x - targetX; final float f = 1f - smoothFrac; if (f < Math.abs(deltaY / mInitDeltaY) || f < Math.abs(deltaX / mInitDeltaX)) { mFloatLoc.y = targetY + (int) (mInitDeltaY * f); mFloatLoc.x = getPaddingLeft() + (int) (mInitDeltaX * f); doDragFloatView(true); } } @Override void onStop() { dropFloatView(); } } /** * Collapses expanded items. */ private class RemoveAnimator extends SmoothAnimator { private float mFloatLocX; private float mFirstStartBlank; private float mSecondStartBlank; private int mFirstChildHeight = -1; private int mSecondChildHeight = -1; private int mFirstPos; private int mSecondPos; RemoveAnimator(float smoothness, int duration) { super(smoothness, duration); } @Override void onStart() { mFirstChildHeight = -1; mSecondChildHeight = -1; mFirstPos = mFirstExpPos; mSecondPos = mSecondExpPos; mDragState = REMOVING; mFloatLocX = mFloatLoc.x; if (mUseRemoveVelocity) { float minVelocity = 2f * getWidth(); if (mRemoveVelocityX == 0) { mRemoveVelocityX = (mFloatLocX < 0 ? -1 : 1) * minVelocity; } else { minVelocity *= 2; if (mRemoveVelocityX < 0 && mRemoveVelocityX > -minVelocity) mRemoveVelocityX = -minVelocity; else if (mRemoveVelocityX > 0 && mRemoveVelocityX < minVelocity) mRemoveVelocityX = minVelocity; } } else { destroyFloatView(); } } @Override void onUpdate(float frac, float smoothFrac) { float f = 1f - smoothFrac; final int firstVis = getFirstVisiblePosition(); View item = getChildAt(mFirstPos - firstVis); ViewGroup.LayoutParams lp; int blank; if (mUseRemoveVelocity) { float dt = (float) (SystemClock.uptimeMillis() - mStartTime) / 1000; if (dt == 0) return; float dx = mRemoveVelocityX * dt; int w = getWidth(); mRemoveVelocityX += (mRemoveVelocityX > 0 ? 1 : -1) * dt * w; mFloatLocX += dx; mFloatLoc.x = (int) mFloatLocX; if (mFloatLocX < w && mFloatLocX > -w) { mStartTime = SystemClock.uptimeMillis(); doDragFloatView(true); return; } } if (item != null) { if (mFirstChildHeight == -1) { mFirstChildHeight = getChildHeight(mFirstPos, item, false); mFirstStartBlank = (float) (item.getHeight() - mFirstChildHeight); } blank = Math.max((int) (f * mFirstStartBlank), 1); lp = item.getLayoutParams(); lp.height = mFirstChildHeight + blank; item.setLayoutParams(lp); } if (mSecondPos != mFirstPos) { item = getChildAt(mSecondPos - firstVis); if (item != null) { if (mSecondChildHeight == -1) { mSecondChildHeight = getChildHeight(mSecondPos, item, false); mSecondStartBlank = (float) (item.getHeight() - mSecondChildHeight); } blank = Math.max((int) (f * mSecondStartBlank), 1); lp = item.getLayoutParams(); lp.height = mSecondChildHeight + blank; item.setLayoutParams(lp); } } } @Override void onStop() { doRemoveItem(); } } void removeItem(int which) { mUseRemoveVelocity = false; removeItem(which, 0); } /** * Removes an item from the list and animates the removal. */ private void removeItem(int which, float velocityX) { if (mDragState == IDLE || mDragState == DRAGGING) { if (mDragState == IDLE) { // called from outside drag-sort mSrcPos = getHeaderViewsCount() + which; mFirstExpPos = mSrcPos; mSecondExpPos = mSrcPos; mFloatPos = mSrcPos; View v = getChildAt(mSrcPos - getFirstVisiblePosition()); if (v != null) { v.setVisibility(View.INVISIBLE); } } mDragState = REMOVING; mRemoveVelocityX = velocityX; if (mInTouchEvent) { switch (mCancelMethod) { case ON_TOUCH_EVENT: super.onTouchEvent(mCancelEvent); break; case ON_INTERCEPT_TOUCH_EVENT: super.onInterceptTouchEvent(mCancelEvent); break; } } if (mRemoveAnimator != null) { mRemoveAnimator.start(); } else { doRemoveItem(which); } } } private void cancelDrag() { if (mDragState == DRAGGING) { mDragScroller.stopScrolling(true); destroyFloatView(); clearPositions(); adjustAllItems(); if (mInTouchEvent) { mDragState = STOPPED; } else { mDragState = IDLE; } } } private void clearPositions() { mSrcPos = -1; mFirstExpPos = -1; mSecondExpPos = -1; mFloatPos = -1; } private void dropFloatView() { // must set to avoid cancelDrag being called from the // DataSetObserver mDragState = DROPPING; if (mDropListener != null && mFloatPos >= 0 && mFloatPos < getCount()) { final int numHeaders = getHeaderViewsCount(); mDropListener.drop(mSrcPos - numHeaders, mFloatPos - numHeaders); } destroyFloatView(); adjustOnReorder(); clearPositions(); adjustAllItems(); // now the drag is done if (mInTouchEvent) { mDragState = STOPPED; } else { mDragState = IDLE; } } private void doRemoveItem() { doRemoveItem(mSrcPos - getHeaderViewsCount()); } /** * Removes dragged item from the list. Calls RemoveListener. */ private void doRemoveItem(int which) { // must set to avoid cancelDrag being called from the // DataSetObserver mDragState = REMOVING; // end it if (mRemoveListener != null) { mRemoveListener.remove(which); } destroyFloatView(); adjustOnReorder(); clearPositions(); // now the drag is done if (mInTouchEvent) { mDragState = STOPPED; } else { mDragState = IDLE; } } private void adjustOnReorder() { final int firstPos = getFirstVisiblePosition(); // Log.d("mobeta", "first="+firstPos+" src="+mSrcPos); if (mSrcPos < firstPos) { // collapsed src item is off screen; // adjust the scroll after item heights have been fixed View v = getChildAt(0); int top = 0; if (v != null) { top = v.getTop(); } // Log.d("mobeta", "top="+top+" fvh="+mFloatViewHeight); setSelectionFromTop(firstPos - 1, top - getPaddingTop()); } } /** * Stop a drag in progress. Pass <code>true</code> if you would * like to remove the dragged item from the list. * * @param remove Remove the dragged item from the list. Calls * a registered RemoveListener, if one exists. Otherwise, calls * the DropListener, if one exists. * @return True if the stop was successful. False if there is * no floating View. */ private boolean stopDrag(boolean remove) { mUseRemoveVelocity = false; return stopDrag(remove, 0); } boolean stopDragWithVelocity(boolean remove, float velocityX) { mUseRemoveVelocity = true; return stopDrag(remove, velocityX); } private boolean stopDrag(boolean remove, float velocityX) { if (mFloatView != null) { mDragScroller.stopScrolling(true); if (remove) { removeItem(mSrcPos - getHeaderViewsCount(), velocityX); } else { if (mDropAnimator != null) { mDropAnimator.start(); } else { dropFloatView(); } } return true; } else { // stop failed return false; } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mIgnoreTouchEvent) { mIgnoreTouchEvent = false; return false; } if (!mDragEnabled) { return super.onTouchEvent(ev); } boolean more = false; boolean lastCallWasIntercept = mLastCallWasIntercept; mLastCallWasIntercept = false; if (!lastCallWasIntercept) { saveTouchCoords(ev); } // if (mFloatView != null) { if (mDragState == DRAGGING) { onDragTouchEvent(ev); more = true; // give us more! } else { // what if float view is null b/c we dropped in middle // of drag touch event? // if (mDragState != STOPPED) { if (mDragState == IDLE) { if (super.onTouchEvent(ev)) { more = true; } } int action = ev.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: doActionUpOrCancel(); break; default: if (more) { mCancelMethod = ON_TOUCH_EVENT; } } } return more; } private void doActionUpOrCancel() { mCancelMethod = NO_CANCEL; mInTouchEvent = false; if (mDragState == STOPPED) { mDragState = IDLE; } mCurrFloatAlpha = mFloatAlpha; mListViewIntercepted = false; mChildHeightCache.clear(); } private void saveTouchCoords(MotionEvent ev) { int action = ev.getAction() & MotionEvent.ACTION_MASK; if (action != MotionEvent.ACTION_DOWN) { mLastY = mY; } mX = (int) ev.getX(); mY = (int) ev.getY(); if (action == MotionEvent.ACTION_DOWN) { mLastY = mY; } } boolean listViewIntercepted() { return mListViewIntercepted; } private boolean mListViewIntercepted = false; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mDragEnabled) { return super.onInterceptTouchEvent(ev); } saveTouchCoords(ev); mLastCallWasIntercept = true; int action = ev.getAction() & MotionEvent.ACTION_MASK; if (action == MotionEvent.ACTION_DOWN) { if (mDragState != IDLE) { // intercept and ignore mIgnoreTouchEvent = true; return true; } mInTouchEvent = true; } boolean intercept = false; // the following deals with calls to super.onInterceptTouchEvent if (mFloatView != null) { // super's touch event canceled in startDrag intercept = true; } else { if (super.onInterceptTouchEvent(ev)) { mListViewIntercepted = true; intercept = true; } switch (action) { case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: doActionUpOrCancel(); break; default: if (intercept) { mCancelMethod = ON_TOUCH_EVENT; } else { mCancelMethod = ON_INTERCEPT_TOUCH_EVENT; } } } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { mInTouchEvent = false; } return intercept; } /** * Set the width of each drag scroll region by specifying * a fraction of the ListView height. * * @param heightFraction Fraction of ListView height. Capped at * 0.5f. */ private void setDragScrollStart(float heightFraction) { setDragScrollStarts(heightFraction, heightFraction); } /** * Set the width of each drag scroll region by specifying * a fraction of the ListView height. * * @param upperFrac Fraction of ListView height for up-scroll bound. * Capped at 0.5f. * @param lowerFrac Fraction of ListView height for down-scroll bound. * Capped at 0.5f. */ private void setDragScrollStarts(float upperFrac, float lowerFrac) { if (lowerFrac > 0.5f) { mDragDownScrollStartFrac = 0.5f; } else { mDragDownScrollStartFrac = lowerFrac; } if (upperFrac > 0.5f) { mDragUpScrollStartFrac = 0.5f; } else { mDragUpScrollStartFrac = upperFrac; } if (getHeight() != 0) { updateScrollStarts(); } } private void continueDrag(int x, int y) { // proposed position mFloatLoc.x = x - mDragDeltaX; mFloatLoc.y = y - mDragDeltaY; doDragFloatView(true); int minY = Math.min(y, mFloatViewMid + mFloatViewHeightHalf); int maxY = Math.max(y, mFloatViewMid - mFloatViewHeightHalf); // get the current scroll direction int currentScrollDir = mDragScroller.getScrollDir(); if (minY > mLastY && minY > mDownScrollStartY && currentScrollDir != DragScroller.DOWN) { // dragged down, it is below the down scroll start and it is not // scrolling up if (currentScrollDir != DragScroller.STOP) { // moved directly from up scroll to down scroll mDragScroller.stopScrolling(true); } // start scrolling down mDragScroller.startScrolling(DragScroller.DOWN); } else if (maxY < mLastY && maxY < mUpScrollStartY && currentScrollDir != DragScroller.UP) { // dragged up, it is above the up scroll start and it is not // scrolling up if (currentScrollDir != DragScroller.STOP) { // moved directly from down scroll to up scroll mDragScroller.stopScrolling(true); } // start scrolling up mDragScroller.startScrolling(DragScroller.UP); } else if (maxY >= mUpScrollStartY && minY <= mDownScrollStartY && mDragScroller.isScrolling()) { // not in the upper nor in the lower drag-scroll regions but it is // still scrolling mDragScroller.stopScrolling(true); } } private void updateScrollStarts() { final int padTop = getPaddingTop(); final int listHeight = getHeight() - padTop - getPaddingBottom(); float heightF = (float) listHeight; mUpScrollStartYF = padTop + mDragUpScrollStartFrac * heightF; mDownScrollStartYF = padTop + (1.0f - mDragDownScrollStartFrac) * heightF; mUpScrollStartY = (int) mUpScrollStartYF; mDownScrollStartY = (int) mDownScrollStartYF; mDragUpScrollHeight = mUpScrollStartYF - padTop; mDragDownScrollHeight = padTop + listHeight - mDownScrollStartYF; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); updateScrollStarts(); } private void adjustAllItems() { final int first = getFirstVisiblePosition(); final int last = getLastVisiblePosition(); int begin = Math.max(0, getHeaderViewsCount() - first); int end = Math.min(last - first, getCount() - 1 - getFooterViewsCount() - first); for (int i = begin; i <= end; ++i) { View v = getChildAt(i); if (v != null) { adjustItem(first + i, v, false); } } } /** * Sets layout param height, gravity, and visibility on * wrapped item. */ private void adjustItem(int position, View v, boolean invalidChildHeight) { // Adjust item height ViewGroup.LayoutParams lp = v.getLayoutParams(); int height; if (position != mSrcPos && position != mFirstExpPos && position != mSecondExpPos) { height = ViewGroup.LayoutParams.WRAP_CONTENT; } else { height = calcItemHeight(position, v, invalidChildHeight); } if (height != lp.height) { lp.height = height; v.setLayoutParams(lp); } // Adjust item gravity if (position == mFirstExpPos || position == mSecondExpPos) { if (position < mSrcPos) { ((DragSortItemView) v).setGravity(Gravity.BOTTOM); } else if (position > mSrcPos) { ((DragSortItemView) v).setGravity(Gravity.TOP); } } // Finally adjust item visibility int oldVis = v.getVisibility(); int vis = View.VISIBLE; if (position == mSrcPos && mFloatView != null) { vis = View.INVISIBLE; } if (vis != oldVis) { v.setVisibility(vis); } } private int getChildHeight(int position) { if (position == mSrcPos) { return 0; } View v = getChildAt(position - getFirstVisiblePosition()); if (v != null) { // item is onscreen, therefore child height is valid, // hence the "true" return getChildHeight(position, v, false); } else { // item is offscreen // first check cache for child height at this position int childHeight = mChildHeightCache.get(position); if (childHeight != -1) { // Log.d("mobeta", "found child height in cache!"); return childHeight; } final ListAdapter adapter = getAdapter(); int type = adapter.getItemViewType(position); // There might be a better place for checking for the following final int typeCount = adapter.getViewTypeCount(); if (typeCount != mSampleViewTypes.length) { mSampleViewTypes = new View[typeCount]; } if (type >= 0) { if (mSampleViewTypes[type] == null) { v = adapter.getView(position, null, this); mSampleViewTypes[type] = v; } else { v = adapter.getView(position, mSampleViewTypes[type], this); } } else { // type is HEADER_OR_FOOTER or IGNORE v = adapter.getView(position, null, this); } // current child height is invalid, hence "true" below childHeight = getChildHeight(position, v, true); // cache it because this could have been expensive mChildHeightCache.add(position, childHeight); return childHeight; } } private int getChildHeight(int position, View item, boolean invalidChildHeight) { if (position == mSrcPos) { return 0; } View child; if (position < getHeaderViewsCount() || position >= getCount() - getFooterViewsCount()) { child = item; } else { child = ((ViewGroup) item).getChildAt(0); } ViewGroup.LayoutParams lp = child.getLayoutParams(); if (lp != null) { if (lp.height > 0) { return lp.height; } } int childHeight = child.getHeight(); if (childHeight == 0 || invalidChildHeight) { measureItem(child); childHeight = child.getMeasuredHeight(); } return childHeight; } private int calcItemHeight(int position, View item, boolean invalidChildHeight) { return calcItemHeight(position, getChildHeight(position, item, invalidChildHeight)); } private int calcItemHeight(int position, int childHeight) { boolean isSliding = mAnimate && mFirstExpPos != mSecondExpPos; int maxNonSrcBlankHeight = mFloatViewHeight - mItemHeightCollapsed; int slideHeight = (int) (mSlideFrac * maxNonSrcBlankHeight); int height; if (position == mSrcPos) { if (mSrcPos == mFirstExpPos) { if (isSliding) { height = slideHeight + mItemHeightCollapsed; } else { height = mFloatViewHeight; } } else if (mSrcPos == mSecondExpPos) { // if gets here, we know an item is sliding height = mFloatViewHeight - slideHeight; } else { height = mItemHeightCollapsed; } } else if (position == mFirstExpPos) { if (isSliding) { height = childHeight + slideHeight; } else { height = childHeight + maxNonSrcBlankHeight; } } else if (position == mSecondExpPos) { // we know an item is sliding (b/c 2ndPos != 1stPos) height = childHeight + maxNonSrcBlankHeight - slideHeight; } else { height = childHeight; } return height; } @Override public void requestLayout() { if (!mBlockLayoutRequests) { super.requestLayout(); } } private int adjustScroll(int movePos, View moveItem, int oldFirstExpPos, int oldSecondExpPos) { int adjust = 0; final int childHeight = getChildHeight(movePos); int moveHeightBefore = moveItem.getHeight(); int moveHeightAfter = calcItemHeight(movePos, childHeight); int moveBlankBefore = moveHeightBefore; int moveBlankAfter = moveHeightAfter; if (movePos != mSrcPos) { moveBlankBefore -= childHeight; moveBlankAfter -= childHeight; } int maxBlank = mFloatViewHeight; if (mSrcPos != mFirstExpPos && mSrcPos != mSecondExpPos) { maxBlank -= mItemHeightCollapsed; } if (movePos <= oldFirstExpPos) { if (movePos > mFirstExpPos) { adjust += maxBlank - moveBlankAfter; } } else if (movePos == oldSecondExpPos) { if (movePos <= mFirstExpPos) { adjust += moveBlankBefore - maxBlank; } else if (movePos == mSecondExpPos) { adjust += moveHeightBefore - moveHeightAfter; } else { adjust += moveBlankBefore; } } else { if (movePos <= mFirstExpPos) { adjust -= maxBlank; } else if (movePos == mSecondExpPos) { adjust -= moveBlankAfter; } } return adjust; } private void measureItem(View item) { ViewGroup.LayoutParams lp = item.getLayoutParams(); if (lp == null) { lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); item.setLayoutParams(lp); } int wspec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, getListPaddingLeft() + getListPaddingRight(), lp.width); int hspec; if (lp.height > 0) { hspec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY); } else { hspec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } item.measure(wspec, hspec); } private void measureFloatView() { if (mFloatView != null) { measureItem(mFloatView); mFloatViewHeight = mFloatView.getMeasuredHeight(); mFloatViewHeightHalf = mFloatViewHeight / 2; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Log.d("mobeta", "onMeasure called"); if (mFloatView != null) { if (mFloatView.isLayoutRequested()) { measureFloatView(); } mFloatViewOnMeasured = true; // set to false after layout } mWidthMeasureSpec = widthMeasureSpec; } @Override protected void layoutChildren() { super.layoutChildren(); if (mFloatView != null) { if (mFloatView.isLayoutRequested() && !mFloatViewOnMeasured) { // Have to measure here when usual android measure // pass is skipped. This happens during a drag-sort // when layoutChildren is called directly. measureFloatView(); } mFloatView.layout(0, 0, mFloatView.getMeasuredWidth(), mFloatView.getMeasuredHeight()); mFloatViewOnMeasured = false; } } private void onDragTouchEvent(MotionEvent ev) { switch (ev.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_CANCEL: if (mDragState == DRAGGING) { cancelDrag(); } doActionUpOrCancel(); break; case MotionEvent.ACTION_UP: // Log.d("mobeta", "calling stopDrag from onDragTouchEvent"); if (mDragState == DRAGGING) { stopDrag(false); } doActionUpOrCancel(); break; case MotionEvent.ACTION_MOVE: continueDrag((int) ev.getX(), (int) ev.getY()); break; } } /** * Start a drag of item at <code>position</code> using the * registered FloatViewManager. Calls through * to {@link #startDrag(int, View, int, int, int)} after obtaining * the floating View from the FloatViewManager. * * @param position Item to drag. * @param dragFlags Flags that restrict some movements of the * floating View. For example, set <code>dragFlags |= * ~{@link #DRAG_NEG_X}</code> to allow dragging the floating * View in all directions except off the screen to the left. * @param deltaX Offset in x of the touch coordinate from the * left edge of the floating View (i.e. touch-x minus float View * left). * @param deltaY Offset in y of the touch coordinate from the * top edge of the floating View (i.e. touch-y minus float View * top). * @return True if the drag was started, false otherwise. This * <code>startDrag</code> will fail if we are not currently in * a touch event, there is no registered FloatViewManager, * or the FloatViewManager returns a null View. */ boolean startDrag(int position, int dragFlags, int deltaX, int deltaY) { if (!mInTouchEvent || mFloatViewManager == null) { return false; } View v = mFloatViewManager.onCreateFloatView(position); if (v == null) { return false; } else { return startDrag(position, v, dragFlags, deltaX, deltaY); } } /** * Start a drag of item at <code>position</code> without using * a FloatViewManager. * * @param position Item to drag. * @param floatView Floating View. * @param dragFlags Flags that restrict some movements of the * floating View. For example, set <code>dragFlags |= * ~{@link #DRAG_NEG_X}</code> to allow dragging the floating * View in all directions except off the screen to the left. * @param deltaX Offset in x of the touch coordinate from the * left edge of the floating View (i.e. touch-x minus float View * left). * @param deltaY Offset in y of the touch coordinate from the * top edge of the floating View (i.e. touch-y minus float View * top). * @return True if the drag was started, false otherwise. This * <code>startDrag</code> will fail if we are not currently in * a touch event, <code>floatView</code> is null, or there is * a drag in progress. */ private boolean startDrag(int position, View floatView, int dragFlags, int deltaX, int deltaY) { if (mDragState != IDLE || !mInTouchEvent || mFloatView != null || floatView == null || !mDragEnabled) { return false; } if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } int pos = position + getHeaderViewsCount(); mFirstExpPos = pos; mSecondExpPos = pos; mSrcPos = pos; mFloatPos = pos; // mDragState = dragType; mDragState = DRAGGING; mDragFlags = 0; mDragFlags |= dragFlags; mFloatView = floatView; measureFloatView(); // sets mFloatViewHeight mDragDeltaX = deltaX; mDragDeltaY = deltaY; // updateFloatView(mX - mDragDeltaX, mY - mDragDeltaY); mFloatLoc.x = mX - mDragDeltaX; mFloatLoc.y = mY - mDragDeltaY; // set src item invisible final View srcItem = getChildAt(mSrcPos - getFirstVisiblePosition()); if (srcItem != null) { srcItem.setVisibility(View.INVISIBLE); } // once float view is created, events are no longer passed // to ListView switch (mCancelMethod) { case ON_TOUCH_EVENT: super.onTouchEvent(mCancelEvent); break; case ON_INTERCEPT_TOUCH_EVENT: super.onInterceptTouchEvent(mCancelEvent); break; } requestLayout(); return true; } private void doDragFloatView(boolean forceInvalidate) { int movePos = getFirstVisiblePosition() + getChildCount() / 2; View moveItem = getChildAt(getChildCount() / 2); if (moveItem == null) { return; } doDragFloatView(movePos, moveItem, forceInvalidate); } private void doDragFloatView(int movePos, View moveItem, boolean forceInvalidate) { mBlockLayoutRequests = true; updateFloatView(); int oldFirstExpPos = mFirstExpPos; int oldSecondExpPos = mSecondExpPos; boolean updated = updatePositions(); if (updated) { adjustAllItems(); int scroll = adjustScroll(movePos, moveItem, oldFirstExpPos, oldSecondExpPos); // Log.d("mobeta", " adjust scroll="+scroll); setSelectionFromTop(movePos, moveItem.getTop() + scroll - getPaddingTop()); layoutChildren(); } if (updated || forceInvalidate) { invalidate(); } mBlockLayoutRequests = false; } /** * Sets float View location based on suggested values and * constraints set in mDragFlags. */ private void updateFloatView() { if (mFloatViewManager != null) { mTouchLoc.set(mX, mY); mFloatViewManager.onDragFloatView(mFloatView, mFloatLoc, mTouchLoc); } final int floatX = mFloatLoc.x; final int floatY = mFloatLoc.y; // restrict x motion int padLeft = getPaddingLeft(); if ((mDragFlags & DRAG_POS_X) == 0 && floatX > padLeft) { mFloatLoc.x = padLeft; } else if ((mDragFlags & DRAG_NEG_X) == 0 && floatX < padLeft) { mFloatLoc.x = padLeft; } // keep floating view from going past bottom of last header view final int numHeaders = getHeaderViewsCount(); final int numFooters = getFooterViewsCount(); final int firstPos = getFirstVisiblePosition(); final int lastPos = getLastVisiblePosition(); // Log.d("mobeta", // "nHead="+numHeaders+" nFoot="+numFooters+" first="+firstPos+" last="+lastPos); int topLimit = getPaddingTop(); if (firstPos < numHeaders) { topLimit = getChildAt(numHeaders - firstPos - 1).getBottom(); } if ((mDragFlags & DRAG_NEG_Y) == 0) { if (firstPos <= mSrcPos) { topLimit = Math.max(getChildAt(mSrcPos - firstPos).getTop(), topLimit); } } // bottom limit is top of first footer View or // bottom of last item in list int bottomLimit = getHeight() - getPaddingBottom(); if (lastPos >= getCount() - numFooters - 1) { bottomLimit = getChildAt(getCount() - numFooters - 1 - firstPos).getBottom(); } if ((mDragFlags & DRAG_POS_Y) == 0) { if (lastPos >= mSrcPos) { bottomLimit = Math.min(getChildAt(mSrcPos - firstPos).getBottom(), bottomLimit); } } // Log.d("mobeta", "dragView top=" + (y - mDragDeltaY)); // Log.d("mobeta", "limit=" + limit); // Log.d("mobeta", "mDragDeltaY=" + mDragDeltaY); if (floatY < topLimit) { mFloatLoc.y = topLimit; } else if (floatY + mFloatViewHeight > bottomLimit) { mFloatLoc.y = bottomLimit - mFloatViewHeight; } // get y-midpoint of floating view (constrained to ListView bounds) mFloatViewMid = mFloatLoc.y + mFloatViewHeightHalf; } private void destroyFloatView() { if (mFloatView != null) { mFloatView.setVisibility(GONE); if (mFloatViewManager != null) { mFloatViewManager.onDestroyFloatView(mFloatView); } mFloatView = null; invalidate(); } } /** * Interface for customization of the floating View appearance * and dragging behavior. */ interface FloatViewManager { /** * Return the floating View for item at <code>position</code>. * DragSortListView will measure and layout this View for you, * so feel free to just inflate it. You can help DSLV by * setting some {@link ViewGroup.LayoutParams} on this View; * otherwise it will set some for you (with a width of FILL_PARENT * and a height of WRAP_CONTENT). * * @param position Position of item to drag (NOTE: * <code>position</code> excludes header Views; thus, if you * want to call {@link ListView#getChildAt(int)}, you will need * to add {@link ListView#getHeaderViewsCount()} to the index). * @return The View you wish to display as the floating View. */ View onCreateFloatView(int position); /** * Called whenever the floating View is dragged. Float View * properties can be changed here. Also, the upcoming location * of the float View can be altered by setting * <code>location.x</code> and <code>location.y</code>. * * @param floatView The floating View. * @param location The location (top-left; relative to DSLV * top-left) at which the float * View would like to appear, given the current touch location * and the offset provided in {@link DragSortListView#startDrag}. * @param touch The current touch location (relative to DSLV * top-left). */ void onDragFloatView(View floatView, Point location, Point touch); /** * Called when the float View is dropped; lets you perform * any necessary cleanup. The internal DSLV floating View * reference is set to null immediately after this is called. * * @param floatView The floating View passed to * {@link #onCreateFloatView(int)}. */ void onDestroyFloatView(View floatView); /** * Register a class which will get onTouch events. */ void setSecondaryOnTouchListener(View.OnTouchListener l); } private void setDragListener(DragListener l) { mDragListener = l; } boolean isDragEnabled() { return mDragEnabled; } public void setDropListener(DropListener l) { mDropListener = l; } /** * Probably a no-brainer, but make sure that your remove listener * calls {@link BaseAdapter#notifyDataSetChanged()} or something like it. * When an item removal occurs, DragSortListView * relies on a redraw of all the items to recover invisible views * and such. Strictly speaking, if you remove something, your dataset * has changed... */ private void setRemoveListener(RemoveListener l) { mRemoveListener = l; } interface DragListener { void drag(int from, int to); } /** * Your implementation of this has to reorder your ListAdapter! * Make sure to call * {@link BaseAdapter#notifyDataSetChanged()} or something like it * in your implementation. * * @author heycosmo */ public interface DropListener { void drop(int from, int to); } /** * Make sure to call * {@link BaseAdapter#notifyDataSetChanged()} or something like it * in your implementation. * * @author heycosmo */ interface RemoveListener { void remove(int which); } /** * Interface for controlling * scroll speed as a function of touch position and time. */ interface DragScrollProfile { /** * Return a scroll speed in pixels/millisecond. Always return a * positive number. * * @param w Normalized position in scroll region (i.e. w \in [0,1]). * Small w typically means slow scrolling. * @param t Time (in milliseconds) since start of scroll (handy if you * want scroll acceleration). * @return Scroll speed at position w and time t in pixels/ms. */ float getSpeed(float w, long t); } private class DragScroller implements Runnable { private boolean mAbort; private long mPrevTime; private long mCurrTime; private int dy; private float dt; private long tStart; private int scrollDir; final static int STOP = -1; final static int UP = 0; final static int DOWN = 1; private float mScrollSpeed; // pixels per ms private boolean mScrolling = false; boolean isScrolling() { return mScrolling; } int getScrollDir() { return mScrolling ? scrollDir : STOP; } DragScroller() { } void startScrolling(int dir) { if (!mScrolling) { // Debug.startMethodTracing("dslv-scroll"); mAbort = false; mScrolling = true; tStart = SystemClock.uptimeMillis(); mPrevTime = tStart; scrollDir = dir; post(this); } } void stopScrolling(boolean now) { if (now) { DragSortListView.this.removeCallbacks(this); mScrolling = false; } else { mAbort = true; } // Debug.stopMethodTracing(); } @Override public void run() { if (mAbort) { mScrolling = false; return; } // Log.d("mobeta", "scroll"); final int first = getFirstVisiblePosition(); final int last = getLastVisiblePosition(); final int count = getCount(); final int padTop = getPaddingTop(); final int listHeight = getHeight() - padTop - getPaddingBottom(); int minY = Math.min(mY, mFloatViewMid + mFloatViewHeightHalf); int maxY = Math.max(mY, mFloatViewMid - mFloatViewHeightHalf); if (scrollDir == UP) { View v = getChildAt(0); // Log.d("mobeta", "vtop="+v.getTop()+" padtop="+padTop); if (v == null) { mScrolling = false; return; } else { if (first == 0 && v.getTop() == padTop) { mScrolling = false; return; } } mScrollSpeed = mScrollProfile.getSpeed((mUpScrollStartYF - maxY) / mDragUpScrollHeight, mPrevTime); } else { View v = getChildAt(last - first); if (v == null) { mScrolling = false; return; } else { if (last == count - 1 && v.getBottom() <= listHeight + padTop) { mScrolling = false; return; } } mScrollSpeed = -mScrollProfile.getSpeed((minY - mDownScrollStartYF) / mDragDownScrollHeight, mPrevTime); } mCurrTime = SystemClock.uptimeMillis(); dt = (float) (mCurrTime - mPrevTime); // dy is change in View position of a list item; i.e. positive dy // means user is scrolling up (list item moves down the screen, // remember // y=0 is at top of View). dy = Math.round(mScrollSpeed * dt); int movePos; if (dy >= 0) { dy = Math.min(listHeight, dy); movePos = first; } else { dy = Math.max(-listHeight, dy); movePos = last; } final View moveItem = getChildAt(movePos - first); int top = moveItem.getTop() + dy; if (movePos == 0 && top > padTop) { top = padTop; } // always do scroll mBlockLayoutRequests = true; setSelectionFromTop(movePos, top - padTop); DragSortListView.this.layoutChildren(); invalidate(); mBlockLayoutRequests = false; // scroll means relative float View movement doDragFloatView(movePos, moveItem, false); mPrevTime = mCurrTime; // Log.d("mobeta", " updated prevTime="+mPrevTime); post(this); } } }
83,769
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DragSortItemView.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mobeta/android/dslv/DragSortItemView.java
package com.mobeta.android.dslv; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; /** * Lightweight ViewGroup that wraps list items obtained from user's * ListAdapter. ItemView expects a single child that has a definite * height (i.e. the child's layout height is not MATCH_PARENT). * The width of * ItemView will always match the width of its child (that is, * the width MeasureSpec given to ItemView is passed directly * to the child, and the ItemView measured width is set to the * child's measured width). The height of ItemView can be anything; * the * * * The purpose of this class is to optimize slide * shuffle animations. */ public class DragSortItemView extends ViewGroup { private int mGravity = Gravity.TOP; public DragSortItemView(Context context) { super(context); // always init with standard ListView layout params setLayoutParams(new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); //setClipChildren(true); } public void setGravity(int gravity) { mGravity = gravity; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { final View child = getChildAt(0); if (child == null) { return; } if (mGravity == Gravity.TOP) { child.layout(0, 0, getMeasuredWidth(), child.getMeasuredHeight()); } else { child.layout(0, getMeasuredHeight() - child.getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight()); } } /** * */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); final View child = getChildAt(0); if (child == null) { setMeasuredDimension(0, width); return; } if (child.isLayoutRequested()) { // Always let child be as tall as it wants. measureChild(child, widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); } if (heightMode == MeasureSpec.UNSPECIFIED) { ViewGroup.LayoutParams lp = getLayoutParams(); if (lp.height > 0) { height = lp.height; } else { height = child.getMeasuredHeight(); } } setMeasuredDimension(width, height); } }
2,859
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MainNavigationDrawer.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/MainNavigationDrawer.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.navigation.NavigationView; import com.mkulesh.onpc.config.Configuration; import com.mkulesh.onpc.config.PreferencesMain; import com.mkulesh.onpc.fragments.Dialogs; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.ConnectionState; import com.mkulesh.onpc.iscp.DeviceList; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.List; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.AppCompatRadioButton; import androidx.appcompat.widget.AppCompatTextView; import androidx.drawerlayout.widget.DrawerLayout; class MainNavigationDrawer { private final MainActivity activity; private final DrawerLayout drawerLayout; private final NavigationView navigationView; private final Configuration configuration; private final List<BroadcastResponseMsg> devices = new ArrayList<>(); MainNavigationDrawer(MainActivity activity, String versionName) { this.activity = activity; drawerLayout = activity.findViewById(R.id.main_drawer_layout); navigationView = activity.findViewById(R.id.navigation_view); configuration = activity.getConfiguration(); if (navigationView != null) { updateNavigationContent(null); updateNavigationHeader(versionName); } } DrawerLayout getDrawerLayout() { return drawerLayout; } private void selectNavigationItem(MenuItem menuItem) { drawerLayout.closeDrawers(); switch (menuItem.getItemId()) { case R.id.drawer_device_search: navigationSearchDevice(); break; case R.id.drawer_device_connect: navigationConnectDevice(); break; case R.id.drawer_zone_1: case R.id.drawer_zone_2: case R.id.drawer_zone_3: case R.id.drawer_zone_4: navigationChangeZone(menuItem.getOrder()); break; case R.id.drawer_all_standby: navigationAllStandby(menuItem); break; case R.id.drawer_multiroom_1: case R.id.drawer_multiroom_2: case R.id.drawer_multiroom_3: case R.id.drawer_multiroom_4: case R.id.drawer_multiroom_5: case R.id.drawer_multiroom_6: navigationDevice(menuItem.getOrder()); break; case R.id.drawer_app_settings: activity.startActivityForResult(new Intent(activity, PreferencesMain.class), MainActivity.SETTINGS_ACTIVITY_REQID); break; case R.id.drawer_about: final Dialogs dl = new Dialogs(activity); dl.showHtmlDialog(R.mipmap.ic_launcher, R.string.app_name, R.string.about_text); break; case R.id.drawer_premium: case R.id.drawer_desktop: try { final String uri = menuItem.getItemId() == R.id.drawer_premium ? activity.getString(R.string.drawer_premium_link) : activity.getString(R.string.drawer_desktop_link); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(android.net.Uri.parse(uri)); activity.startActivity(intent); } catch (Exception e) { Toast.makeText(activity, e.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } } void navigationSearchDevice() { activity.getDeviceList().startSearchDialog(new DeviceList.DialogEventListener() { // These methods will be called from GUI thread @Override public void onDeviceFound(BroadcastResponseMsg response) { if (response == null || !response.isValidConnection()) { return; } activity.connectToDevice(response); } @Override public void noDevice(ConnectionState.FailureReason reason) { activity.getConnectionState().showFailure(reason); } }); } @SuppressLint("SetTextI18n") private void navigationConnectDevice() { final FrameLayout frameView = new FrameLayout(activity); activity.getLayoutInflater().inflate(R.layout.dialog_connect_layout, frameView); final EditText deviceName = frameView.findViewById(R.id.device_name); deviceName.setText(configuration.getDeviceName()); final EditText devicePort = frameView.findViewById(R.id.device_port); final AppCompatRadioButton integraBtn = frameView.findViewById(R.id.connect_models_integra); final AppCompatRadioButton denonBtn = frameView.findViewById(R.id.connect_models_denon); final AppCompatRadioButton[] radioGroup = { integraBtn, denonBtn }; for (AppCompatRadioButton r : radioGroup) { r.setOnClickListener((View v) -> { final int p = v == integraBtn ? ConnectionIf.ISCP_PORT : ConnectionIf.DCP_PORT; devicePort.setText(Integer.toString(p)); onRadioBtnChange(radioGroup, (AppCompatRadioButton) v); }); } onRadioBtnChange(radioGroup, configuration.getDevicePort() == ConnectionIf.ISCP_PORT ? integraBtn : denonBtn); devicePort.setText(configuration.getDevicePortAsString()); final EditText deviceFriendlyName = frameView.findViewById(R.id.device_friendly_name); final CheckBox checkBox = frameView.findViewById(R.id.checkbox_device_save); checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> deviceFriendlyName.setVisibility(isChecked ? View.VISIBLE : View.GONE)); final Drawable icon = Utils.getDrawable(activity, R.drawable.drawer_connect); Utils.setDrawableColorAttr(activity, icon, android.R.attr.textColorSecondary); final AlertDialog dialog = new AlertDialog.Builder(activity) .setTitle(R.string.drawer_device_connect) .setIcon(icon) .setCancelable(false) .setView(frameView) .setNegativeButton(activity.getResources().getString(R.string.action_cancel), (dialog1, which) -> { Utils.showSoftKeyboard(activity, deviceName, false); dialog1.dismiss(); }) .setPositiveButton(activity.getResources().getString(R.string.action_ok), (dialog12, which) -> { Utils.showSoftKeyboard(activity, deviceName, false); // First, use port from configuration if (devicePort.getText().length() == 0) { devicePort.setText(configuration.getDevicePortAsString()); } // Second, fallback to standard port if (devicePort.getText().length() == 0) { devicePort.setText(Integer.toString(ConnectionIf.ISCP_PORT)); } try { final String device = deviceName.getText().toString(); final int port = Integer.parseInt(devicePort.getText().toString()); if (activity.connectToDevice(device, port, false)) { configuration.saveDevice(device, port); if (checkBox.isChecked()) { final String friendlyName = deviceFriendlyName.getText().length() > 0 ? deviceFriendlyName.getText().toString() : Utils.ipToString(device, devicePort.getText().toString()); configuration.favoriteConnections.updateDevice( activity.getStateManager().getState(), friendlyName, null); activity.getDeviceList().updateFavorites(true); } } } catch (Exception e) { String message = activity.getString(R.string.error_invalid_device_address); Logging.info(activity, message + ": " + e.getLocalizedMessage()); Toast.makeText(activity, message, Toast.LENGTH_LONG).show(); } dialog12.dismiss(); }).create(); dialog.show(); Utils.fixDialogLayout(dialog, android.R.attr.textColorSecondary); } private void navigationChangeZone(final int idx) { Logging.info(this, "changed zone: " + idx); configuration.setActiveZone(idx); activity.restartActivity(); } private void navigationAllStandby(MenuItem menuItem) { menuItem.setChecked(false); if (activity.isConnected()) { activity.getStateManager().sendMessage(new PowerStatusMsg( ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE, PowerStatusMsg.PowerStatus.ALL_STB)); } } private void updateNavigationHeader(final String versionName) { for (int i = 0; i < navigationView.getHeaderCount(); i++) { final TextView versionInfo = navigationView.getHeaderView(i).findViewById(R.id.navigation_view_header_version); if (versionInfo != null) { versionInfo.setText(versionName); } final AppCompatImageView logo = navigationView.getHeaderView(i).findViewById(R.id.drawer_header); if (logo != null) { Utils.setImageViewColorAttr(activity, logo, R.attr.colorAccent); } } } void updateNavigationContent(@Nullable final State state) { final int activeZone = state == null ? ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE : state.getActiveZone(); final List<ReceiverInformationMsg.Zone> zones = state == null ? new ArrayList<>() : state.getZones(); final int[] zoneImages = { R.drawable.drawer_zone_1, R.drawable.drawer_zone_2, R.drawable.drawer_zone_3, R.drawable.drawer_zone_4, }; // store devices devices.clear(); devices.addAll(activity.getDeviceList().getDevices()); int favorites = 0; for (BroadcastResponseMsg msg : devices) { if (msg.getAlias() != null) { favorites++; } } final Menu menu = navigationView.getMenu(); for (int k = 0; k < menu.size(); k++) { final MenuItem g = menu.getItem(k); switch (g.getItemId()) { case R.id.drawer_group_zone_id: for (int i = 0; i < g.getSubMenu().size(); i++) { final MenuItem m = g.getSubMenu().getItem(i); if (m.getItemId() == R.id.drawer_all_standby) { if (activity.isConnected() && zones != null && zones.size() > 1) { updateItem(m, R.drawable.drawer_all_standby, activity.getString(R.string.drawer_all_standby), null); m.setChecked(false); } else { m.setVisible(false); } continue; } else if (zones == null || i >= zones.size()) { m.setVisible(false); continue; } updateItem(m, zoneImages[i], zones.get(i).getName(), null); m.setChecked(i == activeZone); } break; case R.id.drawer_multiroom: g.setVisible(devices.size() > 1 || favorites > 0); for (int i = 0; i < g.getSubMenu().size(); i++) { final MenuItem m = g.getSubMenu().getItem(i); if (g.isVisible() && i < devices.size()) { setDeviceVisible(m, devices.get(i), state); } else { m.setVisible(false); m.setChecked(false); } } break; default: for (int i = 0; i < g.getSubMenu().size(); i++) { final MenuItem m = g.getSubMenu().getItem(i); switch (m.getItemId()) { case R.id.drawer_device_search: updateItem(m, R.drawable.cmd_search, R.string.drawer_device_search); break; case R.id.drawer_device_connect: updateItem(m, R.drawable.drawer_connect, R.string.drawer_device_connect); break; case R.id.drawer_app_settings: updateItem(m, R.drawable.drawer_app_settings, R.string.drawer_app_settings); break; case R.id.drawer_about: updateItem(m, R.drawable.drawer_about, R.string.drawer_about); break; case R.id.drawer_premium: updateItem(m, R.drawable.drawer_premium, R.string.drawer_premium); break; case R.id.drawer_desktop: updateItem(m, R.drawable.drawer_desktop, R.string.drawer_desktop); break; } } } } navigationView.setNavigationItemSelectedListener(menuItem -> { selectNavigationItem(menuItem); return true; }); } interface ButtonListener { void onEditItem(); } private void updateItem(@NonNull final MenuItem m, final @DrawableRes int iconId, @StringRes final int titleId) { updateItem(m, iconId, activity.getString(titleId), null); } private void updateItem(@NonNull final MenuItem m, final @DrawableRes int iconId, final String title, final ButtonListener editListener) { if (m.getActionView() != null && m.getActionView() instanceof LinearLayout) { final LinearLayout l = (LinearLayout) m.getActionView(); ((AppCompatImageView) l.findViewWithTag("ICON")).setImageResource(iconId); ((AppCompatTextView) l.findViewWithTag("TEXT")).setText(title); final AppCompatImageButton editBtn = l.findViewWithTag("EDIT"); if (editListener != null) { editBtn.setVisibility(View.VISIBLE); editBtn.setOnClickListener(v -> editListener.onEditItem()); Utils.setButtonEnabled(activity, editBtn, true); } else { editBtn.setVisibility(View.GONE); } } m.setVisible(true); } /** * Multiroom */ private void navigationDevice(int idx) { Logging.info(this, "selected multiroom device: " + idx); if (idx < devices.size()) { activity.connectToDevice(devices.get(idx)); } } private void setDeviceVisible(@NonNull final MenuItem m, final BroadcastResponseMsg msg, @Nullable final State state) { final String name = activity.getMultiroomDeviceName(msg); if (msg.getAlias() != null) { updateItem(m, R.drawable.drawer_favorite_device, name, () -> editFavoriteConnection(m, msg)); } else { updateItem(m, R.drawable.drawer_found_device, name, null); } m.setChecked(state != null && msg.fromHost(state)); } @SuppressLint("DefaultLocale") private void editFavoriteConnection(@NonNull final MenuItem m, final BroadcastResponseMsg msg) { final FrameLayout frameView = new FrameLayout(activity); activity.getLayoutInflater().inflate(R.layout.dialog_favorite_connect_layout, frameView); final TextView deviceAddress = frameView.findViewById(R.id.favorite_connection_address); deviceAddress.setText(String.format("%s %s", activity.getString(R.string.connect_dialog_address), msg.getHostAndPort())); // Connection alias final EditText deviceAlias = frameView.findViewById(R.id.favorite_connection_alias); deviceAlias.setText(msg.getAlias()); // Optional identifier final EditText deviceIdentifier = frameView.findViewById(R.id.favorite_connection_identifier); deviceIdentifier.setText(msg.getIdentifier()); final AppCompatRadioButton renameBtn = frameView.findViewById(R.id.favorite_connection_update); final AppCompatRadioButton deleteBtn = frameView.findViewById(R.id.favorite_connection_delete); final AppCompatRadioButton[] radioGroup = { renameBtn, deleteBtn }; for (AppCompatRadioButton r : radioGroup) { r.setOnClickListener((View v) -> { if (v != renameBtn) { deviceAlias.clearFocus(); deviceIdentifier.clearFocus(); } onRadioBtnChange(radioGroup, (AppCompatRadioButton) v); }); } deviceAlias.setOnFocusChangeListener((v, hasFocus) -> { if (hasFocus) { onRadioBtnChange(radioGroup, renameBtn); } }); deviceIdentifier.setOnFocusChangeListener((v, hasFocus) -> { if (hasFocus) { onRadioBtnChange(radioGroup, renameBtn); } }); final Drawable icon = Utils.getDrawable(activity, R.drawable.drawer_edit_item); Utils.setDrawableColorAttr(activity, icon, android.R.attr.textColorSecondary); final AlertDialog dialog = new AlertDialog.Builder(activity) .setTitle(R.string.favorite_connection_edit) .setIcon(icon) .setCancelable(false) .setView(frameView) .setNegativeButton(activity.getResources().getString(R.string.action_cancel), (dialog1, which) -> { Utils.showSoftKeyboard(activity, deviceAlias, false); dialog1.dismiss(); }) .setPositiveButton(activity.getResources().getString(R.string.action_ok), (dialog12, which) -> { Utils.showSoftKeyboard(activity, deviceAlias, false); // rename or delete favorite connection if (renameBtn.isChecked() && deviceAlias.getText().length() > 0) { final String alias = deviceAlias.getText().toString(); final String identifier = deviceIdentifier.getText().length() > 0 ? deviceIdentifier.getText().toString() : null; final BroadcastResponseMsg newMsg = configuration.favoriteConnections.updateDevice( msg, alias, identifier); updateItem(m, R.drawable.drawer_favorite_device, newMsg.getAlias(), () -> editFavoriteConnection(m, newMsg)); activity.getDeviceList().updateFavorites(false); } if (deleteBtn.isChecked()) { configuration.favoriteConnections.deleteDevice(msg); activity.getDeviceList().updateFavorites(false); updateNavigationContent(activity.isConnected() ? activity.getStateManager().getState() : null); } dialog12.dismiss(); }).create(); dialog.show(); Utils.fixDialogLayout(dialog, android.R.attr.textColorSecondary); } private void onRadioBtnChange(final AppCompatRadioButton[] radioGroup, AppCompatRadioButton v) { for (AppCompatRadioButton r : radioGroup) { r.setChecked(false); } v.setChecked(true); } }
22,429
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MainPagerAdapter.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/MainPagerAdapter.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc; import android.content.Context; import android.util.SparseArray; import android.view.ViewGroup; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.config.Configuration; import com.mkulesh.onpc.fragments.DeviceFragment; import com.mkulesh.onpc.fragments.ListenFragment; import com.mkulesh.onpc.fragments.MediaFragment; import com.mkulesh.onpc.fragments.RemoteControlFragment; import com.mkulesh.onpc.fragments.RemoteInterfaceFragment; import com.mkulesh.onpc.fragments.ShortcutsFragment; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import static com.mkulesh.onpc.config.CfgAppSettings.Tabs; class MainPagerAdapter extends FragmentStatePagerAdapter { private final Context context; private final ArrayList<Tabs> tabs; private final SparseArray<Fragment> registeredFragments = new SparseArray<>(); MainPagerAdapter(final Context context, final FragmentManager fm, final Configuration configuration) { super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT); this.context = context; this.tabs = configuration.appSettings.getVisibleTabs(); } @Override @NonNull public Fragment getItem(int position) { if (position >= getCount()) { return new ListenFragment(); } final Tabs item = tabs.get(position); switch (item) { case LISTEN: return new ListenFragment(); case MEDIA: return new MediaFragment(); case SHORTCUTS: return new ShortcutsFragment(); case DEVICE: return new DeviceFragment(); case RC: return new RemoteControlFragment(); default: return new RemoteInterfaceFragment(); } } @Override public int getCount() { return tabs.size(); } @Override public CharSequence getPageTitle(int position) { return (position < getCount()) ? CfgAppSettings.getTabName(context, tabs.get(position)) : ""; } // Register the fragment when the item is instantiated @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; } // Unregister when the item is inactive @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } // Returns the fragment for the position (if instantiated) Fragment getRegisteredFragment(int position) { return registeredFragments.get(position); } }
3,661
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MainActivity.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/MainActivity.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import com.google.android.material.tabs.TabLayout; import com.mkulesh.onpc.config.AppLocale; import com.mkulesh.onpc.config.CfgAppSettings; import com.mkulesh.onpc.config.Configuration; import com.mkulesh.onpc.fragments.BaseFragment; import com.mkulesh.onpc.fragments.Dialogs; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.ConnectionState; import com.mkulesh.onpc.iscp.DeviceList; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.StateHolder; import com.mkulesh.onpc.iscp.StateManager; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.scripts.AutoPower; import com.mkulesh.onpc.iscp.scripts.MessageScript; import com.mkulesh.onpc.iscp.scripts.MessageScriptIf; import com.mkulesh.onpc.iscp.scripts.RequestListeningMode; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.HashSet; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.ViewPager; public class MainActivity extends AppCompatActivity implements StateManager.StateListener, DeviceList.BackgroundEventListener { public static final int SETTINGS_ACTIVITY_REQID = 256; private static final String SHORTCUT_AUTO_POWER = "com.mkulesh.onpc.AUTO_POWER"; private static final String SHORTCUT_ALL_STANDBY = "com.mkulesh.onpc.ALL_STANDBY"; private Configuration configuration; private Toolbar toolbar; private MainPagerAdapter pagerAdapter; private ViewPager viewPager; private Menu mainMenu; private ConnectionState connectionState; private final StateHolder stateHolder = new StateHolder(); private DeviceList deviceList; private Toast exitToast = null; private MainNavigationDrawer navigationDrawer; private ActionBarDrawerToggle mDrawerToggle; private String versionName = null; private int startRequestCode; private final AtomicBoolean connectToAnyDevice = new AtomicBoolean(false); public int orientation; private String intentData = null; private MessageScript messageScript = null; // #58: observed missed receiver information message on device rotation. // Solution: save and restore the receiver information in // onSaveInstanceState/onRestoreInstanceState private String savedReceiverInformation = null; @Override protected void onCreate(Bundle savedInstanceState) { configuration = new Configuration(this); setTheme(configuration.appSettings.getTheme(this, CfgAppSettings.ThemeType.MAIN_THEME)); Logging.saveLogging = Logging.isEnabled() && configuration.isDeveloperMode(); // Note that due to onActivityResult, the activity will be started twice // after the Preference activity is closed // We store activity result code in startRequestCode and use it to prevent // network communication after Preference activity is just closed startRequestCode = 0; super.onCreate(savedInstanceState); orientation = getResources().getConfiguration().orientation; try { final PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = "v. " + pi.versionName; Logging.info(this, "Starting application: version " + versionName + ", orientation " + orientation); } catch (PackageManager.NameNotFoundException e) { Logging.info(this, "Starting application"); versionName = null; } Logging.info(this, "App can start on-top of the lock screen: " + configuration.isShowWhenLocked()); if (configuration.isShowWhenLocked()) { allowShowWhenLocked(); } connectionState = new ConnectionState(this); deviceList = new DeviceList(this, connectionState, this, configuration.favoriteConnections.getDevices()); // Initially reset zone state configuration.initActiveZone(ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE); initGUI(); setOpenedTab(configuration.appSettings.getOpenedTab()); updateToolbar(null); } private void allowShowWhenLocked() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { setShowWhenLocked(true); setTurnScreenOn(true); KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (keyguardManager!=null) { keyguardManager.requestDismissKeyguard(this, null); } } else { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); } } @Override public void onConfigurationChanged(android.content.res.Configuration newConfig) { orientation = newConfig.orientation; Logging.info(this, "device orientation change: " + orientation); super.onConfigurationChanged(newConfig); // restore active page int page = viewPager.getCurrentItem(); initGUI(); viewPager.setCurrentItem(page); if (stateHolder.getState() != null) { updateConfiguration(stateHolder.getState()); } // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); mDrawerToggle.syncState(); } private void initGUI() { setContentView(orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT ? R.layout.activity_main_port : R.layout.activity_main_land); if (configuration.isKeepScreenOn()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } toolbar = findViewById(R.id.toolbar); toolbar.setTitle(R.string.app_short_name); setSupportActionBar(toolbar); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(R.string.app_short_name); actionBar.setElevation(5.0f); } // Create the adapter that will return a fragment for each of the three // primary sections of the activity. pagerAdapter = new MainPagerAdapter(this, getSupportFragmentManager(), configuration); // Set up the ViewPager with the sections adapter. viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(pagerAdapter); final TabLayout tabLayout = findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager); // Navigation drawer navigationDrawer = new MainNavigationDrawer(this, versionName); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, navigationDrawer.getDrawerLayout(), toolbar, R.string.drawer_open, R.string.drawer_open) { public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); navigationDrawer.updateNavigationContent(stateHolder.getState()); } }; Utils.setDrawerListener(navigationDrawer.getDrawerLayout(), mDrawerToggle); } @Override protected void attachBaseContext(Context newBase) { final Locale prefLocale = AppLocale.ContextWrapper.getPreferredLocale(newBase); Logging.info(this, "Application locale: " + prefLocale); super.attachBaseContext(AppLocale.ContextWrapper.wrap(newBase, prefLocale)); } @Override public void applyOverrideConfiguration(android.content.res.Configuration overrideConfiguration) { // See https://stackoverflow.com/questions/55265834/change-locale-not-work-after-migrate-to-androidx: // There is an issue in new app compat libraries related to night mode that is causing to // override the configuration on android 21 to 25. This can be fixed as follows if (overrideConfiguration != null) { int uiMode = overrideConfiguration.uiMode; overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration()); overrideConfiguration.uiMode = uiMode; } super.applyOverrideConfiguration(overrideConfiguration); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); try { if (savedReceiverInformation != null) { Logging.info(this, "save receiver information"); outState.putString("savedReceiverInformation", savedReceiverInformation); } } catch (Exception e) { Logging.info(this, "cannot save state: " + e.getLocalizedMessage()); } } public void onRestoreInstanceState(@NonNull Bundle inState) { super.onRestoreInstanceState(inState); try { savedReceiverInformation = inState.getString("savedReceiverInformation", ""); if (!savedReceiverInformation.isEmpty()) { Logging.info(this, "restore receiver information"); } } catch (Exception e) { Logging.info(this, "cannot restore state: " + e.getLocalizedMessage()); } } public Configuration getConfiguration() { return configuration; } @Override public boolean onCreateOptionsMenu(Menu menu) { mainMenu = menu; getMenuInflater().inflate(R.menu.activity_main_actions, menu); for (int i = 0; i < mainMenu.size(); i++) { final MenuItem m = mainMenu.getItem(i); Utils.updateMenuIconColor(this, m); if (m.getItemId() == R.id.menu_receiver_information) { m.setVisible(configuration.isDeveloperMode()); } if (m.getItemId() == R.id.menu_latest_logging) { m.setVisible(Logging.saveLogging); } } updateToolbar(stateHolder.getState()); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem menuItem) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(menuItem)) { return true; } Logging.info(this, "Selected main menu: " + menuItem.getTitle()); switch (menuItem.getItemId()) { case R.id.menu_power_standby: if (isConnected()) { powerOnOff(); } return true; case R.id.menu_receiver_information: { final String text = isConnected() ? getStateManager().getState().receiverInformation : getResources().getString(R.string.state_not_connected); final Dialogs dl = new Dialogs(this); dl.showXmlDialog(R.mipmap.ic_launcher, R.string.menu_receiver_information, text); return true; } case R.id.menu_latest_logging: { final Dialogs dl = new Dialogs(this); dl.showXmlDialog(R.mipmap.ic_launcher, R.string.menu_latest_logging, Logging.getLatestLogging()); return true; } default: return super.onOptionsItemSelected(menuItem); } } private void powerOnOff() { final State state = getStateManager().getState(); final PowerStatusMsg.PowerStatus p = state.isOn() ? PowerStatusMsg.PowerStatus.STB : PowerStatusMsg.PowerStatus.ON; final PowerStatusMsg cmdMsg = new PowerStatusMsg(getStateManager().getState().getActiveZone(), p); if (state.isOn() && isMultiroomAvailable() && state.isMasterDevice()) { final Dialogs dl = new Dialogs(this); dl.showOnStandByDialog(cmdMsg); } else { getStateManager().sendMessage(cmdMsg); } } @Override public void onBackPressed() { if (configuration.isBackAsReturn()) { final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); if (f != null && f.onBackPressed()) { return; } } if (!configuration.isExitConfirm()) { finish(); } else if (Utils.isToastVisible(exitToast)) { exitToast.cancel(); exitToast = null; finish(); } else { exitToast = Toast.makeText(this, R.string.action_exit_confirm, Toast.LENGTH_LONG); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { exitToast.addCallback(new Toast.Callback() { @Override public void onToastHidden() { exitToast = null; } }); } if (exitToast != null) { exitToast.show(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SETTINGS_ACTIVITY_REQID) { startRequestCode = requestCode; restartActivity(); } } @SuppressLint("UnsafeIntentLaunch") public void restartActivity() { PackageManager pm = getPackageManager(); Intent intent = pm.getLaunchIntentForPackage(getPackageName()); if (intent == null) { intent = getIntent(); } finish(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } public void connectToDevice(BroadcastResponseMsg response) { if (connectToDevice(response.getHost(), response.getPort(), false)) { configuration.saveDevice(response.getHost(), response.getPort()); updateTabs(); } } private void updateTabs() { // Update tabs since tabs depend on the protocol final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); pagerAdapter = new MainPagerAdapter(this, getSupportFragmentManager(), configuration); viewPager.setAdapter(pagerAdapter); try { setOpenedTab(f.getTabName()); } catch (Exception ex) { // nothing to do } } public boolean connectToDevice(final String device, final int port, final boolean connectToAnyInErrorCase) { // Parse and use input intent AutoPower.AutoPowerMode powerMode = null; if (configuration.isAutoPower()) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } if (SHORTCUT_AUTO_POWER.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } else if (SHORTCUT_ALL_STANDBY.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.ALL_STANDBY; } intentData = null; stateHolder.release(false, "reconnect"); stateHolder.waitForRelease(); onStateChanged(stateHolder.getState(), null); int zone = configuration.getZone(); try { final ArrayList<MessageScriptIf> messageScripts = new ArrayList<>(); if (powerMode != null) { messageScripts.add(new AutoPower(powerMode)); } messageScripts.add(new RequestListeningMode()); if (messageScript != null) { messageScripts.add(messageScript); zone = messageScript.getZone(); // Be sure that messageScript.tab contains a value from CfgAppSettings.Tabs enum. // If not, the app will crash here if (messageScript.tab != null) { try { setOpenedTab(CfgAppSettings.Tabs.valueOf(messageScript.tab.toUpperCase())); } catch (Exception ex) { // nothing to do } } } stateHolder.setStateManager(new StateManager( deviceList, connectionState, this, device, port, zone, true, savedReceiverInformation, messageScripts)); savedReceiverInformation = null; // Default receiver information used if ReceiverInformationMsg is missing { final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); configuration.setReceiverInformation(s); } if (!deviceList.isActive()) { deviceList.start(); } return true; } catch (Exception ex) { if (Configuration.ENABLE_MOCKUP) { stateHolder.setStateManager(new StateManager(connectionState, this, zone)); final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); updateConfiguration(s); return true; } else if (deviceList.isActive() && connectToAnyInErrorCase) { Logging.info(this, "searching for any device to connect"); connectToAnyDevice.set(true); } } return false; } @Override public void onDeviceFound(DeviceList.DeviceInfo di) { if (isConnected()) { getStateManager().inform(di.message); } else if (connectToAnyDevice.get()) { connectToAnyDevice.set(false); connectToDevice(di.message); } } public boolean isConnected() { return stateHolder.getStateManager() != null; } public StateManager getStateManager() { return stateHolder.getStateManager(); } public ConnectionState getConnectionState() { return connectionState; } @Override protected void onResume() { super.onResume(); if (startRequestCode == SETTINGS_ACTIVITY_REQID) { return; } // Analyse input intent handleIntent(getIntent()); connectionState.start(); if (connectionState.isActive()) { deviceList.start(); } if (!configuration.getDeviceName().isEmpty() && configuration.getDevicePort() > 0) { Logging.info(this, "use stored connection data: " + Utils.ipToString(configuration.getDeviceName(), configuration.getDevicePort())); connectToDevice(configuration.getDeviceName(), configuration.getDevicePort(), true); } else if (messageScript != null && !messageScript.getHost().equals(ConnectionIf.EMPTY_HOST) && messageScript.getPort() != ConnectionIf.EMPTY_PORT) { Logging.info(this, "use intent connection data: " + messageScript.getHostAndPort()); connectToDevice(messageScript.getHost(), messageScript.getPort(), true); } else { navigationDrawer.navigationSearchDevice(); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { if (intent != null) { Logging.info(this, "Received intent: " + intent); if (intent.getDataString() != null) { intentData = intent.getDataString(); if (intentData.startsWith("com.mkulesh.onpc")) { Logging.info(this, " direct command in the data field: " + intentData); } else { Logging.info(this, " message script in the data field: " + intentData); final MessageScript ms = (intentData != null && !intentData.isEmpty()) ? new MessageScript(this, intentData) : null; messageScript = ms != null && ms.isValid() ? ms : null; } } else { Logging.info(this, " direct command in the action field: " + intentData); intentData = intent.getAction(); } setIntent(null); } } @Override protected void onPause() { super.onPause(); final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); if (f != null && f.getTabName() != null) { configuration.appSettings.setOpenedTab(f.getTabName()); } if (getStateManager() != null) { savedReceiverInformation = getStateManager().getState().receiverInformation; } deviceList.stop(); connectionState.stop(); stateHolder.release(true, "pause"); } @Override public void onStateChanged(State state, @Nullable final HashSet<State.ChangeType> eventChanges) { if (state != null && eventChanges != null) { if (eventChanges.contains(State.ChangeType.RECEIVER_INFO) || eventChanges.contains(State.ChangeType.MULTIROOM_INFO)) { updateConfiguration(state); } } final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); if (f != null) { f.update(state, eventChanges); } if (eventChanges == null || eventChanges.contains(State.ChangeType.COMMON)) { updateToolbar(state); } } private void updateConfiguration(@NonNull State state) { configuration.setReceiverInformation(state); deviceList.updateFavorites(true); navigationDrawer.updateNavigationContent(state); updateToolbar(state); } @Override public void onManagerStopped() { stateHolder.setStateManager(null); } @Override public void onDeviceDisconnected() { if (!stateHolder.isAppExit()) { onStateChanged(stateHolder.getState(), null); } } private void updateToolbar(State state) { // Logo if (state == null) { toolbar.setSubtitle(R.string.state_not_connected); } else { final StringBuilder subTitle = new StringBuilder(); subTitle.append(state.getDeviceName(configuration.isFriendlyNames())); if (state.isExtendedZone()) { if (!subTitle.toString().isEmpty()) { subTitle.append("/"); } subTitle.append(state.getActiveZoneInfo().getName()); } if (!state.isOn()) { subTitle.append(" (").append(getResources().getString(R.string.state_standby)).append(")"); } toolbar.setSubtitle(subTitle.toString()); } // Main menu if (mainMenu != null) { for (int i = 0; i < mainMenu.size(); i++) { final MenuItem m = mainMenu.getItem(i); if (m.getItemId() == R.id.menu_power_standby) { m.setEnabled(state != null); Utils.updateMenuIconColor(this, m); if (m.isEnabled() && state != null) { Utils.setDrawableColorAttr(this, m.getIcon(), state.isOn() ? android.R.attr.textColorTertiary : R.attr.colorAccent); } } } } } /** * Navigation drawer: When using the ActionBarDrawerToggle, * you must call it during onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (isConnected() && configuration.audioControl.isVolumeKeys()) { if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) { if (event.getAction() == KeyEvent.ACTION_DOWN) { Logging.info(this, "Key event: " + event); getStateManager().changeMasterVolume(configuration.audioControl.getSoundControl(), event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP); return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { // Report to the OS that event is fully processed return true; } } } return super.dispatchKeyEvent(event); } @NonNull public DeviceList getDeviceList() { return deviceList; } public boolean isMultiroomAvailable() { return deviceList.getDevicesNumber() > 1; } @NonNull public String myDeviceId() { return stateHolder.getState() != null ? stateHolder.getState().multiroomDeviceId : ""; } @NonNull public String getMultiroomDeviceName(final @NonNull BroadcastResponseMsg msg) { if (msg.getAlias() != null) { return msg.getAlias(); } final State state = stateHolder.getState(); final String name = (configuration.isFriendlyNames() && state != null) ? state.multiroomNames.get(msg.getHostAndPort()) : null; return (name != null) ? name : msg.getDescription(); } public void setOpenedTab(CfgAppSettings.Tabs tab) { final ArrayList<CfgAppSettings.Tabs> tabs = configuration.appSettings.getVisibleTabs(); for (int i = 0; i < tabs.size(); i++) { if (tabs.get(i) == tab) { try { viewPager.setCurrentItem(i); } catch (Exception ex) { Logging.info(this, "can not change opened tab: " + ex.getLocalizedMessage()); } break; } } } }
29,144
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DraggableItemView.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/widgets/DraggableItemView.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.widgets; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.CheckedTextView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.Utils; import androidx.annotation.DrawableRes; public class DraggableItemView extends LinearLayout implements Checkable { private ImageView icon; private TextView textView; private CheckedTextView checkBox; private boolean checked; public DraggableItemView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onFinishInflate() { icon = this.findViewById(R.id.draggable_icon); textView = this.findViewById(R.id.draggable_text); checkBox = this.findViewById(R.id.draggable_checkbox); ImageView checkableDragger = this.findViewById(R.id.draggable_dragger); Utils.setImageViewColorAttr(getContext(), checkableDragger, android.R.attr.textColor); super.onFinishInflate(); } @Override public void setTag(Object tag) { textView.setTag(tag); } @Override public Object getTag() { return textView.getTag(); } public void setImage(@DrawableRes int imageId) { icon.setImageResource(imageId); icon.setVisibility(VISIBLE); Utils.setImageViewColorAttr(getContext(), icon, android.R.attr.textColorSecondary); } public void setText(String line) { textView.setText(line); } public void setCheckBoxVisibility(int visibility) { checkBox.setVisibility(visibility); } @Override public boolean isChecked() { return checked; } @Override public void setChecked(boolean checked) { this.checked = checked; checkBox.setChecked(this.checked); } @Override public void toggle() { setChecked(!checked); } }
2,729
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CheckableItemView.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/widgets/CheckableItemView.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.widgets; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.CheckedTextView; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.R; public class CheckableItemView extends LinearLayout implements Checkable { private TextView textView, description; private CheckedTextView checkBox; private boolean checked; public CheckableItemView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onFinishInflate() { textView = this.findViewById(R.id.checkable_text); description = this.findViewById(R.id.checkable_description); checkBox = this.findViewById(R.id.checkable_checkbox); super.onFinishInflate(); } @Override public void setTag(Object tag) { textView.setTag(tag); } @Override public Object getTag() { return textView.getTag(); } public void setText(String line) { textView.setText(line); } public void setDescription(String line) { textView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT; description.setVisibility(VISIBLE); description.setText(line); } public void setCheckBoxVisibility(int v) { checkBox.setVisibility(v); } @Override public boolean isChecked() { return checked; } @Override public void setChecked(boolean checked) { this.checked = checked; checkBox.setChecked(this.checked); } @Override public void toggle() { if (checkBox.getVisibility() == VISIBLE) { setChecked(!checked); } } }
2,512
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
HorizontalNumberPicker.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/widgets/HorizontalNumberPicker.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.widgets; import android.content.Context; import android.content.res.TypedArray; import android.text.Editable; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.Utils; import androidx.appcompat.widget.AppCompatImageButton; public class HorizontalNumberPicker extends LinearLayout implements OnClickListener { private EditText editText = null; private ImageButton bDecrease = null, bIncrease = null; private TextView description = null; public int minValue = 1; public int maxValue = Integer.MAX_VALUE; public HorizontalNumberPicker(Context context, AttributeSet attrs) { super(context, attrs); prepare(attrs); } public HorizontalNumberPicker(Context context) { super(context); prepare(null); } private void prepare(AttributeSet attrs) { setBaselineAligned(false); setVerticalGravity(Gravity.CENTER_VERTICAL); setOrientation(HORIZONTAL); final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (inflater != null) { inflater.inflate(R.layout.horizontal_number_picker, this); editText = findViewById(R.id.edit_text_value); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalNumberPicker, 0, 0); CharSequence label = a.getText(R.styleable.HorizontalNumberPicker_label); if (label != null) { ((TextView) findViewById(R.id.label_text)).setText(label); } editText.setMinimumWidth(a.getDimensionPixelSize(R.styleable.HorizontalNumberPicker_minWidth, 0)); a.recycle(); } bDecrease = findViewById(R.id.button_decrease); bDecrease.setOnClickListener(this); bDecrease.setOnLongClickListener(v -> Utils.showButtonDescription(getContext(), v)); updateViewColor(bDecrease); bIncrease = findViewById(R.id.button_increase); bIncrease.setOnClickListener(this); bIncrease.setOnLongClickListener(v -> Utils.showButtonDescription(getContext(), v)); updateViewColor(bIncrease); description = findViewById(R.id.label_text); } } @Override public void onClick(View v) { if (v.getId() == R.id.button_decrease) { editText.setText(String.valueOf(convertToInt(editText.getText(), -1))); } else if (v.getId() == R.id.button_increase) { editText.setText(String.valueOf(convertToInt(editText.getText(), 1))); } } public void setValue(int value) { editText.setText(String.valueOf(value)); } public int getValue() { return convertToInt(editText.getText(), 0); } private int convertToInt(Editable field, int inc) { try { final int r = Integer.parseInt(field.length() > 0 ? field.toString() : "") + inc; return Math.max(minValue, Math.min(maxValue, r)); } catch (Exception e) { return inc > 0 ? maxValue : minValue; } } @Override public void setEnabled(boolean enabled) { updateViewColor(editText); bDecrease.setEnabled(enabled); updateViewColor(bDecrease); bIncrease.setEnabled(enabled); updateViewColor(bIncrease); description.setEnabled(enabled); updateViewColor(description); super.setEnabled(enabled); } private void updateViewColor(View v) { if (v instanceof AppCompatImageButton) { final int attrId = v.isEnabled() ? R.attr.colorButtonEnabled : R.attr.colorButtonDisabled; Utils.setImageButtonColorAttr(getContext(), (AppCompatImageButton) v, attrId); } else if (v instanceof TextView) { final int attrId = v.isEnabled() ? R.attr.colorButtonEnabled : R.attr.colorButtonDisabled; final TextView b = (TextView) v; b.setTextColor(Utils.getThemeColorAttr(getContext(), attrId)); } } }
5,254
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CheckableItemAdapter.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CheckableItemAdapter.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.Context; import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.mkulesh.onpc.R; import com.mkulesh.onpc.widgets.DraggableItemView; import java.util.ArrayList; import java.util.List; import androidx.preference.PreferenceManager; class CheckableItemAdapter extends BaseAdapter { private final LayoutInflater inflater; private final List<CheckableItem> items = new ArrayList<>(); private final SharedPreferences preferences; private final String parameter; CheckableItemAdapter(Context context, String parameter) { inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); preferences = PreferenceManager.getDefaultSharedPreferences(context); this.parameter = parameter; } String getParameter() { return parameter; } void setItems(final List<CheckableItem> newItems) { for (CheckableItem d : newItems) { items.add(new CheckableItem(d)); } notifyDataSetChanged(); } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return items.get(position).id; } @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View convert, ViewGroup parent) { DraggableItemView view; if (convert == null) { view = (DraggableItemView) inflater.inflate(R.layout.draggable_item_view, parent, false); } else { view = (DraggableItemView) convert; } final CheckableItem d = items.get(position); view.setTag(d.code); view.setText(d.text); if (d.imageId > 0) { view.setImage(d.imageId); } return view; } void drop(int from, int to) { if (from != to && from < items.size() && to < items.size()) { CheckableItem p = items.remove(from); items.add(to, p); CheckableItem.writeToPreference(preferences, parameter, items); } notifyDataSetChanged(); } void setChecked(int pos, boolean checked) { if (pos < items.size()) { CheckableItem p = items.get(pos); p.checked = checked; CheckableItem.writeToPreference(preferences, parameter, items); } notifyDataSetChanged(); } }
3,440
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PreferencesListeningModes.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/PreferencesListeningModes.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.os.Bundle; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.List; public class PreferencesListeningModes extends DraggableListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ConnectionIf.ProtoType protoType = Configuration.getProtoType(preferences); Logging.info(this, "Listening mode for: " + protoType); prepareList(CfgAudioControl.getSelectedListeningModePar(protoType)); prepareSelectors(protoType); setTitle(R.string.pref_listening_modes); } private void prepareSelectors(final ConnectionIf.ProtoType protoType) { final ArrayList<String> defItems = new ArrayList<>(); for (ListeningModeMsg.Mode i : CfgAudioControl.getListeningModes(protoType)) { defItems.add(i.getCode()); } final List<CheckableItem> targetItems = new ArrayList<>(); final List<String> checkedItems = new ArrayList<>(); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, adapter.getParameter(), defItems)) { final ListeningModeMsg.Mode item = (ListeningModeMsg.Mode) ISCPMessage.searchParameter( sp.code, ListeningModeMsg.Mode.values(), ListeningModeMsg.Mode.UP); if (item == ListeningModeMsg.Mode.UP) { Logging.info(this, "Listening mode not known: " + sp.code); continue; } if (sp.checked) { checkedItems.add(item.getCode()); } targetItems.add(new CheckableItem( item.getDescriptionId(), item.getCode(), getString(item.getDescriptionId()), -1, sp.checked)); } setItems(targetItems, checkedItems); } }
2,800
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CheckableItem.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CheckableItem.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.annotation.SuppressLint; import android.content.SharedPreferences; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import static com.mkulesh.onpc.utils.Utils.getStringPref; class CheckableItem { final int id; final String code; final String text; @DrawableRes final int imageId; boolean checked; CheckableItem(final int id, @NonNull final String code, @NonNull final String text, @DrawableRes final int imageId, final boolean checked) { this.id = id; this.code = code; this.text = text; this.imageId = imageId; this.checked = checked; } private CheckableItem(@NonNull final String code, final boolean checked) { this.id = -1; this.code = code; this.text = ""; this.imageId = -1; this.checked = checked; } CheckableItem(@NonNull CheckableItem d) { this.id = d.id; this.code = d.code; this.text = d.text; this.imageId = d.imageId; this.checked = d.checked; } @NonNull @Override public String toString() { return code + "/" + checked; } @SuppressLint("ApplySharedPref") static void writeToPreference( @NonNull final SharedPreferences preferences, @NonNull final String parameter, @NonNull final List<CheckableItem> items) { final StringBuilder selectedItems = new StringBuilder(); for (CheckableItem d : items) { if (d != null) { if (!selectedItems.toString().isEmpty()) { selectedItems.append(";"); } selectedItems.append(d.code).append(",").append(d.checked); } } Logging.info(preferences, parameter + ": " + selectedItems); SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putString(parameter, selectedItems.toString()); prefEditor.commit(); } @NonNull static ArrayList<CheckableItem> readFromPreference( @NonNull final SharedPreferences preference, @NonNull final String parameter, @NonNull final ArrayList<String> defItems) { ArrayList<CheckableItem> retValue = new ArrayList<>(); final String cfg = getStringPref(preference, parameter, ""); // Add items stored in the configuration if (!cfg.isEmpty()) { final ArrayList<String> items = new ArrayList<>(Arrays.asList(cfg.split(";"))); if (items.isEmpty()) { for (String d : defItems) { retValue.add(new CheckableItem(d, true)); } } else { for (String d : items) { String[] item = d.split(","); if (item.length == 1) { retValue.add(new CheckableItem(item[0], true)); } else if (item.length == 2) { retValue.add(new CheckableItem(item[0], Boolean.parseBoolean(item[1]))); } } } } // Add missed default items for (String d : defItems) { boolean found = false; for (CheckableItem p : retValue) { if (d.equals(p.code)) { found = true; break; } } if (!found) { retValue.add(new CheckableItem(d, true)); } } return retValue; } }
4,705
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PreferencesMain.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/PreferencesMain.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import androidx.preference.ListPreference; import androidx.preference.PreferenceCategory; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceManager; import androidx.preference.PreferenceScreen; public class PreferencesMain extends AppCompatPreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportFragmentManager().beginTransaction().replace( android.R.id.content, new MyPreferenceFragment()).commit(); setTitle(R.string.drawer_app_settings); } @SuppressWarnings("WeakerAccess") public static class MyPreferenceFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.preferences_main); prepareListPreference(findPreference(CfgAppSettings.APP_THEME), getActivity()); prepareListPreference(findPreference(CfgAppSettings.APP_LANGUAGE), getActivity()); prepareListPreference(findPreference(CfgAudioControl.SOUND_CONTROL), null); tintIcons(getPreferenceScreen().getContext(), getPreferenceScreen()); hidePreferences(); } private void hidePreferences() { final PreferenceScreen screen = getPreferenceScreen(); final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(screen.getContext()); final ConnectionIf.ProtoType protoType = Configuration.getProtoType(preferences); if (protoType == ConnectionIf.ProtoType.DCP) { screen.removePreference(findPreference(CfgAppSettings.REMOTE_INTERFACE_AMP)); screen.removePreference(findPreference(CfgAppSettings.REMOTE_INTERFACE_CD)); //noinspection RedundantCast final PreferenceCategory adv = (PreferenceCategory) findPreference("category_advanced"); if (adv != null) { adv.removePreference(findPreference(Configuration.ADVANCED_QUEUE)); adv.removePreference(findPreference(Configuration.KEEP_PLAYBACK_MODE)); } } } } @SuppressWarnings("SameReturnValue") private static void prepareListPreference(final ListPreference listPreference, final Activity activity) { if (listPreference == null) { return; } if (listPreference.getValue() == null) { // to ensure we don't get a null value // set first value by default listPreference.setValueIndex(0); } if (listPreference.getEntry() != null) { listPreference.setSummary(listPreference.getEntry().toString()); } listPreference.setOnPreferenceChangeListener((preference, newValue) -> { listPreference.setValue(newValue.toString()); preference.setSummary(listPreference.getEntry().toString()); if (activity != null) { final Intent intent = activity.getIntent(); activity.finish(); activity.startActivity(intent); } return true; }); } }
4,289
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
DraggableListActivity.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/DraggableListActivity.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import com.mkulesh.onpc.R; import com.mobeta.android.dslv.DragSortListView; import java.util.List; import static com.mkulesh.onpc.utils.Utils.getStringPref; public abstract class DraggableListActivity extends AppCompatPreferenceActivity { CheckableItemAdapter adapter; void prepareList(String parameter) { setContentView(R.layout.draggable_preference_activity); adapter = new CheckableItemAdapter(this, parameter); } String[] getTokens(String par) { final String cfg = getStringPref(preferences, par, ""); return cfg.isEmpty() ? null : cfg.split(","); } void setItems(List<CheckableItem> targetItems, List<String> checkedItems) { adapter.setItems(targetItems); final DragSortListView itemList = findViewById(R.id.list); itemList.setAdapter(adapter); for (int i = 0; i < adapter.getCount(); i++) { itemList.setItemChecked(i, checkedItems.contains(targetItems.get(i).code)); } itemList.setOnItemClickListener((adapterView, view, pos, l) -> adapter.setChecked(pos, ((DragSortListView) adapterView).isItemChecked(pos))); itemList.setDropListener((int from, int to) -> adapter.drop(from, to)); } }
1,986
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CfgFavoriteShortcuts.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CfgFavoriteShortcuts.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.Context; import android.content.SharedPreferences; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import org.apache.commons.text.StringEscapeUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.util.ArrayList; import java.util.List; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.mkulesh.onpc.utils.Utils.getStringPref; public class CfgFavoriteShortcuts { private static final String FAVORITE_SHORTCUT_TAG = "favoriteShortcut"; private static final String FAVORITE_SHORTCUT_NUMBER = "favorite_shortcut_number"; private static final String FAVORITE_SHORTCUT_ITEM = "favorite_shortcut_item"; public static class Shortcut { public final int id; final InputSelectorMsg.InputType input; final ServiceType service; final String item; public final String alias; public int order; final List<String> pathItems = new ArrayList<>(); Shortcut(final Element e) { this.id = Utils.parseIntAttribute(e, "id", 0); this.input = (InputSelectorMsg.InputType) InputSelectorMsg.searchParameter( e.getAttribute("input"), InputSelectorMsg.InputType.values(), InputSelectorMsg.InputType.NONE); this.service = (ServiceType) ISCPMessage.searchParameter( e.getAttribute("service"), ServiceType.values(), ServiceType.UNKNOWN); this.item = e.getAttribute("item"); this.alias = e.getAttribute("alias"); this.order = Utils.parseIntAttribute(e, "order", id); for (Node dir = e.getFirstChild(); dir != null; dir = dir.getNextSibling()) { if (dir instanceof Element) { if (((Element) dir).getTagName().equals("dir")) { this.pathItems.add(((Element) dir).getAttribute("name")); } } } } public Shortcut(final Shortcut old, final String alias) { this.id = old.id; this.input = old.input; this.service = old.service; this.item = old.item; this.alias = alias; this.order = old.order; this.pathItems.addAll(old.pathItems); } public Shortcut(final int id, final InputSelectorMsg.InputType input, final ServiceType service, final String item, final String alias) { this.id = id; this.input = input; this.service = service; this.item = item; this.alias = alias; this.order = id; } public void setPathItems(@NonNull final List<String> path, @Nullable final Context context, @NonNull final ServiceType service) { pathItems.clear(); for (int i = 1; i < path.size(); i++) { // Issue #210: When creating a shortcut for a station from TuneIn "My Presets" on TX-NR646, // additional "TuneIn Radio" is sometime added in front of the path that makes the path invalid if (i == 1 && service == ServiceType.TUNEIN_RADIO && context != null && context.getString(service.getDescriptionId()).equals(path.get(i))) { continue; } pathItems.add(path.get(i)); } } @Override @NonNull public String toString() { StringBuilder label = new StringBuilder(); label.append("<").append(FAVORITE_SHORTCUT_TAG); label.append(" id=\"").append(id).append("\""); label.append(" input=\"").append(input.getCode()).append("\""); label.append(" service=\"").append(service.getCode()).append("\""); label.append(" item=\"").append(escape(item)).append("\""); label.append(" alias=\"").append(escape(alias)).append("\""); label.append(" order=\"").append(order).append("\">"); for (String dir : pathItems) { label.append("<dir name=\"").append(escape(dir)).append("\"/>"); } label.append("</" + FAVORITE_SHORTCUT_TAG + ">"); return label.toString(); } public String getLabel(Context context) { StringBuilder label = new StringBuilder(); if (input != InputSelectorMsg.InputType.NONE) { label.append(context.getString(input.getDescriptionId())).append("/"); } if (input == InputSelectorMsg.InputType.NET && service != ServiceType.UNKNOWN) { label.append(context.getString(service.getDescriptionId())).append("/"); } for (String dir : pathItems) { label.append(dir).append("/"); } label.append(item); return label.toString(); } @NonNull public String toScript(@NonNull final Context context, @NonNull final State state) { final StringBuilder data = new StringBuilder(); data.append("<onpcScript host=\"\" port=\"\" zone=\"0\">"); data.append("<send cmd=\"PWR\" par=\"QSTN\" wait=\"PWR\"/>"); data.append("<send cmd=\"PWR\" par=\"01\" wait=\"PWR\" resp=\"01\"/>"); data.append("<send cmd=\"SLI\" par=\"QSTN\" wait=\"SLI\"/>"); data.append("<send cmd=\"SLI\" par=\"").append(input.getCode()) .append("\" wait=\"SLI\" resp=\"").append(input.getCode()).append("\"/>"); // Radio input requires a special handling if (input == InputSelectorMsg.InputType.FM || input == InputSelectorMsg.InputType.DAB) { data.append("<send cmd=\"PRS\" par=\"").append(item).append("\" wait=\"PRS\"/>"); data.append("</onpcScript>"); return data.toString(); } // Issue #248: Shortcuts not working when an empty play queue is selected in MEDIA tab: // when an empty play queue is selected in MEDIA tab, NLT message is not answered by receiver final boolean emptyQueue = state.serviceType == ServiceType.PLAYQUEUE && state.numberOfItems == 0; if (!emptyQueue) { data.append("<send cmd=\"NLT\" par=\"QSTN\" wait=\"NLT\"/>"); } // Go to the top level. Response depends on the input type and model String firstPath = escape(pathItems.isEmpty() ? item : pathItems.get(0)); if (input == InputSelectorMsg.InputType.NET && service != ServiceType.UNKNOWN) { if ("TX-8130".equals(state.getModel())) { // Issue #233: on TX-8130, NTC(TOP) not always changes to the NET top. Sometime is still be // within a service line DLNA, i.e NTC(TOP) sometime moves to the top of the current service // (not to the top of network). In this case, listitem shall be ignored in the output data.append("<send cmd=\"NTC\" par=\"TOP\" wait=\"NLS\"/>"); } else { data.append("<send cmd=\"NTC\" par=\"TOP\" wait=\"NLS\" listitem=\"") .append(context.getString(service.getDescriptionId())).append("\"/>"); } } else { data.append("<send cmd=\"NTC\" par=\"TOP\" wait=\"NLA\" listitem=\"") .append(firstPath).append("\"/>"); } // Select target service data.append("<send cmd=\"NSV\" par=\"").append(service.getCode()) .append("0\" wait=\"NLA\" listitem=\"").append(firstPath).append("\"/>"); // Apply target path, if necessary if (!pathItems.isEmpty()) { for (int i = 0; i < pathItems.size() - 1; i++) { firstPath = escape(pathItems.get(i)); String nextPath = escape(pathItems.get(i + 1)); data.append("<send cmd=\"NLA\" par=\"").append(firstPath) .append("\" wait=\"NLA\" listitem=\"").append(nextPath).append("\"/>"); } String lastPath = escape(pathItems.get(pathItems.size() - 1)); data.append("<send cmd=\"NLA\" par=\"").append(lastPath) .append("\" wait=\"NLA\" listitem=\"") .append(escape(item)) .append("\"/>"); } // Select target item data.append("<send cmd=\"NLA\" par=\"") .append(escape(item)) .append("\" wait=\"1000\"/>"); data.append("</onpcScript>"); return data.toString(); } @DrawableRes public int getIcon() { int icon = service.getImageId(); if (icon == R.drawable.media_item_unknown) { icon = input.getImageId(); } return icon; } private String escape(final String d) { return StringEscapeUtils.escapeXml10(d); } } private final ArrayList<Shortcut> shortcuts = new ArrayList<>(); private SharedPreferences preferences; void setPreferences(SharedPreferences preferences) { this.preferences = preferences; } void read() { shortcuts.clear(); final int fcNumber = preferences.getInt(FAVORITE_SHORTCUT_NUMBER, 0); for (int i = 0; i < fcNumber; i++) { final String key = FAVORITE_SHORTCUT_ITEM + "_" + i; Utils.openXml(this, getStringPref(preferences, key, ""), (final Element elem) -> { if (elem.getTagName().equals(FAVORITE_SHORTCUT_TAG)) { shortcuts.add(new Shortcut(elem)); } }); } } private void write() { final int fcNumber = shortcuts.size(); SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putInt(FAVORITE_SHORTCUT_NUMBER, fcNumber); for (int i = 0; i < fcNumber; i++) { final String key = FAVORITE_SHORTCUT_ITEM + "_" + i; prefEditor.putString(key, shortcuts.get(i).toString()); } prefEditor.apply(); } @NonNull public final List<Shortcut> getShortcuts() { return shortcuts; } private int find(final int id) { for (int i = 0; i < shortcuts.size(); i++) { final Shortcut item = shortcuts.get(i); if (item.id == id) { return i; } } return -1; } public void updateShortcut(@NonNull final Shortcut shortcut, final String alias) { Shortcut newMsg; int idx = find(shortcut.id); if (idx >= 0) { final Shortcut oldMsg = shortcuts.get(idx); newMsg = new Shortcut(oldMsg, alias); Logging.info(this, "Update favorite shortcut: " + oldMsg + " -> " + newMsg); shortcuts.set(idx, newMsg); } else { newMsg = new Shortcut(shortcut, alias); Logging.info(this, "Add favorite shortcut: " + newMsg); shortcuts.add(newMsg); } write(); } public void deleteShortcut(@NonNull final Shortcut shortcut) { int idx = find(shortcut.id); if (idx >= 0) { final Shortcut oldMsg = shortcuts.get(idx); Logging.info(this, "Delete favorite shortcut: " + oldMsg.toString()); shortcuts.remove(oldMsg); write(); } } public int getNextId() { int id = 0; for (Shortcut s : shortcuts) { id = Math.max(id, s.id); } return id + 1; } public void reorder(List<Shortcut> items) { for (int i = 0; i < items.size(); i++) { int idx = find(items.get(i).id); if (idx >= 0) { shortcuts.get(idx).order = i; } } write(); } }
13,490
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PreferencesDeviceSelectors.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/PreferencesDeviceSelectors.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.os.Bundle; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.mkulesh.onpc.utils.Utils.getStringPref; public class PreferencesDeviceSelectors extends DraggableListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prepareList(Configuration.getSelectedDeviceSelectorsParameter(preferences)); prepareSelectors(); setTitle(R.string.pref_device_selectors); } private void prepareSelectors() { final String[] allItems = getTokens(Configuration.DEVICE_SELECTORS); if (allItems == null || allItems.length == 0) { return; } final boolean fName = preferences.getBoolean(Configuration.FRIENDLY_NAMES, true); final ArrayList<String> defItems = new ArrayList<>(Arrays.asList(allItems)); final List<CheckableItem> targetItems = new ArrayList<>(); final List<String> checkedItems = new ArrayList<>(); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, adapter.getParameter(), defItems)) { final InputSelectorMsg.InputType item = (InputSelectorMsg.InputType) InputSelectorMsg.searchParameter( sp.code, InputSelectorMsg.InputType.values(), InputSelectorMsg.InputType.NONE); if (item == InputSelectorMsg.InputType.NONE) { Logging.info(this, "Input selector not known: " + sp.code); continue; } if (sp.checked) { checkedItems.add(item.getCode()); } final String defName = getString(item.getDescriptionId()); final String name = fName ? getStringPref(preferences, Configuration.DEVICE_SELECTORS + "_" + item.getCode(), defName) : defName; targetItems.add(new CheckableItem( item.getDescriptionId(), item.getCode(), name, -1, sp.checked)); } setItems(targetItems, checkedItems); } }
3,020
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
Configuration.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/Configuration.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import static com.mkulesh.onpc.utils.Utils.getStringPref; public class Configuration { public static final boolean ENABLE_MOCKUP = false; static final String PROTO_TYPE = "proto_type"; private static final String SERVER_NAME = "server_name"; private static final String SERVER_PORT = "server_port"; static final String MODEL = "model"; private static final String ACTIVE_ZONE = "active_zone"; static final String DEVICE_SELECTORS = "device_selectors"; private static final String SELECTED_DEVICE_SELECTORS = "selected_device_selectors"; private static final String AUTO_POWER = "auto_power"; static final String FRIENDLY_NAMES = "pref_friendly_names"; static final String NETWORK_SERVICES = "network_services"; private static final String SELECTED_NETWORK_SERVICES = "selected_network_services"; private static final String KEEP_SCREEN_ON = "keep_screen_on"; static final String SHOW_WHEN_LOCKED = "show_when_locked"; private static final String BACK_AS_RETURN = "back_as_return"; static final String ADVANCED_QUEUE = "advanced_queue"; static final String KEEP_PLAYBACK_MODE = "keep_playback_mode"; private static final String EXIT_CONFIRM = "exit_confirm"; private static final String DEVELOPER_MODE = "developer_mode"; private final SharedPreferences preferences; private String deviceName; private int devicePort; public final CfgAppSettings appSettings = new CfgAppSettings(); public final CfgAudioControl audioControl = new CfgAudioControl(); public final CfgFavoriteConnections favoriteConnections = new CfgFavoriteConnections(); public final CfgFavoriteShortcuts favoriteShortcuts = new CfgFavoriteShortcuts(); public Configuration(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); deviceName = preferences.getString(Configuration.SERVER_NAME, ""); devicePort = preferences.getInt(Configuration.SERVER_PORT, ConnectionIf.ISCP_PORT); appSettings.setPreferences(preferences); audioControl.setPreferences(preferences); audioControl.read(context); favoriteConnections.setPreferences(preferences); favoriteConnections.read(); favoriteShortcuts.setPreferences(preferences); favoriteShortcuts.read(); } public String getDeviceName() { return deviceName; } public int getDevicePort() { return devicePort; } @SuppressLint("SetTextI18n") public String getDevicePortAsString() { return Integer.toString(devicePort); } public void saveDevice(final String device, final int port) { deviceName = device; devicePort = port; SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putString(SERVER_NAME, device); prefEditor.putInt(SERVER_PORT, port); prefEditor.apply(); } public void initActiveZone(int defaultActiveZone) { final String activeZone = getStringPref(preferences, ACTIVE_ZONE, ""); if (activeZone.isEmpty()) { setActiveZone(defaultActiveZone); } } @SuppressLint("ApplySharedPref") public void setActiveZone(int zone) { SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putString(ACTIVE_ZONE, Integer.toString(zone)); prefEditor.commit(); } public int getZone() { try { final String activeZone = getStringPref(preferences, ACTIVE_ZONE, ""); return (activeZone.isEmpty()) ? ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE : Integer.parseInt(activeZone); } catch (Exception e) { return ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE; } } public void setReceiverInformation(@NonNull State state) { SharedPreferences.Editor prefEditor = preferences.edit(); Logging.info(this, "Save receiver information"); Logging.info(this, " Network protocol: " + state.protoType.name()); prefEditor.putString(PROTO_TYPE, state.protoType.name()); final String model = state.getModel(); Logging.info(this, " Model: " + model); if (!model.isEmpty()) { prefEditor.putString(MODEL, model); } if (!state.networkServices.isEmpty()) { final StringBuilder str = new StringBuilder(); for (final String p : state.networkServices.keySet()) { if (!str.toString().isEmpty()) { str.append(","); } str.append(p); } Logging.info(this, " Network services: " + str); prefEditor.putString(NETWORK_SERVICES, str.toString()); } List<ReceiverInformationMsg.Selector> deviceSelectors = state.cloneDeviceSelectors(); if (!deviceSelectors.isEmpty()) { final StringBuilder str = new StringBuilder(); for (ReceiverInformationMsg.Selector d : deviceSelectors) { if (!str.toString().isEmpty()) { str.append(","); } str.append(d.getId()); prefEditor.putString(DEVICE_SELECTORS + "_" + d.getId(), d.getName()); } Logging.info(this, " Device selectors: " + str); prefEditor.putString(DEVICE_SELECTORS, str.toString()); } prefEditor.apply(); favoriteConnections.updateIdentifier(state); } @NonNull static String getSelectedDeviceSelectorsParameter(final SharedPreferences p) { return Configuration.SELECTED_DEVICE_SELECTORS + "_" + p.getString(MODEL, "NONE"); } @NonNull public ArrayList<ReceiverInformationMsg.Selector> getSortedDeviceSelectors( boolean allItems, @NonNull InputSelectorMsg.InputType activeItem, @NonNull final List<ReceiverInformationMsg.Selector> defaultItems) { final ArrayList<ReceiverInformationMsg.Selector> result = new ArrayList<>(); final ArrayList<String> defItems = new ArrayList<>(); for (ReceiverInformationMsg.Selector i : defaultItems) { defItems.add(i.getId()); } final String par = getSelectedDeviceSelectorsParameter(preferences); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, par, defItems)) { final boolean visible = allItems || sp.checked || (activeItem != InputSelectorMsg.InputType.NONE && activeItem.getCode().equals(sp.code)); for (ReceiverInformationMsg.Selector i : defaultItems) { if (visible && i.getId().equals(sp.code)) { result.add(i); } } } return result; } public boolean isAutoPower() { return preferences.getBoolean(AUTO_POWER, false); } public boolean isFriendlyNames() { return preferences.getBoolean(FRIENDLY_NAMES, true); } @NonNull static String getSelectedNetworkServicesParameter(final SharedPreferences p) { return Configuration.SELECTED_NETWORK_SERVICES + "_" + p.getString(MODEL, "NONE"); } @NonNull public ArrayList<NetworkServiceMsg> getSortedNetworkServices( @NonNull ServiceType activeItem, @NonNull final List<NetworkServiceMsg> defaultItems) { final ArrayList<NetworkServiceMsg> result = new ArrayList<>(); final ArrayList<String> defItems = new ArrayList<>(); for (NetworkServiceMsg i : defaultItems) { defItems.add(i.getService().getCode()); } final String par = getSelectedNetworkServicesParameter(preferences); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, par, defItems)) { final boolean visible = sp.checked || (activeItem != ServiceType.UNKNOWN && activeItem.getCode().equals(sp.code)); for (NetworkServiceMsg i : defaultItems) { if (visible && i.getService().getCode().equals(sp.code)) { result.add(new NetworkServiceMsg(i)); } } } return result; } public boolean isKeepScreenOn() { return preferences.getBoolean(Configuration.KEEP_SCREEN_ON, false); } public boolean isShowWhenLocked() { return preferences.getBoolean(Configuration.SHOW_WHEN_LOCKED, false); } public boolean isBackAsReturn() { return preferences.getBoolean(Configuration.BACK_AS_RETURN, false); } public boolean isAdvancedQueue() { return preferences.getBoolean(Configuration.ADVANCED_QUEUE, false); } public boolean keepPlaybackMode() { return preferences.getBoolean(Configuration.KEEP_PLAYBACK_MODE, false); } public boolean isExitConfirm() { return preferences.getBoolean(Configuration.EXIT_CONFIRM, false); } public boolean isDeveloperMode() { return preferences.getBoolean(DEVELOPER_MODE, false); } @NonNull public static ConnectionIf.ProtoType getProtoType(final SharedPreferences preferences) { final String protoType = preferences.getString(Configuration.PROTO_TYPE, "NONE"); for (ConnectionIf.ProtoType p : ConnectionIf.ProtoType.values()) { if (p.name().equalsIgnoreCase(protoType)) { return p; } } return ConnectionIf.ProtoType.ISCP; } }
11,101
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PreferencesVisibleTabs.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/PreferencesVisibleTabs.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.os.Bundle; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.List; public class PreferencesVisibleTabs extends DraggableListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prepareList(CfgAppSettings.VISIBLE_TABS); prepareSelectors(); setTitle(R.string.pref_visible_tabs); } private void prepareSelectors() { final ArrayList<String> defItems = new ArrayList<>(); for (CfgAppSettings.Tabs i : CfgAppSettings.Tabs.values()) { defItems.add(i.name()); } final ConnectionIf.ProtoType protoType = Configuration.getProtoType(preferences); final List<CheckableItem> targetItems = new ArrayList<>(); final List<String> checkedItems = new ArrayList<>(); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, adapter.getParameter(), defItems)) { try { final CfgAppSettings.Tabs item = CfgAppSettings.Tabs.valueOf(sp.code); if (!item.isVisible(protoType)) { continue; } if (sp.checked) { checkedItems.add(item.name()); } targetItems.add(new CheckableItem( item.ordinal(), item.name(), CfgAppSettings.getTabName(this, item), -1, sp.checked)); } catch (Exception ex) { Logging.info(this, "A tab with code not known: " + sp.code); } } setItems(targetItems, checkedItems); } }
2,582
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PreferencesNetworkServices.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/PreferencesNetworkServices.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.os.Bundle; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ISCPMessage; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PreferencesNetworkServices extends DraggableListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prepareList(Configuration.getSelectedNetworkServicesParameter(preferences)); prepareSelectors(); setTitle(R.string.pref_network_services); } private void prepareSelectors() { final String[] allItems = getTokens(Configuration.NETWORK_SERVICES); if (allItems == null || allItems.length == 0) { return; } final ArrayList<String> defItems = new ArrayList<>(Arrays.asList(allItems)); final List<CheckableItem> targetItems = new ArrayList<>(); final List<String> checkedItems = new ArrayList<>(); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, adapter.getParameter(), defItems)) { final ServiceType item = (ServiceType) ISCPMessage.searchParameter( sp.code, ServiceType.values(), ServiceType.UNKNOWN); if (item == ServiceType.UNKNOWN) { Logging.info(this, "Service not known: " + sp.code); continue; } if (sp.checked) { checkedItems.add(item.getCode()); } targetItems.add(new CheckableItem( item.getDescriptionId(), item.getCode(), getString(item.getDescriptionId()), item.getImageId(), sp.checked)); } setItems(targetItems, checkedItems); } }
2,610
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AppCompatPreferenceActivity.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/AppCompatPreferenceActivity.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.Locale; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.preference.Preference; import androidx.preference.PreferenceGroup; import androidx.preference.PreferenceManager; public abstract class AppCompatPreferenceActivity extends AppCompatActivity { SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { final com.mkulesh.onpc.config.Configuration configuration = new com.mkulesh.onpc.config.Configuration(this); setTheme(configuration.appSettings.getTheme(this, com.mkulesh.onpc.config.CfgAppSettings.ThemeType.SETTINGS_THEME)); getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); setupActionBar(); preferences = PreferenceManager.getDefaultSharedPreferences(this); } @Override protected void attachBaseContext(Context newBase) { final Locale prefLocale = AppLocale.ContextWrapper.getPreferredLocale(newBase); Logging.info(this, "Settings locale: " + prefLocale); super.attachBaseContext(AppLocale.ContextWrapper.wrap(newBase, prefLocale)); } @Override public void applyOverrideConfiguration(android.content.res.Configuration overrideConfiguration) { // See https://stackoverflow.com/questions/55265834/change-locale-not-work-after-migrate-to-androidx: // There is an issue in new app compat libraries related to night mode that is causing to // override the configuration on android 21 to 25. This can be fixed as follows if (overrideConfiguration != null) { int uiMode = overrideConfiguration.uiMode; overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration()); overrideConfiguration.uiMode = uiMode; } super.applyOverrideConfiguration(overrideConfiguration); } static void tintIcons(final Context c, Preference preference) { if (preference instanceof PreferenceGroup) { PreferenceGroup group = ((PreferenceGroup) preference); Utils.setDrawableColorAttr(c, group.getIcon(), android.R.attr.textColorSecondary); for (int i = 0; i < group.getPreferenceCount(); i++) { tintIcons(c, group.getPreference(i)); } } else { Utils.setDrawableColorAttr(c, preference.getIcon(), android.R.attr.textColorSecondary); } } private void setupActionBar() { ViewGroup rootView = findViewById(R.id.action_bar_root); //id from appcompat if (rootView != null) { View view = getLayoutInflater().inflate(R.layout.settings_toolbar, rootView, false); rootView.addView(view, 0); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { //noinspection SwitchStatementWithTooFewBranches switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return (super.onOptionsItemSelected(item)); } }
4,589
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CfgFavoriteConnections.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CfgFavoriteConnections.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.SharedPreferences; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.State; import com.mkulesh.onpc.iscp.messages.BroadcastResponseMsg; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.mkulesh.onpc.utils.Utils.getStringPref; public class CfgFavoriteConnections { private static final String FAVORITE_CONNECTION_SEP = "<;>"; private static final String FAVORITE_CONNECTION_NUMBER = "favorite_connection_number"; private static final String FAVORITE_CONNECTION_ITEM = "favorite_connection_item"; private final ArrayList<BroadcastResponseMsg> devices = new ArrayList<>(); private SharedPreferences preferences; void setPreferences(SharedPreferences preferences) { this.preferences = preferences; } void read() { devices.clear(); final int fcNumber = preferences.getInt(FAVORITE_CONNECTION_NUMBER, 0); for (int i = 0; i < fcNumber; i++) { final String key = FAVORITE_CONNECTION_ITEM + "_" + i; final String val = getStringPref(preferences, key, ""); final String[] tokens = val.split(FAVORITE_CONNECTION_SEP); if (tokens.length >= 3) { try { devices.add(new BroadcastResponseMsg( tokens[0], /* host */ Integer.parseInt(tokens[1], 10), /* port */ tokens[2], /* alias */ tokens.length == 3 ? null : tokens[3])); /* identifier that is optional */ } catch (Exception ex) { // nothing to do } } } } private void write() { final int fcNumber = devices.size(); SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putInt(FAVORITE_CONNECTION_NUMBER, fcNumber); for (int i = 0; i < fcNumber; i++) { final BroadcastResponseMsg msg = devices.get(i); if (msg.getAlias() != null) { final String key = FAVORITE_CONNECTION_ITEM + "_" + i; String val = msg.getHost() + FAVORITE_CONNECTION_SEP + msg.getPort() + FAVORITE_CONNECTION_SEP + msg.getAlias(); // identifier is optional if (!msg.getIdentifier().isEmpty()) { val += FAVORITE_CONNECTION_SEP + msg.getIdentifier(); } prefEditor.putString(key, val); } } prefEditor.apply(); } @NonNull public final List<BroadcastResponseMsg> getDevices() { return devices; } private int find(@NonNull final ConnectionIf connection) { for (int i = 0; i < devices.size(); i++) { final BroadcastResponseMsg msg = devices.get(i); if (msg.fromHost(connection)) { return i; } } return -1; } public BroadcastResponseMsg updateDevice(@NonNull final ConnectionIf connection, @NonNull final String alias, @Nullable final String identifier) { BroadcastResponseMsg newMsg; int idx = find(connection); if (idx >= 0) { final BroadcastResponseMsg oldMsg = devices.get(idx); newMsg = new BroadcastResponseMsg(connection.getHost(), connection.getPort(), alias, identifier); Logging.info(this, "Update favorite connection: " + oldMsg.toString() + " -> " + newMsg); devices.set(idx, newMsg); } else { newMsg = new BroadcastResponseMsg(connection.getHost(), connection.getPort(), alias, null); Logging.info(this, "Add favorite connection: " + newMsg); devices.add(newMsg); } write(); return newMsg; } public void deleteDevice(@NonNull final ConnectionIf connection) { int idx = find(connection); if (idx >= 0) { final BroadcastResponseMsg oldMsg = devices.get(idx); Logging.info(this, "Delete favorite connection: " + oldMsg.toString()); devices.remove(oldMsg); write(); } } void updateIdentifier(@NonNull State state) { String identifier = state.deviceProperties.get("macaddress"); if (identifier == null) { identifier = state.deviceProperties.get("deviceserial"); } if (identifier == null) { return; } int idx = find(state); if (idx >= 0) { final BroadcastResponseMsg oldMsg = devices.get(idx); if (oldMsg.getAlias() != null) { final BroadcastResponseMsg newMsg = new BroadcastResponseMsg( oldMsg.getHost(), oldMsg.getPort(), oldMsg.getAlias(), identifier); Logging.info(this, "Update favorite connection: " + oldMsg + " -> " + newMsg); devices.set(idx, newMsg); write(); } } } }
6,084
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CfgAppSettings.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CfgAppSettings.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import java.util.Locale; import androidx.annotation.NonNull; import androidx.annotation.StyleRes; import static com.mkulesh.onpc.utils.Utils.getStringPref; public class CfgAppSettings { // Themes public enum ThemeType { MAIN_THEME, SETTINGS_THEME } static final String APP_THEME = "app_theme"; // Languages static final String APP_LANGUAGE = "app_language"; // Tabs public enum Tabs { LISTEN(true, true), MEDIA(true, true), SHORTCUTS(true, false), DEVICE(true, true), RC(true, true), RI(true, false); final boolean isIscp, isDcp; @SuppressWarnings("SameParameterValue") Tabs(final boolean isIscp, final boolean isDcp) { this.isIscp = isIscp; this.isDcp = isDcp; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isVisible(ConnectionIf.ProtoType pt) { return (pt == ConnectionIf.ProtoType.ISCP && isIscp) || (pt == ConnectionIf.ProtoType.DCP && isDcp); } } static final String VISIBLE_TABS = "visible_tabs"; private static final String OPENED_TAB_NAME = "opened_tab_name"; // RI static final String REMOTE_INTERFACE_AMP = "remote_interface_amp"; static final String REMOTE_INTERFACE_CD = "remote_interface_cd"; private SharedPreferences preferences; void setPreferences(SharedPreferences preferences) { this.preferences = preferences; } @StyleRes public int getTheme(final Context context, ThemeType type) { final String themeCode = preferences.getString(APP_THEME, context.getResources().getString(R.string.pref_theme_default)); final CharSequence[] allThemes = context.getResources().getStringArray(R.array.pref_theme_codes); int themeIndex = 0; for (int i = 0; i < allThemes.length; i++) { if (allThemes[i].toString().equals(themeCode)) { themeIndex = i; break; } } if (type == ThemeType.MAIN_THEME) { TypedArray mainThemes = context.getResources().obtainTypedArray(R.array.main_themes); final int resId = mainThemes.getResourceId(themeIndex, R.style.BaseThemeIndigoOrange); mainThemes.recycle(); return resId; } else { TypedArray settingsThemes = context.getResources().obtainTypedArray(R.array.settings_themes); final int resId = settingsThemes.getResourceId(themeIndex, R.style.SettingsThemeIndigoOrange); settingsThemes.recycle(); return resId; } } public static String getTabName(final Context context, Tabs item) { Locale l = Locale.getDefault(); try { final String[] tabNames = context.getResources().getStringArray(R.array.pref_visible_tabs_names); return item.ordinal() < tabNames.length ? tabNames[item.ordinal()].toUpperCase(l) : ""; } catch (Exception ex) { return ""; } } @NonNull public ArrayList<CfgAppSettings.Tabs> getVisibleTabs() { final ArrayList<CfgAppSettings.Tabs> result = new ArrayList<>(); final ArrayList<String> defItems = new ArrayList<>(); for (CfgAppSettings.Tabs i : CfgAppSettings.Tabs.values()) { defItems.add(i.name()); } final ConnectionIf.ProtoType protoType = Configuration.getProtoType(preferences); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, VISIBLE_TABS, defItems)) { for (CfgAppSettings.Tabs i : CfgAppSettings.Tabs.values()) { if (!i.isVisible(protoType)) { continue; } if (sp.checked && i.name().equals(sp.code)) { result.add(i); } } } return result; } public CfgAppSettings.Tabs getOpenedTab() { CfgAppSettings.Tabs retValue = Tabs.LISTEN; try { final String tab = getStringPref(preferences, OPENED_TAB_NAME, Tabs.LISTEN.toString()); retValue = CfgAppSettings.Tabs.valueOf(tab.toUpperCase()); } catch (Exception ex) { // nothing to do } return retValue; } public void setOpenedTab(CfgAppSettings.Tabs tab) { Logging.info(this, "Save opened tab: " + tab.toString()); SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putString(OPENED_TAB_NAME, tab.toString()); prefEditor.apply(); } public boolean isRemoteInterfaceAmp() { return preferences.getBoolean(REMOTE_INTERFACE_AMP, false); } public boolean isRemoteInterfaceCd() { return preferences.getBoolean(REMOTE_INTERFACE_CD, false); } }
6,011
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
CfgAudioControl.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/CfgAudioControl.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.content.Context; import android.content.SharedPreferences; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.ConnectionIf; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.utils.Logging; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class CfgAudioControl { static final String SOUND_CONTROL = "sound_control"; private static final String FORCE_AUDIO_CONTROL = "force_audio_control"; private static final String SELECTED_LISTENING_MODES = "selected_listening_modes"; private static final String MASTER_VOLUME_MAX = "master_volume_max"; private static final String VOLUME_KEYS = "volume_keys"; private static final ListeningModeMsg.Mode[] ISCP_LISTENING_MODES = new ListeningModeMsg.Mode[]{ ListeningModeMsg.Mode.MODE_0F, // MONO ListeningModeMsg.Mode.MODE_00, // STEREO ListeningModeMsg.Mode.MODE_01, // DIRECT ListeningModeMsg.Mode.MODE_09, // UNPLUGGED ListeningModeMsg.Mode.MODE_08, // ORCHESTRA ListeningModeMsg.Mode.MODE_0A, // STUDIO-MIX ListeningModeMsg.Mode.MODE_11, // PURE AUDIO ListeningModeMsg.Mode.MODE_0C, // ALL CH STEREO ListeningModeMsg.Mode.MODE_0B, // TV Logic ListeningModeMsg.Mode.MODE_0D, // Theater-Dimensional ListeningModeMsg.Mode.MODE_40, // DOLBY DIGITAL ListeningModeMsg.Mode.MODE_80, // DOLBY SURROUND ListeningModeMsg.Mode.MODE_84, // Dolby THX Cinema ListeningModeMsg.Mode.MODE_8B, // Dolby THX Music ListeningModeMsg.Mode.MODE_89, // Dolby THX Games ListeningModeMsg.Mode.MODE_03, // Game-RPG ListeningModeMsg.Mode.MODE_05, // Game-Action ListeningModeMsg.Mode.MODE_06, // Game-Rock ListeningModeMsg.Mode.MODE_0E, // Game-Sports ListeningModeMsg.Mode.MODE_82, // DTS NEURAL:X ListeningModeMsg.Mode.MODE_17 // DTS Virtual:X }; private static final ListeningModeMsg.Mode[] DCP_LISTENING_MODES = new ListeningModeMsg.Mode[]{ ListeningModeMsg.Mode.DCP_DIRECT, ListeningModeMsg.Mode.DCP_PURE_DIRECT, ListeningModeMsg.Mode.DCP_STEREO, ListeningModeMsg.Mode.DCP_AUTO, ListeningModeMsg.Mode.DCP_DOLBY_DIGITAL, ListeningModeMsg.Mode.DCP_DTS_SURROUND, ListeningModeMsg.Mode.DCP_AURO3D, ListeningModeMsg.Mode.DCP_AURO2DSURR, ListeningModeMsg.Mode.DCP_MCH_STEREO, ListeningModeMsg.Mode.DCP_WIDE_SCREEN, ListeningModeMsg.Mode.DCP_SUPER_STADIUM, ListeningModeMsg.Mode.DCP_ROCK_ARENA, ListeningModeMsg.Mode.DCP_JAZZ_CLUB, ListeningModeMsg.Mode.DCP_CLASSIC_CONCERT, ListeningModeMsg.Mode.DCP_MONO_MOVIE, ListeningModeMsg.Mode.DCP_MATRIX, ListeningModeMsg.Mode.DCP_VIDEO_GAME, ListeningModeMsg.Mode.DCP_VIRTUAL }; private SharedPreferences preferences; private String soundControl; void setPreferences(SharedPreferences preferences) { this.preferences = preferences; } void read(final Context context) { soundControl = preferences.getString(CfgAudioControl.SOUND_CONTROL, context.getResources().getString(R.string.pref_sound_control_default)); } public String getSoundControl() { return soundControl; } public boolean isForceAudioControl() { return preferences.getBoolean(FORCE_AUDIO_CONTROL, false); } @NonNull private String getMasterVolumeMaxParameter() { return MASTER_VOLUME_MAX + "_" + preferences.getString(Configuration.MODEL, "NONE"); } public int getMasterVolumeMax() { return preferences.getInt(getMasterVolumeMaxParameter(), Integer.MAX_VALUE); } public void setMasterVolumeMax(int limit) { Logging.info(this, "Save volume max limit: " + limit); SharedPreferences.Editor prefEditor = preferences.edit(); prefEditor.putInt(getMasterVolumeMaxParameter(), limit); prefEditor.apply(); } @NonNull public ArrayList<ListeningModeMsg.Mode> getSortedListeningModes( boolean allItems, @Nullable ListeningModeMsg.Mode activeItem, @NonNull ConnectionIf.ProtoType protoType) { final ArrayList<ListeningModeMsg.Mode> result = new ArrayList<>(); final ArrayList<String> defItems = new ArrayList<>(); for (ListeningModeMsg.Mode i : getListeningModes(protoType)) { defItems.add(i.getCode()); } final String par = getSelectedListeningModePar(protoType); for (CheckableItem sp : CheckableItem.readFromPreference(preferences, par, defItems)) { final boolean visible = allItems || sp.checked || (activeItem != null && activeItem.getCode().equals(sp.code)); for (ListeningModeMsg.Mode i : getListeningModes(protoType)) { if (visible && i.getCode().equals(sp.code)) { result.add(i); } } } return result; } public boolean isVolumeKeys() { return preferences.getBoolean(VOLUME_KEYS, false); } public static ListeningModeMsg.Mode[] getListeningModes(@NonNull ConnectionIf.ProtoType protoType) { return protoType == ConnectionIf.ProtoType.ISCP ? ISCP_LISTENING_MODES : DCP_LISTENING_MODES; } public static String getSelectedListeningModePar(@NonNull ConnectionIf.ProtoType protoType) { String par = SELECTED_LISTENING_MODES; if (protoType == ConnectionIf.ProtoType.DCP) { par += "_DCP"; } return par; } }
6,624
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
AppLocale.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/config/AppLocale.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.config; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.os.LocaleList; import android.preference.PreferenceManager; import java.util.Locale; import static com.mkulesh.onpc.utils.Utils.getStringPref; /********************************************************* * Handling of locale (language etc) *********************************************************/ public final class AppLocale { public static class ContextWrapper extends android.content.ContextWrapper { ContextWrapper(Context base) { super(base); } public static Locale getPreferredLocale(Context context) { final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); final String languageCode = getStringPref(pref, com.mkulesh.onpc.config.CfgAppSettings.APP_LANGUAGE, "system"); if (languageCode.equals("system")) { return new Locale(Locale.getDefault().getLanguage()); } String[] array = languageCode.split("-r", -1); if (array.length == 1) { return new Locale(array[0]); } else { return new Locale(array[0], array[1]); } } @SuppressLint({ "NewApi", "AppBundleLocaleChanges" }) public static ContextWrapper wrap(Context context, Locale newLocale) { final Resources res = context.getResources(); final Configuration configuration = res.getConfiguration(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { configuration.setLocale(newLocale); LocaleList localeList = new LocaleList(newLocale); LocaleList.setDefault(localeList); configuration.setLocales(localeList); context = context.createConfigurationContext(configuration); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { configuration.setLocale(newLocale); context = context.createConfigurationContext(configuration); } else { configuration.locale = newLocale; } res.updateConfiguration(configuration, res.getDisplayMetrics()); return new ContextWrapper(context); } } }
3,354
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ConnectionState.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/ConnectionState.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.widget.Toast; import com.mkulesh.onpc.R; import com.mkulesh.onpc.utils.AppTask; import com.mkulesh.onpc.utils.Logging; import androidx.annotation.NonNull; import androidx.annotation.StringRes; @SuppressLint("NewApi") public class ConnectionState extends AppTask { public enum FailureReason { NO_NETWORK(R.string.error_connection_no_network), NO_WIFI(R.string.error_connection_no_wifi); @StringRes final int descriptionId; FailureReason(@StringRes final int descriptionId) { this.descriptionId = descriptionId; } @StringRes int getDescriptionId() { return descriptionId; } } private final Context context; private final ConnectivityManager connectivity; private final WifiManager wifi; public ConnectionState(Context context) { super(true); this.context = context; this.connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); this.wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); } public Context getContext() { return context; } boolean isNetwork() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // getActiveNetwork Added in API level 23 final Network net = connectivity.getActiveNetwork(); if (net == null) { return false; } // getNetworkCapabilities Added in API level 21 return connectivity.getNetworkCapabilities(net) != null; } else { // getActiveNetworkInfo, Added in API level 1, Deprecated in API level 29 final NetworkInfo netInfo = connectivity.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnected(); } } @SuppressWarnings("deprecation") boolean isWifi() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // getActiveNetwork Added in API level 23 final Network net = connectivity.getActiveNetwork(); if (net == null) { return false; } // getNetworkCapabilities Added in API level 21 final NetworkCapabilities cap = connectivity.getNetworkCapabilities(net); if (cap == null) { return false; } // hasTransport Added in API level 21 return cap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || cap.hasTransport(NetworkCapabilities.TRANSPORT_VPN); } else { // If app targets Android 10 or higher, it must have the ACCESS_FINE_LOCATION permission // in order to use getConnectionInfo(), see // https://developer.android.com/about/versions/10/privacy/changes return wifi != null && wifi.isWifiEnabled() && wifi.getConnectionInfo() != null && wifi.getConnectionInfo().getNetworkId() != -1; } } public void showFailure(@NonNull final FailureReason reason) { final String message = context.getResources().getString(reason.getDescriptionId()); Logging.info(this, message); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } }
4,458
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ISCPMessage.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/ISCPMessage.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class ISCPMessage implements ConnectionIf { protected final static String PAR_SEP = "/"; protected final static String COMMA_SEP = ","; private final String code; protected final int messageId; protected final String data; private final Character modelCategoryId; // connected host (ConnectionIf) protected String host = ConnectionIf.EMPTY_HOST; protected int port = ConnectionIf.EMPTY_PORT; protected ISCPMessage(final int messageId, final String data) { this.code = null; this.messageId = messageId; this.data = data; modelCategoryId = 'X'; } @SuppressWarnings("RedundantThrows") protected ISCPMessage(EISCPMessage raw) throws Exception { code = raw.getCode(); messageId = raw.getMessageId(); data = raw.getParameters().trim(); modelCategoryId = raw.getModelCategoryId(); } protected ISCPMessage(ISCPMessage other) { code = other.code; messageId = other.messageId; data = other.data; modelCategoryId = other.modelCategoryId; host = other.host; port = other.port; } @NonNull @Override public String getHost() { return host; } @Override public int getPort() { return port; } @NonNull @Override public String getHostAndPort() { return Utils.ipToString(host, port); } void setHostAndPort(@NonNull final ConnectionIf connection) { host = connection.getHost(); port = connection.getPort(); } public boolean fromHost(@NonNull final ConnectionIf connection) { return host.equals(connection.getHost()) && port == connection.getPort(); } public boolean isValidConnection() { return !host.equals(ConnectionIf.EMPTY_HOST) && port != ConnectionIf.EMPTY_PORT; } public final String getCode() { return code; } public int getMessageId() { return messageId; } public final String getData() { return data; } @NonNull @Override public String toString() { return "ISCPMessage/" + modelCategoryId; } protected boolean isMultiline() { return data != null && data.length() > EISCPMessage.LOG_LINE_LENGTH; } void logParameters() { if (!Logging.isEnabled() || data == null) { return; } String p = data; while (true) { if (p.length() > EISCPMessage.LOG_LINE_LENGTH) { Logging.info(this, p.substring(0, EISCPMessage.LOG_LINE_LENGTH)); p = p.substring(EISCPMessage.LOG_LINE_LENGTH); } else { Logging.info(this, p); break; } } } /** * Helper methods for enumerations based on char parameter */ protected interface CharParameterIf { Character getCode(); } protected static CharParameterIf searchParameter(Character code, CharParameterIf[] values, CharParameterIf defValue) { for (CharParameterIf t : values) { if (t.getCode() == code) { return t; } } return defValue; } /** * Helper methods for enumerations based on char parameter */ public interface StringParameterIf { String getCode(); } public static StringParameterIf searchParameter(String code, StringParameterIf[] values, StringParameterIf defValue) { if (code == null) { return defValue; } for (StringParameterIf t : values) { if (t.getCode().equalsIgnoreCase(code)) { return t; } } return defValue; } public EISCPMessage getCmdMsg() { return null; } public boolean hasImpactOnMediaList() { return true; } protected String getTags(String[] pars, int start, int end) { StringBuilder str = new StringBuilder(); for (int i = start; i < Math.min(end, pars.length); i++) { if (pars[i] != null && !pars[i].isEmpty()) { if (!str.toString().isEmpty()) { str.append(", "); } str.append(pars[i]); } } return str.toString(); } /* * Denon control protocol */ public final static String DCP_MSG_SEP = "==>>"; protected final static String DCP_MSG_REQ = "?"; public final static String DCP_HEOS_PID = "{$PLAYER_PID}"; @NonNull public static ArrayList<String> getAcceptedDcpCodes() { return new ArrayList<>(); } @Nullable public String buildDcpMsg(boolean isQuery) { return null; } public interface DcpStringParameterIf extends StringParameterIf { @NonNull String getDcpCode(); } @Nullable public static DcpStringParameterIf searchDcpParameter(@NonNull final String dcpCommand, @NonNull final String dcpMsg, @NonNull final DcpStringParameterIf[] values) { if (dcpMsg.startsWith(dcpCommand)) { final String par = dcpMsg.substring(dcpCommand.length()).trim(); return searchDcpParameter(par, values, null); } return null; } @Nullable public static DcpStringParameterIf searchDcpParameter(@Nullable final String par, @NonNull final DcpStringParameterIf[] values, DcpStringParameterIf defValue) { for (DcpStringParameterIf t : values) { if (t.getDcpCode().equalsIgnoreCase(par)) { return t; } } return defValue; } public interface DcpCharParameterIf extends CharParameterIf { @NonNull String getDcpCode(); } @Nullable public static DcpCharParameterIf searchDcpParameter(@Nullable final String par, @NonNull final DcpCharParameterIf[] values) { for (DcpCharParameterIf t : values) { if (t.getDcpCode().equalsIgnoreCase(par)) { return t; } } return null; } public static Map<String, String> parseHeosMessage(final String heosMsg) { final Map<String, String> retValue = new HashMap<>(); final String[] heosTokens = heosMsg.split("&"); for (String token : heosTokens) { final String[] parTokens = token.split("="); if (parTokens.length == 2) { retValue.put(parTokens[0], parTokens[1]); } else if (parTokens.length == 1) { retValue.put(parTokens[0], ""); } } return retValue; } protected static String getDcpGoformUrl(final String host, final int port, final String s) { return "http://" + host + ":" + port + "/goform/" + s; } protected static String getDcpAppCommand(final String s) { return "<?xml version=\"1.0\" encoding=\"utf-8\"?><tx>" + s + "</tx>"; } }
8,518
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
MessageChannelIscp.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/MessageChannelIscp.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.os.StrictMode; import android.widget.Toast; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.messages.MessageFactory; import com.mkulesh.onpc.iscp.messages.OperationCommandMsg; import com.mkulesh.onpc.utils.AppTask; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import androidx.annotation.NonNull; public class MessageChannelIscp extends AppTask implements Runnable, MessageChannel { private final static long CONNECTION_TIMEOUT = 5000; private final static int SOCKET_BUFFER = 4 * 1024; // thread implementation private final AtomicBoolean threadCancelled = new AtomicBoolean(); // connection state private final ConnectionState connectionState; private SocketChannel socket = null; // connected host (ConnectionIf) private String host = ConnectionIf.EMPTY_HOST; private int port = ConnectionIf.EMPTY_PORT; // input-output queues private final BlockingQueue<EISCPMessage> outputQueue = new ArrayBlockingQueue<>(QUEUE_SIZE, true); private final BlockingQueue<ISCPMessage> inputQueue; // message handling private byte[] packetJoinBuffer = null; private int messageId = 0; private final Set<String> allowedMessages = new HashSet<>(); MessageChannelIscp(final ConnectionState connectionState, final BlockingQueue<ISCPMessage> inputQueue) { super(false); this.connectionState = connectionState; this.inputQueue = inputQueue; StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } @Override public void start() { if (isActive()) { return; } super.start(); final Thread thread = new Thread(this, this.getClass().getSimpleName()); threadCancelled.set(false); thread.start(); } @Override public void stop() { synchronized (threadCancelled) { threadCancelled.set(true); } } @NonNull @Override public String getHost() { return host; } @Override public int getPort() { return port; } @NonNull @Override public String getHostAndPort() { return Utils.ipToString(host, port); } @Override public void addAllowedMessage(final String code) { allowedMessages.add(code); } @Override public ProtoType getProtoType() { return ConnectionIf.ProtoType.ISCP; } @Override public void run() { Logging.info(this, "started " + getHostAndPort() + ":" + this); ByteBuffer buffer = ByteBuffer.allocate(SOCKET_BUFFER); while (true) { try { synchronized (threadCancelled) { if (threadCancelled.get()) { Logging.info(this, "cancelled " + getHostAndPort()); break; } } if (!connectionState.isNetwork()) { Logging.info(this, "no network"); break; } // process input messages buffer.clear(); int readedSize = socket.read(buffer); if (readedSize < 0) { Logging.info(this, "host " + getHostAndPort() + " disconnected"); break; } else if (readedSize > 0) { try { processInputData(buffer); } catch (Exception e) { Logging.info(this, "error: process input data: " + e.getLocalizedMessage()); break; } } // process output messages EISCPMessage m = outputQueue.poll(); if (m != null) { final byte[] bytes = m.getBytes(); if (bytes != null) { final ByteBuffer messageBuffer = ByteBuffer.wrap(bytes); Logging.info(this, ">> sending: " + m + " to " + getHostAndPort()); socket.write(messageBuffer); } } } catch (Exception e) { Logging.info(this, "interrupted " + getHostAndPort() + ": " + e.getLocalizedMessage()); break; } } try { socket.close(); } catch (IOException e) { // nothing to do } super.stop(); Logging.info(this, "stopped " + getHostAndPort() + ":" + this); inputQueue.add(new OperationCommandMsg(OperationCommandMsg.Command.DOWN)); } @Override public boolean connectToServer(@NonNull String host, int port) { this.host = host; this.port = port; try { socket = SocketChannel.open(); socket.configureBlocking(false); socket.connect(new InetSocketAddress(host, port)); final long startTime = Calendar.getInstance().getTimeInMillis(); while (!socket.finishConnect()) { final long currTime = Calendar.getInstance().getTimeInMillis(); if (currTime > startTime + CONNECTION_TIMEOUT) { throw new Exception("connection timeout"); } } if (socket.socket().getInetAddress() != null && socket.socket().getInetAddress().getHostAddress() != null) { this.host = socket.socket().getInetAddress().getHostAddress(); } Logging.info(this, "connected to " + getHostAndPort()); return true; } catch (Exception e) { String message = String.format(connectionState.getContext().getResources().getString( R.string.error_connection_no_response), getHostAndPort()); Logging.info(this, message + ": " + e.getLocalizedMessage()); for (StackTraceElement t : e.getStackTrace()) { Logging.info(this, t.toString()); } try { // An exception is possible here: // Can't toast on a thread that has not called Looper.prepare() Toast.makeText(connectionState.getContext(), message, Toast.LENGTH_LONG).show(); } catch (Exception e1) { // nothing to do } } return false; } private void processInputData(ByteBuffer buffer) { buffer.flip(); final int incoming = buffer.remaining(); byte[] bytes; if (packetJoinBuffer == null) { // A new buffer - just copy it bytes = new byte[incoming]; buffer.get(bytes); } else { // Remaining part of existing buffer - join it final int s1 = packetJoinBuffer.length; bytes = new byte[s1 + incoming]; System.arraycopy(packetJoinBuffer, 0, bytes, 0, s1); buffer.get(bytes, s1, incoming); packetJoinBuffer = null; } int remaining = bytes.length; while (remaining > 0) { final int startIndex = EISCPMessage.getMsgStartIndex(bytes); if (startIndex < 0) { Logging.info(this, "<< error: message start marker not found. " + remaining + "B ignored"); return; } else if (startIndex > 0) { Logging.info(this, "<< error: unexpected position of message start: " + startIndex + ", remaining=" + remaining + "B"); } // convert header and data sizes int hSize, dSize; try { hSize = EISCPMessage.getHeaderSize(bytes, startIndex); dSize = EISCPMessage.getDataSize(bytes, startIndex); } catch (Exception e) { Logging.info(this, "<< error: invalid expected size: " + e.getLocalizedMessage()); packetJoinBuffer = null; return; } // inspect expected size final int expectedSize = hSize + dSize; if (hSize < 0 || dSize < 0 || expectedSize > remaining) { packetJoinBuffer = bytes; return; } // try to convert raw message. In case of any errors, skip expectedSize EISCPMessage raw = null; try { messageId++; raw = new EISCPMessage(messageId, bytes, startIndex, hSize, dSize); } catch (Exception e) { remaining = Math.max(0, bytes.length - expectedSize); Logging.info(this, "<< error: invalid raw message: " + e.getLocalizedMessage() + ", remaining=" + remaining + "B"); } if (raw != null) { remaining = Math.max(0, bytes.length - raw.getMsgSize()); try { final boolean ignored = !allowedMessages.isEmpty() && !allowedMessages.contains(raw.getCode()); if (!ignored) { if (!"NTM".equals(raw.getCode())) { Logging.info(this, "<< new message " + raw.getCode() + " from " + getHostAndPort() + ", size=" + raw.getMsgSize() + "B, remaining=" + remaining + "B"); } ISCPMessage msg = MessageFactory.create(raw); msg.setHostAndPort(this); inputQueue.add(msg); } } catch (Exception e) { Logging.info(this, "<< error: ignored: " + e.getLocalizedMessage() + ": " + raw); } } if (remaining > 0) { bytes = Utils.catBuffer(bytes, bytes.length - remaining, remaining); } } } @Override public void sendMessage(EISCPMessage eiscpMessage) { outputQueue.add(eiscpMessage); } }
11,864
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
State.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/State.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.messages.AlbumNameMsg; import com.mkulesh.onpc.iscp.messages.ArtistNameMsg; import com.mkulesh.onpc.iscp.messages.AudioInformationMsg; import com.mkulesh.onpc.iscp.messages.AudioMutingMsg; import com.mkulesh.onpc.iscp.messages.AutoPowerMsg; import com.mkulesh.onpc.iscp.messages.CdPlayerOperationCommandMsg; import com.mkulesh.onpc.iscp.messages.CenterLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.CustomPopupMsg; import com.mkulesh.onpc.iscp.messages.DcpAudioRestorerMsg; import com.mkulesh.onpc.iscp.messages.DcpEcoModeMsg; import com.mkulesh.onpc.iscp.messages.DcpMediaContainerMsg; import com.mkulesh.onpc.iscp.messages.DcpMediaItemMsg; import com.mkulesh.onpc.iscp.messages.DcpReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.DcpSearchCriteriaMsg; import com.mkulesh.onpc.iscp.messages.DcpTunerModeMsg; import com.mkulesh.onpc.iscp.messages.DigitalFilterMsg; import com.mkulesh.onpc.iscp.messages.DimmerLevelMsg; import com.mkulesh.onpc.iscp.messages.DirectCommandMsg; import com.mkulesh.onpc.iscp.messages.FileFormatMsg; import com.mkulesh.onpc.iscp.messages.FirmwareUpdateMsg; import com.mkulesh.onpc.iscp.messages.FriendlyNameMsg; import com.mkulesh.onpc.iscp.messages.GoogleCastAnalyticsMsg; import com.mkulesh.onpc.iscp.messages.GoogleCastVersionMsg; import com.mkulesh.onpc.iscp.messages.HdmiCecMsg; import com.mkulesh.onpc.iscp.messages.InputSelectorMsg; import com.mkulesh.onpc.iscp.messages.JacketArtMsg; import com.mkulesh.onpc.iscp.messages.LateNightCommandMsg; import com.mkulesh.onpc.iscp.messages.ListInfoMsg; import com.mkulesh.onpc.iscp.messages.ListTitleInfoMsg; import com.mkulesh.onpc.iscp.messages.ListeningModeMsg; import com.mkulesh.onpc.iscp.messages.MasterVolumeMsg; import com.mkulesh.onpc.iscp.messages.MenuStatusMsg; import com.mkulesh.onpc.iscp.messages.MultiroomChannelSettingMsg; import com.mkulesh.onpc.iscp.messages.MultiroomDeviceInformationMsg; import com.mkulesh.onpc.iscp.messages.MusicOptimizerMsg; import com.mkulesh.onpc.iscp.messages.NetworkServiceMsg; import com.mkulesh.onpc.iscp.messages.NetworkStandByMsg; import com.mkulesh.onpc.iscp.messages.PhaseMatchingBassMsg; import com.mkulesh.onpc.iscp.messages.PlayStatusMsg; import com.mkulesh.onpc.iscp.messages.PowerStatusMsg; import com.mkulesh.onpc.iscp.messages.PresetCommandMsg; import com.mkulesh.onpc.iscp.messages.PrivacyPolicyStatusMsg; import com.mkulesh.onpc.iscp.messages.RadioStationNameMsg; import com.mkulesh.onpc.iscp.messages.ReceiverInformationMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.iscp.messages.SleepSetCommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerACommandMsg; import com.mkulesh.onpc.iscp.messages.SpeakerBCommandMsg; import com.mkulesh.onpc.iscp.messages.SubwooferLevelCommandMsg; import com.mkulesh.onpc.iscp.messages.TimeInfoMsg; import com.mkulesh.onpc.iscp.messages.TitleNameMsg; import com.mkulesh.onpc.iscp.messages.ToneCommandMsg; import com.mkulesh.onpc.iscp.messages.TrackInfoMsg; import com.mkulesh.onpc.iscp.messages.TuningCommandMsg; import com.mkulesh.onpc.iscp.messages.VideoInformationMsg; import com.mkulesh.onpc.iscp.messages.XmlListInfoMsg; import com.mkulesh.onpc.iscp.messages.XmlListItemMsg; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import java.io.ByteArrayOutputStream; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicReference; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.util.Pair; public class State implements ConnectionIf { private static final boolean SKIP_XML_MESSAGES = false; public static final String BRAND_PIONEER = "Pioneer"; // Changes public enum ChangeType { NONE, COMMON, TIME_SEEK, MEDIA_ITEMS, RECEIVER_INFO, AUDIO_CONTROL, MULTIROOM_INFO } // connected host (ConnectionIf) public final ProtoType protoType; private final String host; private final int port; // Receiver Information public String receiverInformation = ""; String friendlyName = null; public Map<String, String> deviceProperties = new HashMap<>(); public Map<String, ReceiverInformationMsg.NetworkService> networkServices = new TreeMap<>(); private final int activeZone; private List<ReceiverInformationMsg.Zone> zones = new ArrayList<>(); private final List<ReceiverInformationMsg.Selector> deviceSelectors = new ArrayList<>(); private Set<String> controlList = new HashSet<>(); private HashMap<String, ReceiverInformationMsg.ToneControl> toneControls = new HashMap<>(); //Common public PowerStatusMsg.PowerStatus powerStatus = PowerStatusMsg.PowerStatus.STB; public FirmwareUpdateMsg.Status firmwareStatus = FirmwareUpdateMsg.Status.NONE; public InputSelectorMsg.InputType inputType = InputSelectorMsg.InputType.NONE; // Settings public DimmerLevelMsg.Level dimmerLevel = DimmerLevelMsg.Level.NONE; public DigitalFilterMsg.Filter digitalFilter = DigitalFilterMsg.Filter.NONE; public AudioMutingMsg.Status audioMuting = AudioMutingMsg.Status.NONE; public MusicOptimizerMsg.Status musicOptimizer = MusicOptimizerMsg.Status.NONE; public AutoPowerMsg.Status autoPower = AutoPowerMsg.Status.NONE; public HdmiCecMsg.Status hdmiCec = HdmiCecMsg.Status.NONE; public DirectCommandMsg.Status toneDirect = DirectCommandMsg.Status.NONE; public PhaseMatchingBassMsg.Status phaseMatchingBass = PhaseMatchingBassMsg.Status.NONE; public int sleepTime = SleepSetCommandMsg.NOT_APPLICABLE; public SpeakerACommandMsg.Status speakerA = SpeakerACommandMsg.Status.NONE; public SpeakerBCommandMsg.Status speakerB = SpeakerBCommandMsg.Status.NONE; public LateNightCommandMsg.Status lateNightMode = LateNightCommandMsg.Status.NONE; public NetworkStandByMsg.Status networkStandBy = NetworkStandByMsg.Status.NONE; // Sound control public enum SoundControlType { DEVICE_BUTTONS, DEVICE_SLIDER, DEVICE_BTN_AROUND_SLIDER, DEVICE_BTN_ABOVE_SLIDER, RI_AMP, NONE } public ListeningModeMsg.Mode listeningMode = ListeningModeMsg.Mode.MODE_FF; public int volumeLevel = MasterVolumeMsg.NO_LEVEL; public int bassLevel = ToneCommandMsg.NO_LEVEL; public int trebleLevel = ToneCommandMsg.NO_LEVEL; public int subwooferLevel = SubwooferLevelCommandMsg.NO_LEVEL; public int subwooferCmdLength = SubwooferLevelCommandMsg.NO_LEVEL; public int centerLevel = CenterLevelCommandMsg.NO_LEVEL; public int centerCmdLength = CenterLevelCommandMsg.NO_LEVEL; // Google cast public String googleCastVersion = "N/A"; public GoogleCastAnalyticsMsg.Status googleCastAnalytics = GoogleCastAnalyticsMsg.Status.NONE; private String privacyPolicy = PrivacyPolicyStatusMsg.Status.NONE.getCode(); // Track info (default values are set in clearTrackInfo method) public Bitmap cover; private URL coverUrl = null; public String album, artist, title, currentTime, maxTime, fileFormat; Integer currentTrack = null, maxTrack = null; private ByteArrayOutputStream coverBuffer = null; // Radio public DcpTunerModeMsg.TunerMode dcpTunerMode = DcpTunerModeMsg.TunerMode.NONE; public List<ReceiverInformationMsg.Preset> presetList = new ArrayList<>(); public int preset = PresetCommandMsg.NO_PRESET; private String frequency = ""; public String stationName = ""; // Playback public PlayStatusMsg.PlayStatus playStatus = PlayStatusMsg.PlayStatus.STOP; public PlayStatusMsg.RepeatStatus repeatStatus = PlayStatusMsg.RepeatStatus.OFF; public PlayStatusMsg.ShuffleStatus shuffleStatus = PlayStatusMsg.ShuffleStatus.OFF; public MenuStatusMsg.TimeSeek timeSeek = MenuStatusMsg.TimeSeek.ENABLE; private MenuStatusMsg.TrackMenu trackMenu = MenuStatusMsg.TrackMenu.ENABLE; public MenuStatusMsg.Feed positiveFeed = MenuStatusMsg.Feed.DISABLE; public MenuStatusMsg.Feed negativeFeed = MenuStatusMsg.Feed.DISABLE; public ServiceType serviceIcon = ServiceType.UNKNOWN; // service that is currently playing // Navigation public ServiceType serviceType = null; // service that is currently selected (may differs from currently playing) ListTitleInfoMsg.LayerInfo layerInfo = null; private ListTitleInfoMsg.UIType uiType = null; int numberOfLayers = 0; public int numberOfItems = 0; private int currentCursorPosition = 0; public String titleBar = ""; private final List<XmlListItemMsg> mediaItems = new ArrayList<>(); final List<NetworkServiceMsg> serviceItems = new ArrayList<>(); private final List<String> listInfoItems = new ArrayList<>(); // Path used for shortcuts private int pathIndexOffset = 0; public final List<String> pathItems = new ArrayList<>(); // Multiroom public String multiroomDeviceId = ""; public final Map<String, MultiroomDeviceInformationMsg> multiroomLayout = new HashMap<>(); public final Map<String, String> multiroomNames = new HashMap<>(); public MultiroomDeviceInformationMsg.ChannelType multiroomChannel = MultiroomDeviceInformationMsg.ChannelType.NONE; // Audio/Video information dialog public String avInfoAudioInput = ""; public String avInfoAudioOutput = ""; public String avInfoVideoInput = ""; public String avInfoVideoOutput = ""; // Denon settings public DcpEcoModeMsg.Status dcpEcoMode = DcpEcoModeMsg.Status.NONE; public DcpAudioRestorerMsg.Status dcpAudioRestorer = DcpAudioRestorerMsg.Status.NONE; public final List<DcpMediaContainerMsg> dcpMediaPath = new ArrayList<>(); public String mediaListCid = ""; public String mediaListMid = ""; private final List<XmlListItemMsg> dcpTrackMenuItems = new ArrayList<>(); private final Map<String, List<Pair<String, Integer>>> dcpSearchCriteria = new HashMap<>(); public String mediaListSid = ""; // Popup public final AtomicReference<CustomPopupMsg> popup = new AtomicReference<>(); // Default tone control private static final ReceiverInformationMsg.ToneControl DEFAULT_BASS_CONTROL = new ReceiverInformationMsg.ToneControl(ToneCommandMsg.BASS_KEY, -10, 10, 2); private static final ReceiverInformationMsg.ToneControl DEFAULT_TREBLE_CONTROL = new ReceiverInformationMsg.ToneControl(ToneCommandMsg.TREBLE_KEY, -10, 10, 2); State(final ProtoType protoType, final String host, int port, int activeZone) { this.protoType = protoType; this.host = host; this.port = port; this.activeZone = activeZone; clearTrackInfo(); } @NonNull @Override public String getHost() { return host; } @Override public int getPort() { return port; } @NonNull @Override public String getHostAndPort() { return Utils.ipToString(host, port); } @NonNull @Override public String toString() { return powerStatus.toString() + "; activeZone=" + activeZone; } public List<ReceiverInformationMsg.Zone> getZones() { return zones; } public int getActiveZone() { return activeZone; } public boolean isExtendedZone() { return activeZone < zones.size() && activeZone != ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE; } public ReceiverInformationMsg.Zone getActiveZoneInfo() { return activeZone < zones.size() ? zones.get(activeZone) : null; } public boolean isReceiverInformation() { return receiverInformation != null && !receiverInformation.isEmpty(); } public boolean isFriendlyName() { return friendlyName != null; } public boolean isOn() { return powerStatus == PowerStatusMsg.PowerStatus.ON; } public boolean isPlaying() { return playStatus != PlayStatusMsg.PlayStatus.STOP; } public boolean isUiTypeValid() { return uiType != null; } public boolean isPlaybackMode() { return uiType == ListTitleInfoMsg.UIType.PLAYBACK; } public boolean isPopupMode() { return uiType == ListTitleInfoMsg.UIType.POPUP || uiType == ListTitleInfoMsg.UIType.KEYBOARD; } public boolean isMenuMode() { return uiType == ListTitleInfoMsg.UIType.MENU || uiType == ListTitleInfoMsg.UIType.MENU_LIST; } public boolean isTrackMenuActive() { return trackMenu == MenuStatusMsg.TrackMenu.ENABLE && isPlaying(); } @NonNull public String getModel() { final String m = deviceProperties.get("model"); return m == null ? getHostAndPort() : m; } @NonNull public String getBrand() { final String m = deviceProperties.get("brand"); return m == null ? "" : m; } @NonNull public String getDeviceName(boolean useFriendlyName) { if (useFriendlyName) { // name from FriendlyNameMsg (NFN) if (friendlyName != null && !friendlyName.isEmpty()) { return friendlyName; } // fallback to ReceiverInformationMsg final String name = deviceProperties.get("friendlyname"); if (name != null) { return name; } } // fallback to model from ReceiverInformationMsg { final String name = getModel(); if (!name.isEmpty()) { return name; } } return ""; } public void createDefaultReceiverInfo(final Context context, final boolean forceAudioControl) { // By default, add all possible device selectors synchronized (deviceSelectors) { deviceSelectors.clear(); for (InputSelectorMsg.InputType it : InputSelectorMsg.InputType.values()) { if (protoType != it.getProtoType()) { continue; } if (it != InputSelectorMsg.InputType.NONE) { // #265 Add new input selector "SOURCE": // "SOURCE" input not allowed for main zone final int zones = it == InputSelectorMsg.InputType.SOURCE ? ReceiverInformationMsg.EXT_ZONES : ReceiverInformationMsg.ALL_ZONES; final ReceiverInformationMsg.Selector s = new ReceiverInformationMsg.Selector( it.getCode(), context.getString(it.getDescriptionId()), zones, it.getCode(), false); deviceSelectors.add(s); } } } // Add default bass and treble limits toneControls.clear(); toneControls.put(ToneCommandMsg.BASS_KEY, DEFAULT_BASS_CONTROL); toneControls.put(ToneCommandMsg.TREBLE_KEY, DEFAULT_TREBLE_CONTROL); toneControls.put(SubwooferLevelCommandMsg.KEY, new ReceiverInformationMsg.ToneControl(SubwooferLevelCommandMsg.KEY, -15, 12, 1)); toneControls.put(CenterLevelCommandMsg.KEY, new ReceiverInformationMsg.ToneControl(CenterLevelCommandMsg.KEY, -12, 12, 1)); // Default zones: zones = ReceiverInformationMsg.getDefaultZones(); // Audio control if (forceAudioControl) { volumeLevel = volumeLevel == MasterVolumeMsg.NO_LEVEL ? 0 : volumeLevel; bassLevel = bassLevel == ToneCommandMsg.NO_LEVEL ? 0 : bassLevel; trebleLevel = trebleLevel == ToneCommandMsg.NO_LEVEL ? 0 : trebleLevel; } // Settings if (protoType == ConnectionIf.ProtoType.DCP) { controlList.add("Setup"); controlList.add("Quick"); } } public ReceiverInformationMsg.ToneControl getToneControl(final String toneKey, final boolean forceAudioControl) { final ReceiverInformationMsg.ToneControl cfg = toneControls.get(toneKey); if (cfg != null) { return cfg; } if (forceAudioControl && toneKey.equals(ToneCommandMsg.BASS_KEY)) { return DEFAULT_BASS_CONTROL; } if (forceAudioControl && toneKey.equals(ToneCommandMsg.TREBLE_KEY)) { return DEFAULT_TREBLE_CONTROL; } return null; } public boolean isControlExists(@NonNull final String control) { return controlList != null && controlList.contains(control); } public boolean isListeningModeControl() { if (controlList == null) { return true; } else { for (final String c : controlList) { if (c.startsWith(ListeningModeMsg.CODE)) { return true; } } } return false; } private void clearTrackInfo() { cover = null; coverUrl = null; album = ""; artist = ""; title = ""; fileFormat = ""; currentTime = TimeInfoMsg.INVALID_TIME; maxTime = TimeInfoMsg.INVALID_TIME; currentTrack = null; maxTrack = null; titleBar = ""; } public ChangeType update(ISCPMessage msg) { if (!(msg instanceof TimeInfoMsg) && !(msg instanceof JacketArtMsg)) { Logging.info(msg, "<< " + msg.toString()); if (msg.isMultiline()) { msg.logParameters(); } } else if (msg instanceof TimeInfoMsg && Logging.isTimeMsgEnabled()) { Logging.info(msg, "<< " + msg); } //Common if (msg instanceof PowerStatusMsg) { return isCommonChange(process((PowerStatusMsg) msg)); } if (msg instanceof FirmwareUpdateMsg) { return isCommonChange(process((FirmwareUpdateMsg) msg)); } if (msg instanceof ReceiverInformationMsg) { return process((ReceiverInformationMsg) msg, true) ? ChangeType.RECEIVER_INFO : ChangeType.NONE; } if (msg instanceof FriendlyNameMsg) { return isCommonChange(process((FriendlyNameMsg) msg)); } // Settings if (msg instanceof DimmerLevelMsg) { return isCommonChange(process((DimmerLevelMsg) msg)); } if (msg instanceof DigitalFilterMsg) { return isCommonChange(process((DigitalFilterMsg) msg)); } if (msg instanceof AudioMutingMsg) { return isCommonChange(process((AudioMutingMsg) msg)); } if (msg instanceof MusicOptimizerMsg) { return isCommonChange(process((MusicOptimizerMsg) msg)); } if (msg instanceof AutoPowerMsg) { return isCommonChange(process((AutoPowerMsg) msg)); } if (msg instanceof PhaseMatchingBassMsg) { return isCommonChange(process((PhaseMatchingBassMsg) msg)); } if (msg instanceof SleepSetCommandMsg) { return isCommonChange(process((SleepSetCommandMsg) msg)); } if (msg instanceof HdmiCecMsg) { return isCommonChange(process((HdmiCecMsg) msg)); } if (msg instanceof SpeakerACommandMsg) { return isCommonChange(process((SpeakerACommandMsg) msg)); } if (msg instanceof SpeakerBCommandMsg) { return isCommonChange(process((SpeakerBCommandMsg) msg)); } if (msg instanceof LateNightCommandMsg) { return isCommonChange(process((LateNightCommandMsg) msg)); } if (msg instanceof NetworkStandByMsg) { return isCommonChange(process((NetworkStandByMsg) msg)); } // Sound control if (msg instanceof ListeningModeMsg) { return process((ListeningModeMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } if (msg instanceof MasterVolumeMsg) { return process((MasterVolumeMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } if (msg instanceof DirectCommandMsg) { return process((DirectCommandMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } if (msg instanceof ToneCommandMsg) { return process((ToneCommandMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } if (msg instanceof SubwooferLevelCommandMsg) { return process((SubwooferLevelCommandMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } if (msg instanceof CenterLevelCommandMsg) { return process((CenterLevelCommandMsg) msg) ? ChangeType.AUDIO_CONTROL : ChangeType.NONE; } // Google cast if (msg instanceof GoogleCastVersionMsg) { return isCommonChange(process((GoogleCastVersionMsg) msg)); } if (msg instanceof GoogleCastAnalyticsMsg) { return isCommonChange(process((GoogleCastAnalyticsMsg) msg)); } if (msg instanceof PrivacyPolicyStatusMsg) { return isCommonChange(process((PrivacyPolicyStatusMsg) msg)); } // Track info if (msg instanceof JacketArtMsg) { return isCommonChange(process((JacketArtMsg) msg)); } if (msg instanceof AlbumNameMsg) { return isCommonChange(process((AlbumNameMsg) msg)); } if (msg instanceof ArtistNameMsg) { return isCommonChange(process((ArtistNameMsg) msg)); } if (msg instanceof TitleNameMsg) { return isCommonChange(process((TitleNameMsg) msg)); } if (msg instanceof FileFormatMsg) { return isCommonChange(process((FileFormatMsg) msg)); } if (msg instanceof TimeInfoMsg) { return process((TimeInfoMsg) msg) ? ChangeType.TIME_SEEK : ChangeType.NONE; } if (msg instanceof TrackInfoMsg) { return isCommonChange(process((TrackInfoMsg) msg)); } // Radio if (msg instanceof PresetCommandMsg) { return process((PresetCommandMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof TuningCommandMsg) { return isCommonChange(process((TuningCommandMsg) msg)); } if (msg instanceof RadioStationNameMsg) { return isCommonChange(process((RadioStationNameMsg) msg)); } // Playback if (msg instanceof PlayStatusMsg) { return isCommonChange(process((PlayStatusMsg) msg)); } if (msg instanceof MenuStatusMsg) { return isCommonChange(process((MenuStatusMsg) msg)); } // Navigation if (msg instanceof CustomPopupMsg) { return isCommonChange(process((CustomPopupMsg) msg)); } if (msg instanceof InputSelectorMsg) { return process((InputSelectorMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof ListTitleInfoMsg) { return process((ListTitleInfoMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof XmlListInfoMsg) { return process((XmlListInfoMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof ListInfoMsg) { return process((ListInfoMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } // Multiroom if (msg instanceof MultiroomDeviceInformationMsg) { return process((MultiroomDeviceInformationMsg) msg) ? ChangeType.MULTIROOM_INFO : ChangeType.NONE; } if (msg instanceof MultiroomChannelSettingMsg) { return isCommonChange(process((MultiroomChannelSettingMsg) msg)); } // Audio/Video information dialog if (msg instanceof AudioInformationMsg) { return isCommonChange(process((AudioInformationMsg) msg)); } if (msg instanceof VideoInformationMsg) { return isCommonChange(process((VideoInformationMsg) msg)); } // Denon-specific messages if (msg instanceof DcpReceiverInformationMsg) { return process((DcpReceiverInformationMsg) msg); } if (msg instanceof DcpTunerModeMsg) { return process((DcpTunerModeMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof DcpEcoModeMsg) { return isCommonChange(process((DcpEcoModeMsg) msg)); } if (msg instanceof DcpAudioRestorerMsg) { return isCommonChange(process((DcpAudioRestorerMsg) msg)); } if (msg instanceof DcpMediaContainerMsg) { return process((DcpMediaContainerMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } if (msg instanceof DcpMediaItemMsg) { return process((DcpMediaItemMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } else if (msg instanceof DcpSearchCriteriaMsg) { return process((DcpSearchCriteriaMsg) msg) ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } return ChangeType.NONE; } private ChangeType isCommonChange(boolean change) { return change ? ChangeType.COMMON : ChangeType.NONE; } private boolean process(PowerStatusMsg msg) { final boolean changed = msg.getPowerStatus() != powerStatus; powerStatus = msg.getPowerStatus(); if (changed && !isOn()) { clearItems(); } return changed; } private boolean process(FirmwareUpdateMsg msg) { final boolean changed = firmwareStatus != msg.getStatus(); firmwareStatus = msg.getStatus(); return changed; } boolean process(ReceiverInformationMsg msg, boolean showInfo) { if (SKIP_XML_MESSAGES) { return false; } try { msg.parseXml(showInfo); receiverInformation = msg.getData(); deviceProperties = msg.getDeviceProperties(); networkServices = msg.getNetworkServices(); zones = msg.getZones(); synchronized (deviceSelectors) { deviceSelectors.clear(); for (ReceiverInformationMsg.Selector s : msg.getDeviceSelectors()) { if (s.isActiveForZone(activeZone)) { deviceSelectors.add(s); } } } controlList = msg.getControlList(); toneControls = msg.getToneControls(); presetList = msg.getPresetList(); return true; } catch (Exception e) { Logging.info(msg, "Can not parse XML: " + e.getLocalizedMessage()); } return false; } public List<ReceiverInformationMsg.Selector> cloneDeviceSelectors() { synchronized (deviceSelectors) { return new ArrayList<>(deviceSelectors); } } private boolean process(FriendlyNameMsg msg) { multiroomNames.put(msg.getHostAndPort(), msg.getFriendlyName()); if (msg.fromHost(this)) { if (friendlyName == null) { friendlyName = ""; } final boolean changed = !friendlyName.equals(msg.getFriendlyName()); friendlyName = msg.getFriendlyName(); return changed; } return false; } private boolean process(InputSelectorMsg msg) { final boolean changed = inputType != msg.getInputType(); inputType = msg.getInputType(); if (isSimpleInput()) { Logging.info(msg, "New selector is not a media list. Clearing..."); clearTrackInfo(); serviceType = null; clearItems(); if (!isCdInput()) { timeSeek = MenuStatusMsg.TimeSeek.DISABLE; serviceIcon = ServiceType.UNKNOWN; } } return changed; } private boolean process(DimmerLevelMsg msg) { final boolean changed = dimmerLevel != msg.getLevel(); dimmerLevel = msg.getLevel(); return changed; } private boolean process(DigitalFilterMsg msg) { final boolean changed = digitalFilter != msg.getFilter(); digitalFilter = msg.getFilter(); return changed; } private boolean process(AudioMutingMsg msg) { final boolean changed = audioMuting != msg.getStatus(); audioMuting = msg.getStatus(); return changed; } private boolean process(ListeningModeMsg msg) { final boolean changed = listeningMode != msg.getMode(); listeningMode = msg.getMode(); return changed; } private boolean process(MasterVolumeMsg msg) { final boolean changed = volumeLevel != msg.getVolumeLevel(); volumeLevel = msg.getVolumeLevel(); return changed; } private boolean process(ToneCommandMsg msg) { final boolean changed = (msg.getBassLevel() != ToneCommandMsg.NO_LEVEL && bassLevel != msg.getBassLevel()) || (msg.getTrebleLevel() != ToneCommandMsg.NO_LEVEL && trebleLevel != msg.getTrebleLevel()); if (msg.isTonJoined()) { bassLevel = msg.getBassLevel(); trebleLevel = msg.getTrebleLevel(); } else { if (msg.getBassLevel() != ToneCommandMsg.NO_LEVEL) { bassLevel = msg.getBassLevel(); } if (msg.getTrebleLevel() != ToneCommandMsg.NO_LEVEL) { trebleLevel = msg.getTrebleLevel(); } } return changed; } private boolean process(SubwooferLevelCommandMsg msg) { final boolean changed = subwooferLevel != msg.getLevel(); if (msg.getLevel() != SubwooferLevelCommandMsg.NO_LEVEL) { // Do not overwrite a valid value with an invalid value subwooferLevel = msg.getLevel(); subwooferCmdLength = msg.getCmdLength(); } return changed; } private boolean process(CenterLevelCommandMsg msg) { final boolean changed = centerLevel != msg.getLevel(); if (msg.getLevel() != CenterLevelCommandMsg.NO_LEVEL) { // Do not overwrite a valid value with an invalid value centerLevel = msg.getLevel(); centerCmdLength = msg.getCmdLength(); } return changed; } private boolean process(PresetCommandMsg msg) { final boolean changed = preset != msg.getPreset(); preset = msg.getPreset(); return changed; } private boolean process(TuningCommandMsg msg) { final boolean changed = !msg.getFrequency().equals(frequency); if (inputType != InputSelectorMsg.InputType.DCP_TUNER) { frequency = msg.getFrequency(); if (!isDab()) { // For ISCP, station name is only available for DAB stationName = ""; } return changed; } else if (dcpTunerMode == msg.getDcpTunerMode()) { frequency = msg.getFrequency(); return changed; } return false; } private boolean process(RadioStationNameMsg msg) { final boolean changed = !msg.getData().equals(stationName); if (inputType != InputSelectorMsg.InputType.DCP_TUNER) { stationName = isDab() ? msg.getData() : ""; return changed; } else if (dcpTunerMode == msg.getDcpTunerMode()) { stationName = msg.getData(); return changed; } return false; } private boolean process(MusicOptimizerMsg msg) { final boolean changed = musicOptimizer != msg.getStatus(); musicOptimizer = msg.getStatus(); return changed; } private boolean process(AutoPowerMsg msg) { final boolean changed = autoPower != msg.getStatus(); autoPower = msg.getStatus(); return changed; } private boolean process(HdmiCecMsg msg) { final boolean changed = hdmiCec != msg.getStatus(); hdmiCec = msg.getStatus(); return changed; } private boolean process(DirectCommandMsg msg) { final boolean changed = toneDirect != msg.getStatus(); toneDirect = msg.getStatus(); return changed; } private boolean process(PhaseMatchingBassMsg msg) { final boolean changed = phaseMatchingBass != msg.getStatus(); phaseMatchingBass = msg.getStatus(); return changed; } private boolean process(SleepSetCommandMsg msg) { final boolean changed = sleepTime != msg.getSleepTime(); sleepTime = msg.getSleepTime(); return changed; } private boolean process(SpeakerACommandMsg msg) { final boolean changed = speakerA != msg.getStatus(); speakerA = msg.getStatus(); return changed; } private boolean process(SpeakerBCommandMsg msg) { final boolean changed = speakerB != msg.getStatus(); speakerB = msg.getStatus(); return changed; } private boolean process(LateNightCommandMsg msg) { final boolean changed = lateNightMode != msg.getStatus(); lateNightMode = msg.getStatus(); return changed; } private boolean process(NetworkStandByMsg msg) { final boolean changed = networkStandBy != msg.getStatus(); networkStandBy = msg.getStatus(); return changed; } private boolean process(GoogleCastVersionMsg msg) { final boolean changed = !msg.getData().equals(googleCastVersion); googleCastVersion = msg.getData(); return changed; } private boolean process(GoogleCastAnalyticsMsg msg) { final boolean changed = googleCastAnalytics != msg.getStatus(); googleCastAnalytics = msg.getStatus(); return changed; } private boolean process(PrivacyPolicyStatusMsg msg) { final boolean changed = !msg.getData().equals(privacyPolicy); privacyPolicy = msg.getData(); return changed; } private boolean process(JacketArtMsg msg) { if (msg.getImageType() == JacketArtMsg.ImageType.URL) { if (protoType == ConnectionIf.ProtoType.DCP && coverUrl != null && coverUrl.equals(msg.getUrl())) { Logging.info(msg, "Cover image already loaded, reload skipped"); return false; } Logging.info(msg, "<< " + msg); cover = msg.loadFromUrl(); coverUrl = msg.getUrl(); return true; } else if (msg.getRawData() != null) { final byte[] in = msg.getRawData(); if (msg.getPacketFlag() == JacketArtMsg.PacketFlag.START) { Logging.info(msg, "<< " + msg); coverBuffer = new ByteArrayOutputStream(); } if (coverBuffer != null) { coverBuffer.write(in, 0, in.length); } if (msg.getPacketFlag() == JacketArtMsg.PacketFlag.END) { Logging.info(msg, "<< " + msg); cover = msg.loadFromBuffer(coverBuffer); coverBuffer = null; return true; } } else { Logging.info(msg, "<< " + msg); } return false; } private boolean process(AlbumNameMsg msg) { final boolean changed = !msg.getData().equals(album); album = msg.getData(); return changed; } private boolean process(ArtistNameMsg msg) { final boolean changed = !msg.getData().equals(artist); artist = msg.getData(); return changed; } private boolean process(TitleNameMsg msg) { final boolean changed = !msg.getData().equals(title); title = msg.getData(); return changed; } private boolean process(TimeInfoMsg msg) { final boolean changed = !msg.getCurrentTime().equals(currentTime) || !msg.getMaxTime().equals(maxTime); currentTime = msg.getCurrentTime(); maxTime = msg.getMaxTime(); return changed; } private boolean process(TrackInfoMsg msg) { final boolean changed = !isEqual(currentTrack, msg.getCurrentTrack()) || !isEqual(maxTrack, msg.getMaxTrack()); currentTrack = msg.getCurrentTrack(); maxTrack = msg.getMaxTrack(); return changed; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isEqual(Integer a, Integer b) { if (a == null && b == null) { return true; } //noinspection ConstantConditions if ((a == null && b != null) || (a != null && b == null)) { return false; } return a.equals(b); } private boolean process(FileFormatMsg msg) { final boolean changed = !msg.getFullFormat().equals(fileFormat); fileFormat = msg.getFullFormat(); return changed; } private boolean process(PlayStatusMsg msg) { boolean changed; switch (msg.getUpdateType()) { case ALL: changed = msg.getPlayStatus() != playStatus || msg.getRepeatStatus() != repeatStatus || msg.getShuffleStatus() != shuffleStatus; playStatus = msg.getPlayStatus(); repeatStatus = msg.getRepeatStatus(); shuffleStatus = msg.getShuffleStatus(); return changed; case PLAY_STATE: changed = msg.getPlayStatus() != playStatus; playStatus = msg.getPlayStatus(); return changed; case PLAY_MODE: changed = msg.getRepeatStatus() != repeatStatus || msg.getShuffleStatus() != shuffleStatus; repeatStatus = msg.getRepeatStatus(); shuffleStatus = msg.getShuffleStatus(); return changed; case REPEAT: changed = msg.getRepeatStatus() != repeatStatus; repeatStatus = msg.getRepeatStatus(); return changed; case SHUFFLE: changed = msg.getShuffleStatus() != shuffleStatus; shuffleStatus = msg.getShuffleStatus(); return changed; } return false; } private boolean process(MenuStatusMsg msg) { final boolean changed = timeSeek != msg.getTimeSeek() || trackMenu != msg.getTrackMenu() || serviceIcon != msg.getServiceIcon() || positiveFeed != msg.getPositiveFeed() || negativeFeed != msg.getNegativeFeed(); timeSeek = msg.getTimeSeek(); trackMenu = msg.getTrackMenu(); serviceIcon = msg.getServiceIcon(); positiveFeed = msg.getPositiveFeed(); negativeFeed = msg.getNegativeFeed(); return changed; } private boolean process(ListTitleInfoMsg msg) { boolean changed = false; if (serviceType != msg.getServiceType()) { serviceType = msg.getServiceType(); clearItems(); changed = true; } if (layerInfo != msg.getLayerInfo()) { layerInfo = msg.getLayerInfo(); changed = true; } if (uiType != msg.getUiType()) { uiType = msg.getUiType(); clearItems(); if (!isPopupMode()) { popup.set(null); } changed = true; } if (!titleBar.equals(msg.getTitleBar())) { titleBar = msg.getTitleBar(); changed = true; } if (currentCursorPosition != msg.getCurrentCursorPosition()) { currentCursorPosition = msg.getCurrentCursorPosition(); changed = true; } if (numberOfLayers != msg.getNumberOfLayers()) { numberOfLayers = msg.getNumberOfLayers(); changed = true; } if (numberOfItems != msg.getNumberOfItems()) { numberOfItems = msg.getNumberOfItems(); changed = true; } // Update path items if (layerInfo != ListTitleInfoMsg.LayerInfo.UNDER_2ND_LAYER) { pathItems.clear(); pathIndexOffset = numberOfLayers; } // Issue #233: For some receivers like TX-8130, the LAYERS value for the top of service is 0 instead 1. // Therefore, we shift it by one in this case final int pathIndex = numberOfLayers + 1 - pathIndexOffset; for (int i = pathItems.size(); i < pathIndex; i++) { pathItems.add(""); } if (uiType != ListTitleInfoMsg.UIType.PLAYBACK) { if (pathIndex > 0) { pathItems.set(pathIndex - 1, titleBar); while (pathItems.size() > pathIndex) { pathItems.remove(pathItems.size() - 1); } } Logging.info(this, "media list path = " + pathItems + "(offset = " + pathIndexOffset + ")"); } return changed; } private void clearItems() { synchronized (mediaItems) { mediaItems.clear(); } synchronized (serviceItems) { serviceItems.clear(); } } public List<XmlListItemMsg> cloneMediaItems() { synchronized (mediaItems) { return new ArrayList<>(mediaItems); } } private boolean process(XmlListInfoMsg msg) { if (SKIP_XML_MESSAGES) { return false; } synchronized (mediaItems) { if (isSimpleInput()) { mediaItems.clear(); Logging.info(msg, "skipped: input channel " + inputType.toString() + " is not a media list"); return true; } if (isPopupMode()) { clearItems(); Logging.info(msg, "skipped: it is a POPUP message"); return true; } try { Logging.info(msg, "processing XmlListInfoMsg"); msg.parseXml(mediaItems, numberOfLayers); if (serviceType == ServiceType.PLAYQUEUE && (currentTrack == null || maxTrack == null)) { trackInfoFromList(mediaItems); } return true; } catch (Exception e) { mediaItems.clear(); Logging.info(msg, "Can not parse XML: " + e.getLocalizedMessage()); } } return false; } private void trackInfoFromList(final List<XmlListItemMsg> list) { for (int i = 0; i < list.size(); i++) { final XmlListItemMsg m = list.get(i); if (m.getIcon() == XmlListItemMsg.Icon.PLAY) { currentTrack = i + 1; maxTrack = list.size(); return; } } } public List<NetworkServiceMsg> cloneServiceItems() { synchronized (serviceItems) { return new ArrayList<>(serviceItems); } } private boolean process(ListInfoMsg msg) { if (!isOn()) { // Some receivers send this message before receiver information and power status. // In such cases, just ignore it return false; } if (msg.getInformationType() == ListInfoMsg.InformationType.CURSOR) { // #167: if receiver does not support XML, clear list items here if (!isReceiverInformation() && msg.getUpdateType() == ListInfoMsg.UpdateType.PAGE) { // only clear if cursor is not changed clearItems(); } listInfoItems.clear(); return false; } if (serviceType == ServiceType.NET && isTopLayer()) { synchronized (serviceItems) { // Since the names in ListInfoMsg and ReceiverInformationMsg are // not consistent for some services (see https://github.com/mkulesh/onpc/issues/35) // we just clone here networkServices provided by ReceiverInformationMsg // into serviceItems list by any NET ListInfoMsg (is ReceiverInformationMsg exists) if (!networkServices.isEmpty()) { createServiceItems(); } else // fallback: parse listData from ListInfoMsg { for (NetworkServiceMsg i : serviceItems) { if (i.getService().getName().equalsIgnoreCase(msg.getListedData())) { return false; } } final NetworkServiceMsg nsMsg = new NetworkServiceMsg(msg.getListedData()); if (nsMsg.getService() != ServiceType.UNKNOWN) { serviceItems.add(nsMsg); } } } return !serviceItems.isEmpty(); } else if (isMenuMode() || !isReceiverInformation()) { synchronized (mediaItems) { for (XmlListItemMsg i : mediaItems) { if (i.getTitle().equalsIgnoreCase(msg.getListedData())) { return false; } } final ListInfoMsg cmdMessage = new ListInfoMsg(msg.getLineInfo(), msg.getListedData()); final XmlListItemMsg nsMsg = new XmlListItemMsg( msg.getLineInfo(), 0, msg.getListedData(), XmlListItemMsg.Icon.UNKNOWN, true, cmdMessage); if (nsMsg.getMessageId() < mediaItems.size()) { mediaItems.set(nsMsg.getMessageId(), nsMsg); } else { mediaItems.add(nsMsg); } } return true; } else if (isUsb()) { final String name = msg.getListedData(); if (!listInfoItems.contains(name)) { listInfoItems.add(name); } return false; } return false; } public void createServiceItems() { serviceItems.clear(); for (final String code : networkServices.keySet()) { final ServiceType service = (ServiceType) ISCPMessage.searchParameter(code, ServiceType.values(), ServiceType.UNKNOWN); if (service != ServiceType.UNKNOWN) { serviceItems.add(new NetworkServiceMsg(service)); } } } private boolean process(CustomPopupMsg msg) { popup.set(msg); return msg != null; } public ReceiverInformationMsg.Selector getActualSelector() { synchronized (deviceSelectors) { for (ReceiverInformationMsg.Selector s : deviceSelectors) { if (s.getId().equals(inputType.getCode())) { return s; } } } return null; } public boolean isFm() { return inputType == InputSelectorMsg.InputType.FM || (inputType == InputSelectorMsg.InputType.DCP_TUNER && dcpTunerMode == DcpTunerModeMsg.TunerMode.FM); } public boolean isDab() { return inputType == InputSelectorMsg.InputType.DAB || (inputType == InputSelectorMsg.InputType.DCP_TUNER && dcpTunerMode == DcpTunerModeMsg.TunerMode.DAB); } public boolean isRadioInput() { return isFm() || isDab() || inputType == InputSelectorMsg.InputType.AM; } public int nextEmptyPreset() { for (ReceiverInformationMsg.Preset p : presetList) { if (p.isEmpty()) { return p.getId(); } } return presetList.size() + 1; } /** * Simple inputs do not have time, cover, or media items * * @return boolean */ public boolean isSimpleInput() { return inputType != InputSelectorMsg.InputType.NONE && !inputType.isMediaList(); } public boolean isUsb() { return serviceType == ServiceType.USB_FRONT || serviceType == ServiceType.USB_REAR; } public boolean isTopLayer() { if (isSimpleInput()) { // Single inputs are always on top level return true; } if (!isPlaybackMode()) { if (protoType == ConnectionIf.ProtoType.DCP && inputType == InputSelectorMsg.InputType.DCP_NET) { return layerInfo == ListTitleInfoMsg.LayerInfo.NET_TOP; } if (serviceType == ServiceType.NET && layerInfo == ListTitleInfoMsg.LayerInfo.NET_TOP) { return true; } if (layerInfo == ListTitleInfoMsg.LayerInfo.SERVICE_TOP) { return isUsb() || serviceType == ServiceType.UNKNOWN; } } return false; } public boolean isMediaEmpty() { return mediaItems.isEmpty() && serviceItems.isEmpty(); } boolean listInfoConsistent() { if (numberOfItems == 0 || numberOfLayers == 0 || listInfoItems.isEmpty()) { return true; } synchronized (mediaItems) { for (String s : listInfoItems) { for (XmlListItemMsg i : mediaItems) { if (i.getTitle().equalsIgnoreCase(s)) { return true; } } } } return false; } @SuppressLint("SetTextI18n") public static String getVolumeLevelStr(int volumeLevel, ReceiverInformationMsg.Zone zone) { if (zone != null && zone.getVolumeStep() == 0) { final float f = (float) volumeLevel / 2.0f; final DecimalFormat df = Utils.getDecimalFormat("0.0"); return df.format(f); } else { return Integer.toString(volumeLevel, 10); } } public ReceiverInformationMsg.Preset searchPreset() { for (ReceiverInformationMsg.Preset p : presetList) { if (p.getId() == preset) { return p; } } return null; } public String getTrackInfo(final Context context) { final StringBuilder str = new StringBuilder(); final String dashedString = context.getString(R.string.dashed_string); if (isRadioInput()) { str.append(preset != PresetCommandMsg.NO_PRESET ? Integer.toString(preset) : dashedString); str.append("/"); str.append(!presetList.isEmpty() ? Integer.toString(presetList.size()) : dashedString); } else if (protoType == ConnectionIf.ProtoType.ISCP) { str.append(currentTrack != null ? Integer.toString(currentTrack) : dashedString); str.append("/"); str.append(maxTrack != null ? Integer.toString(maxTrack) : dashedString); } return str.toString(); } @NonNull public String getFrequencyInfo(final Context context) { final String dashedString = context.getString(R.string.dashed_string); if (frequency == null) { return dashedString; } if (isFm()) { try { final float f = (float) Integer.parseInt(frequency) / 100.0f; final DecimalFormat df = Utils.getDecimalFormat("0.00 MHz"); return df.format(f); } catch (Exception e) { return dashedString; } } if (isDab()) { final String freq1 = !frequency.contains(":") && frequency.length() > 2 ? frequency.substring(0, 2) + ":" + frequency.substring(2) : frequency; return !freq1.isEmpty() && !freq1.contains("MHz") ? freq1 + "MHz" : freq1; } return frequency; } public ReceiverInformationMsg.NetworkService getNetworkService() { if (serviceType != null) { return networkServices.get(serviceType.getCode()); } return null; } private boolean process(MultiroomDeviceInformationMsg msg) { try { msg.parseXml(true); final String id = msg.getProperty("deviceid"); if (!id.isEmpty()) { multiroomLayout.put(id, msg); } if (!msg.fromHost(this)) { Logging.info(msg, "Multiroom device information for another host"); } else { multiroomDeviceId = id; multiroomChannel = getMultiroomChannelType(); } return true; } catch (Exception e) { Logging.info(msg, "Can not parse XML: " + e.getLocalizedMessage()); } return false; } public boolean isMasterDevice() { final MultiroomDeviceInformationMsg msg = multiroomLayout.get(multiroomDeviceId); final MultiroomDeviceInformationMsg.RoleType role = (msg == null) ? MultiroomDeviceInformationMsg.RoleType.NONE : msg.getRole(getActiveZone() + 1); return role == MultiroomDeviceInformationMsg.RoleType.SRC; } private MultiroomDeviceInformationMsg.ChannelType getMultiroomChannelType() { final MultiroomDeviceInformationMsg msg = multiroomLayout.get(multiroomDeviceId); return (msg == null) ? MultiroomDeviceInformationMsg.ChannelType.NONE : msg.getChannelType(getActiveZone() + 1); } public int getMultiroomGroupId() { final MultiroomDeviceInformationMsg msg = multiroomLayout.get(multiroomDeviceId); return (msg == null) ? MultiroomDeviceInformationMsg.NO_GROUP : msg.getGroupId(getActiveZone() + 1); } private boolean process(MultiroomChannelSettingMsg msg) { final boolean changed = multiroomChannel != msg.getChannelType(); multiroomChannel = msg.getChannelType(); return changed; } @DrawableRes public int getServiceIcon() { @DrawableRes int serviceIcon = isPlaying() ? this.serviceIcon.getImageId() : (this.serviceType != null ? this.serviceType.getImageId() : R.drawable.media_item_unknown); if (serviceIcon == R.drawable.media_item_unknown) { serviceIcon = inputType.getImageId(); if (inputType == InputSelectorMsg.InputType.DCP_TUNER && dcpTunerMode != DcpTunerModeMsg.TunerMode.NONE) { // Special icon for Denon tuner input serviceIcon = dcpTunerMode.getImageId(); } } return serviceIcon; } public SoundControlType soundControlType(final String config, ReceiverInformationMsg.Zone zone) { switch (config) { case "auto": return (zone != null && zone.getVolMax() == 0) ? SoundControlType.RI_AMP : SoundControlType.DEVICE_SLIDER; case "device": return SoundControlType.DEVICE_BUTTONS; case "device-slider": return SoundControlType.DEVICE_SLIDER; case "device-btn-slider": return SoundControlType.DEVICE_BTN_AROUND_SLIDER; case "device-btn-above-slider": return SoundControlType.DEVICE_BTN_ABOVE_SLIDER; case "external-amplifier": return SoundControlType.RI_AMP; default: return SoundControlType.NONE; } } public boolean isCdInput() { return (inputType == InputSelectorMsg.InputType.CD) && (isControlExists(CdPlayerOperationCommandMsg.CONTROL_CD_INT1) || isControlExists(CdPlayerOperationCommandMsg.CONTROL_CD_INT2)); } public boolean isShortcutPossible() { final boolean isMediaList = numberOfLayers > 0 && titleBar != null && !titleBar.isEmpty() && serviceType != null; Logging.info(this, "Shortcut parameters: numberOfLayers=" + numberOfLayers + ", titleBar=" + titleBar + ", serviceType=" + serviceType + ", isMediaList=" + isMediaList); return !SKIP_XML_MESSAGES && (isMediaList || isSimpleInput()); } public boolean isPathItemsConsistent() { for (int i = 1; i < pathItems.size(); i++) { if (pathItems.get(i) == null || pathItems.get(i).isEmpty()) { return false; } } return true; } private boolean process(AudioInformationMsg msg) { final boolean changed = !avInfoAudioInput.equals(msg.audioInput) || !avInfoAudioOutput.equals(msg.audioOutput); avInfoAudioInput = msg.audioInput; avInfoAudioOutput = msg.audioOutput; return changed; } private boolean process(VideoInformationMsg msg) { final boolean changed = !avInfoVideoInput.equals(msg.videoInput) || !avInfoVideoOutput.equals(msg.videoOutput); avInfoVideoInput = msg.videoInput; avInfoVideoOutput = msg.videoOutput; return changed; } // Denon-specific messages private ChangeType process(DcpReceiverInformationMsg msg) { // Input Selector if (msg.updateType == DcpReceiverInformationMsg.UpdateType.SELECTOR && msg.getSelector() != null) { ChangeType changed = ChangeType.NONE; synchronized (deviceSelectors) { ReceiverInformationMsg.Selector oldSelector = null; for (ReceiverInformationMsg.Selector s : deviceSelectors) { if (s.getId().equals(msg.getSelector().getId())) { oldSelector = s; break; } } if (oldSelector == null) { Logging.info(this, " Received friendly name for not configured selector. Ignored."); } else { final ReceiverInformationMsg.Selector newSelector = new ReceiverInformationMsg.Selector( oldSelector, msg.getSelector().getName()); Logging.info(this, " DCP selector " + newSelector); deviceSelectors.remove(oldSelector); deviceSelectors.add(newSelector); changed = ChangeType.MEDIA_ITEMS; } } return changed; } // Max. volume if (msg.updateType == DcpReceiverInformationMsg.UpdateType.MAX_VOLUME && msg.getMaxVolumeZone() != null) { ChangeType changed = ChangeType.NONE; for (int i = 0; i < zones.size(); i++) { if (zones.get(i).getVolMax() != msg.getMaxVolumeZone().getVolMax()) { zones.get(i).setVolMax(msg.getMaxVolumeZone().getVolMax()); Logging.info(this, " DCP zone " + zones.get(i)); changed = ChangeType.COMMON; } } return changed; } // Tone control final ReceiverInformationMsg.ToneControl toneControl = msg.getToneControl(); if (msg.updateType == DcpReceiverInformationMsg.UpdateType.TONE_CONTROL && toneControl != null) { boolean changed = !toneControl.equals(toneControls.get(toneControl.getId())); toneControls.put(toneControl.getId(), toneControl); Logging.info(this, " DCP tone control " + toneControl); return changed ? ChangeType.COMMON : ChangeType.NONE; } // Radio presets final ReceiverInformationMsg.Preset preset = msg.getPreset(); if (msg.updateType == DcpReceiverInformationMsg.UpdateType.PRESET && preset != null) { boolean changed = false; int oldPresetIdx = -1; for (int i = 0; i < presetList.size(); i++) { if (presetList.get(i).getId() == preset.getId()) { oldPresetIdx = i; break; } } if (oldPresetIdx >= 0) { changed = !preset.equals(presetList.get(oldPresetIdx)); presetList.set(oldPresetIdx, preset); Logging.info(this, " DCP Preset " + preset); } else if (presetList.isEmpty() || !preset.equals(presetList.get(presetList.size() - 1))) { changed = true; presetList.add(preset); Logging.info(this, " DCP Preset " + preset); } return changed ? ChangeType.MEDIA_ITEMS : ChangeType.NONE; } // Network services if (msg.updateType == DcpReceiverInformationMsg.UpdateType.NETWORK_SERVICES) { if (networkServices.isEmpty()) { Logging.info(this, " Updating network services: " + networkServices.size()); networkServices = msg.getNetworkServices(); return ChangeType.RECEIVER_INFO; } else { Logging.info(this, " Set network top layer: " + networkServices.size()); clearItems(); setDcpNetTopLayer(); return ChangeType.MEDIA_ITEMS; } } // Firmware version if (msg.updateType == DcpReceiverInformationMsg.UpdateType.FIRMWARE_VER && msg.getFirmwareVer() != null) { deviceProperties.put("firmwareversion", msg.getFirmwareVer()); Logging.info(this, " DCP firmware " + msg.getFirmwareVer()); return ChangeType.COMMON; } return ChangeType.NONE; } private boolean process(DcpTunerModeMsg msg) { final boolean changed = dcpTunerMode != msg.getTunerMode(); dcpTunerMode = msg.getTunerMode(); return changed; } private boolean process(DcpEcoModeMsg msg) { final boolean changed = dcpEcoMode != msg.getStatus(); dcpEcoMode = msg.getStatus(); return changed; } private boolean process(DcpAudioRestorerMsg msg) { final boolean changed = dcpAudioRestorer != msg.getStatus(); dcpAudioRestorer = msg.getStatus(); return changed; } private boolean process(DcpMediaContainerMsg msg) { synchronized (mediaItems) { // Media items if (msg.getStart() == 0) { mediaItems.clear(); // Media path final List<DcpMediaContainerMsg> tmpPath = new ArrayList<>(); for (DcpMediaContainerMsg pe : dcpMediaPath) { if (pe.keyEqual(msg)) { break; } tmpPath.add(pe); } tmpPath.add(new DcpMediaContainerMsg(msg)); dcpMediaPath.clear(); dcpMediaPath.addAll(tmpPath); Logging.info(this, "Dcp media path: " + dcpMediaPath); // Info serviceType = (ServiceType) ISCPMessage.searchDcpParameter( "HS" + msg.getSid(), ServiceType.values(), ServiceType.UNKNOWN); layerInfo = msg.getLayerInfo(); uiType = ListTitleInfoMsg.UIType.LIST; numberOfLayers = dcpMediaPath.size(); mediaListSid = msg.getSid(); mediaListCid = msg.getCid(); if (layerInfo == ListTitleInfoMsg.LayerInfo.SERVICE_TOP && serviceType != ServiceType.UNKNOWN) { titleBar = serviceType.getName(); } else if (msg.getBrowseType() == DcpMediaContainerMsg.BrowseType.SEARCH_RESULT && !msg.getSearchStr().isEmpty()) { titleBar = msg.getSearchStr(); } else if (!dcpMediaPath.isEmpty() && dcpMediaPath.size() >= 2) { titleBar = dcpMediaPath.get(dcpMediaPath.size() - 2).getItems().get(0).getTitle(); } else { titleBar = ""; } } else if (!msg.getCid().equals(mediaListCid)) { return false; } mediaItems.addAll(msg.getItems()); Collections.sort(mediaItems, (lhs, rhs) -> { int val = lhs.getIconType().compareTo(rhs.getIconType()); if (val == 0) { return lhs.getIcon().isSong() && rhs.getIcon().isSong() ? Integer.compare(lhs.getMessageId(), rhs.getMessageId()) : lhs.getTitle().compareTo(rhs.getTitle()); } return val; }); numberOfItems = mediaItems.size(); setDcpPlayingItem(); } synchronized (dcpTrackMenuItems) { dcpTrackMenuItems.clear(); dcpTrackMenuItems.addAll(msg.getOptions()); for (XmlListItemMsg m : dcpTrackMenuItems) { Logging.info(this, "DCP menu: " + m.toString()); } } return true; } public List<XmlListItemMsg> cloneDcpTrackMenuItems(final DcpMediaContainerMsg dcpItem) { synchronized (dcpTrackMenuItems) { List<XmlListItemMsg> retValue = new ArrayList<>(dcpTrackMenuItems); if (dcpItem != null) { for (XmlListItemMsg msg : retValue) { final DcpMediaContainerMsg newItem = new DcpMediaContainerMsg(dcpItem); newItem.setAid(DcpMediaContainerMsg.HEOS_SET_SERVICE_OPTION); newItem.setStart(msg.messageId); msg.setCmdMessage(newItem); } } return retValue; } } public void setDcpNetTopLayer() { layerInfo = ListTitleInfoMsg.LayerInfo.NET_TOP; synchronized (mediaItems) { mediaItems.clear(); } createServiceItems(); numberOfItems = serviceItems.size(); mediaListSid = ""; dcpMediaPath.clear(); } private boolean process(DcpMediaItemMsg msg) { ServiceType si = (ServiceType) ISCPMessage.searchDcpParameter( "HS" + msg.getSid(), ServiceType.values(), ServiceType.UNKNOWN); final boolean changed = !msg.getData().equals(mediaListMid) || si != serviceIcon; mediaListMid = msg.getData(); serviceIcon = si; timeSeek = MenuStatusMsg.TimeSeek.DISABLE; if (changed) { synchronized (mediaItems) { setDcpPlayingItem(); } } return changed; } private boolean process(DcpSearchCriteriaMsg msg) { dcpSearchCriteria.put(msg.getSid(), msg.getCriteria()); for (Map.Entry<String, List<Pair<String, Integer>>> entry : dcpSearchCriteria.entrySet()) { Logging.info(this, "DCP search criteria: sid=" + entry.getKey() + ", value=" + entry.getValue()); } return true; } @Nullable public List<Pair<String, Integer>> getDcpSearchCriteria() { if (isOn() && protoType == State.ProtoType.DCP && inputType == InputSelectorMsg.InputType.DCP_NET) { final List<Pair<String, Integer>> sc = dcpSearchCriteria.get(mediaListSid); return sc != null && !sc.isEmpty() ? sc : null; } return null; } public void storeSelectedDcpItem(XmlListItemMsg rowMsg) { if (!dcpMediaPath.isEmpty()) { final DcpMediaContainerMsg last = dcpMediaPath.get(dcpMediaPath.size() - 1); last.getItems().clear(); last.getItems().add(rowMsg); Logging.info(this, "Stored selected DCP item: " + rowMsg.toString() + " in container " + last); } } private void setDcpPlayingItem() { for (XmlListItemMsg msg : mediaItems) { if (msg.getCmdMessage() instanceof DcpMediaContainerMsg) { final DcpMediaContainerMsg mc = (DcpMediaContainerMsg) msg.getCmdMessage(); if (mc.getType().equals("heos_server")) { msg.setIcon(XmlListItemMsg.Icon.HEOS_SERVER); } else if (!mc.isContainer() && mc.isPlayable() && !mediaListMid.isEmpty()) { msg.setIcon(mediaListMid.equals(mc.getMid()) ? XmlListItemMsg.Icon.PLAY : XmlListItemMsg.Icon.MUSIC); } } } } }
72,218
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
StateHolder.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/StateHolder.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import com.mkulesh.onpc.utils.Logging; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class StateHolder { private StateManager stateManager = null; private final AtomicBoolean released = new AtomicBoolean(); private boolean appExit = false; public StateHolder() { released.set(true); } public void setStateManager(StateManager stateManager) { this.stateManager = stateManager; synchronized (released) { released.set(stateManager == null); } } public StateManager getStateManager() { return stateManager; } public State getState() { return stateManager == null ? null : stateManager.getState(); } public void release(boolean appExit, String reason) { this.appExit = appExit; synchronized (released) { if (stateManager != null) { Logging.info(this, "request to release state holder (" + reason + ")"); released.set(false); // state manager may be set to null in setStateManager during the setting // "released" to false if (stateManager != null) { stateManager.stop(); } } else { released.set(true); } } } public void waitForRelease() { while (true) { synchronized (released) { if (released.get()) { Logging.info(this, "state holder released"); return; } } try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { // nothing to do } } } public boolean isAppExit() { return appExit; } }
2,739
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
PopupBuilder.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/PopupBuilder.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.mkulesh.onpc.R; import com.mkulesh.onpc.iscp.messages.CustomPopupMsg; import com.mkulesh.onpc.iscp.messages.ServiceType; import com.mkulesh.onpc.utils.Logging; import com.mkulesh.onpc.utils.Utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatButton; import androidx.appcompat.widget.AppCompatEditText; public class PopupBuilder { public interface ButtonListener { void onButtonSelected(final CustomPopupMsg outMsg); } private final Context context; private final ServiceType serviceType; private final String artist; private final ButtonListener buttonListener; @DrawableRes private final int serviceIcon; public PopupBuilder(final @NonNull Context context, final @NonNull State state, final @NonNull ButtonListener buttonListener) { this.context = context; this.serviceType = state.serviceType; this.artist = state.artist; this.buttonListener = buttonListener; this.serviceIcon = state.getServiceIcon(); } public AlertDialog build(final CustomPopupMsg pMsg) throws Exception { CustomPopupMsg.UiType uiType = null; final Document document = xmlToDocument(pMsg.getXml().getBytes(Utils.UTF_8)); final Element popup = Utils.getElement(document, "popup"); if (popup == null) { throw new Exception("popup element not found"); } final String title = popup.getAttribute("title"); Logging.info(this, "received popup: " + title); final FrameLayout frameView = new FrameLayout(context); AlertDialog.Builder builder = new AlertDialog.Builder(context) .setTitle(title) .setView(frameView); // icon if (serviceIcon != R.drawable.media_item_unknown) { final Drawable bg = Utils.getDrawable(context, serviceIcon); Utils.setDrawableColorAttr(context, bg, android.R.attr.textColorSecondary); builder.setIcon(bg); } // dialog layout final AlertDialog alertDialog = builder.create(); LayoutInflater inflater = alertDialog.getLayoutInflater(); FrameLayout dialogFrame = (FrameLayout) inflater.inflate(R.layout.dialog_popup_layout, frameView); if (dialogFrame.getChildCount() != 1) { throw new Exception("cannot inflate dialog layout"); } LinearLayout dialogLayout = (LinearLayout) dialogFrame.getChildAt(0); // labels final StringBuilder message = new StringBuilder(); message.append(title).append(": "); for (final Element label : Utils.getElements(popup, "label")) { for (final Element line : Utils.getElements(label, "line")) { message.append(line.getAttribute("text")); dialogLayout.addView(createTextView(line, R.style.PrimaryTextViewStyle)); } } // text boxes for (final Element group : Utils.getElements(popup, "textboxgroup")) { for (final Element textBox : Utils.getElements(group, "textbox")) { dialogLayout.addView(createTextView(textBox, R.style.SecondaryTextViewStyle)); dialogLayout.addView(createEditText(textBox)); uiType = CustomPopupMsg.UiType.KEYBOARD; } } // buttons for (final Element group : Utils.getElements(popup, "buttongroup")) { for (final Element button : Utils.getElements(group, "button")) { if (uiType == null) { uiType = CustomPopupMsg.UiType.POPUP; } dialogLayout.addView(createButton(alertDialog, document, button, uiType)); } } // Show toast instead dialog, if there are no buttons and fields if (uiType == null) { Toast.makeText(context, message.toString(), Toast.LENGTH_LONG).show(); return null; } return alertDialog; } @SuppressLint("NewApi") private TextView createTextView(final Element textBox, final int style) { final TextView tv = new TextView(context); tv.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { tv.setTextAppearance(style); } else { tv.setTextAppearance(context, style); } tv.setText(textBox.getAttribute("text")); return tv; } private AppCompatEditText createEditText(final Element box) { final AppCompatEditText tv = new AppCompatEditText(context); tv.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); final String defValue = getDefaultValue(box); if (defValue != null) { tv.setText(defValue); box.setAttribute("value", defValue); } else { tv.setText(box.getAttribute("value")); } tv.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) { box.setAttribute("value", s.toString()); } @Override public void afterTextChanged(Editable s) { } }); return tv; } private String getDefaultValue(Element box) { final String text = box.getAttribute("text"); if (serviceType == ServiceType.DEEZER && "Search".equals(text) && artist != null && !artist.isEmpty()) { return artist.contains("(") ? artist.substring(0, artist.indexOf("(")) : artist; } return null; } private AppCompatButton createButton(final AlertDialog alertDialog, final Document document, final Element button, final CustomPopupMsg.UiType uiType) { final AppCompatButton b = new AppCompatButton(context); b.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); b.setGravity(Gravity.CENTER); b.setText(button.getAttribute("text")); b.setOnClickListener(v -> { Utils.showSoftKeyboard(context, v, false); button.setAttribute("selected", "true"); alertDialog.dismiss(); final CustomPopupMsg outMsg = new CustomPopupMsg(uiType, documentToXml(document)); buttonListener.onButtonSelected(outMsg); }); return b; } private Document xmlToDocument(byte[] bytes) throws Exception { InputStream stream = new ByteArrayInputStream(bytes); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(stream); stream.close(); return document; } private static String documentToXml(final Document document) { try { DOMSource domSource = new DOMSource(document); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (Exception e) { Logging.info(document, "Can not generate popup response: " + e.getLocalizedMessage()); return null; } } }
9,871
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z
ZonedMessage.java
/FileExtraction/Java_unseen/mkulesh_onpc/app/src/main/java/com/mkulesh/onpc/iscp/ZonedMessage.java
/* * Enhanced Music Controller * Copyright (C) 2018-2023 by Mikhail Kulesh * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. You should have received a copy of the GNU General * Public License along with this program. */ package com.mkulesh.onpc.iscp; public abstract class ZonedMessage extends ISCPMessage { protected int zoneIndex; protected ZonedMessage(EISCPMessage raw, final String[] zoneCommands) throws Exception { super(raw); for (int i = 0; i < zoneCommands.length; i++) { if (zoneCommands[i].equalsIgnoreCase(raw.getCode())) { zoneIndex = i; return; } } throw new Exception("No zone defined for message " + raw.getCode()); } @SuppressWarnings("SameParameterValue") protected ZonedMessage(final int messageId, final String data, int zoneIndex) { super(messageId, data); this.zoneIndex = zoneIndex; } @SuppressWarnings("unused") abstract public String getZoneCommand(); }
1,501
Java
.java
mkulesh/onpc
122
22
8
2018-10-13T13:24:13Z
2024-05-05T19:04:17Z