Search in sources :

Example 21 with PersistableBundleCompat

use of com.evernote.android.job.util.support.PersistableBundleCompat in project android by nextcloud.

the class NotificationJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    Context context = getContext();
    PersistableBundleCompat persistableBundleCompat = getParams().getExtras();
    String subject = persistableBundleCompat.getString(KEY_NOTIFICATION_SUBJECT, "");
    String signature = persistableBundleCompat.getString(KEY_NOTIFICATION_SIGNATURE, "");
    if (!TextUtils.isEmpty(subject) && !TextUtils.isEmpty(signature)) {
        try {
            byte[] base64DecodedSubject = Base64.decode(subject, Base64.DEFAULT);
            byte[] base64DecodedSignature = Base64.decode(signature, Base64.DEFAULT);
            PushUtils pushUtils = new PushUtils();
            PrivateKey privateKey = (PrivateKey) PushUtils.readKeyFromFile(false);
            try {
                SignatureVerification signatureVerification = pushUtils.verifySignature(context, base64DecodedSignature, base64DecodedSubject);
                if (signatureVerification.isSignatureValid()) {
                    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
                    cipher.init(Cipher.DECRYPT_MODE, privateKey);
                    byte[] decryptedSubject = cipher.doFinal(base64DecodedSubject);
                    Gson gson = new Gson();
                    DecryptedPushMessage decryptedPushMessage = gson.fromJson(new String(decryptedSubject), DecryptedPushMessage.class);
                    // We ignore Spreed messages for now
                    if (!decryptedPushMessage.getApp().equals("spreed")) {
                        sendNotification(decryptedPushMessage.getSubject(), signatureVerification.getAccount());
                    }
                }
            } catch (NoSuchAlgorithmException e1) {
                Log.d(TAG, "No proper algorithm to decrypt the message " + e1.getLocalizedMessage());
            } catch (NoSuchPaddingException e1) {
                Log.d(TAG, "No proper padding to decrypt the message " + e1.getLocalizedMessage());
            } catch (InvalidKeyException e1) {
                Log.d(TAG, "Invalid private key " + e1.getLocalizedMessage());
            }
        } catch (Exception exception) {
            Log.d(TAG, "Something went very wrong" + exception.getLocalizedMessage());
        }
    }
    return Result.SUCCESS;
}
Also used : Context(android.content.Context) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) PushUtils(com.owncloud.android.utils.PushUtils) PrivateKey(java.security.PrivateKey) Gson(com.google.gson.Gson) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) SignatureVerification(com.owncloud.android.datamodel.SignatureVerification) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) DecryptedPushMessage(com.owncloud.android.datamodel.DecryptedPushMessage) Cipher(javax.crypto.Cipher) NonNull(android.support.annotation.NonNull)

Example 22 with PersistableBundleCompat

use of com.evernote.android.job.util.support.PersistableBundleCompat in project talk-android by nextcloud.

the class MagicFirebaseMessagingService method onMessageReceived.

@SuppressLint("LongLogTag")
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData() != null) {
        PersistableBundleCompat persistableBundleCompat = new PersistableBundleCompat();
        persistableBundleCompat.putString(BundleKeys.KEY_NOTIFICATION_SUBJECT, remoteMessage.getData().get("subject"));
        persistableBundleCompat.putString(BundleKeys.KEY_NOTIFICATION_SIGNATURE, remoteMessage.getData().get("signature"));
        new JobRequest.Builder(NotificationJob.TAG).addExtras(persistableBundleCompat).setUpdateCurrent(false).startNow().build().schedule();
    }
}
Also used : PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) JobRequest(com.evernote.android.job.JobRequest) SuppressLint(android.annotation.SuppressLint)

Example 23 with PersistableBundleCompat

use of com.evernote.android.job.util.support.PersistableBundleCompat in project talk-android by nextcloud.

the class AccountVerificationController method checkEverything.

private void checkEverything() {
    String credentials = ApiUtils.getCredentials(username, token);
    cookieManager.getCookieStore().removeAll();
    roomsQueryDisposable = ncApi.getRooms(credentials, ApiUtils.getUrlForGetRooms(baseUrl)).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(roomsOverall -> {
        progressText.setText(String.format(getResources().getString(R.string.nc_nextcloud_talk_app_installed), getResources().getString(R.string.nc_app_name)));
        profileQueryDisposable = ncApi.getUserProfile(credentials, ApiUtils.getUrlForUserProfile(baseUrl)).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(userProfileOverall -> {
            progressText.setText(progressText.getText().toString() + "\n" + getResources().getString(R.string.nc_display_name_fetched));
            String displayName = null;
            if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData().getDisplayName())) {
                displayName = userProfileOverall.getOcs().getData().getDisplayName();
            } else if (!TextUtils.isEmpty(userProfileOverall.getOcs().getData().getDisplayNameAlt())) {
                displayName = userProfileOverall.getOcs().getData().getDisplayNameAlt();
            }
            if (!TextUtils.isEmpty(displayName)) {
                dbQueryDisposable = userUtils.createOrUpdateUser(username, token, baseUrl, displayName, null, true, userProfileOverall.getOcs().getData().getUserId(), null, null).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(userEntity -> {
                    progressText.setText(progressText.getText().toString() + "\n" + getResources().getString(R.string.nc_display_name_stored));
                    new JobRequest.Builder(PushRegistrationJob.TAG).setUpdateCurrent(true).startNow().build().schedule();
                    PersistableBundleCompat persistableBundleCompat = new PersistableBundleCompat();
                    persistableBundleCompat.putLong(BundleKeys.KEY_INTERNAL_USER_ID, userEntity.getId());
                    new JobRequest.Builder(CapabilitiesJob.TAG).setUpdateCurrent(false).addExtras(persistableBundleCompat).startNow().build().schedule();
                    cookieManager.getCookieStore().removeAll();
                    userUtils.disableAllUsersWithoutId(userEntity.getId());
                    if (userUtils.getUsers().size() == 1) {
                        getRouter().setRoot(RouterTransaction.with(new MagicBottomNavigationController()).pushChangeHandler(new HorizontalChangeHandler()).popChangeHandler(new HorizontalChangeHandler()));
                    } else {
                        if (isAccountImport) {
                            ApplicationWideMessageHolder.getInstance().setMessageType(ApplicationWideMessageHolder.MessageType.ACCOUNT_WAS_IMPORTED);
                        }
                        getRouter().popToRoot();
                    }
                }, throwable -> {
                    progressText.setText(progressText.getText().toString() + "\n" + getResources().getString(R.string.nc_display_name_not_stored));
                    abortVerification();
                }, () -> dispose(dbQueryDisposable));
            } else {
                progressText.setText(progressText.getText().toString() + "\n" + getResources().getString(R.string.nc_display_name_not_fetched));
                abortVerification();
            }
        }, throwable -> {
            progressText.setText(progressText.getText().toString() + "\n" + getResources().getString(R.string.nc_display_name_not_fetched));
            abortVerification();
        }, () -> dispose(profileQueryDisposable));
    }, throwable -> {
        progressText.setText(String.format(getResources().getString(R.string.nc_nextcloud_talk_app_not_installed), getResources().getString(R.string.nc_app_name)));
        ApplicationWideMessageHolder.getInstance().setMessageType(ApplicationWideMessageHolder.MessageType.SERVER_WITHOUT_TALK);
        abortVerification();
    }, () -> dispose(roomsQueryDisposable));
}
Also used : AutoInjector(autodagger.AutoInjector) JobRequest(com.evernote.android.job.JobRequest) Bundle(android.os.Bundle) UserUtils(com.nextcloud.talk.utils.database.user.UserUtils) PushRegistrationJob(com.nextcloud.talk.jobs.PushRegistrationJob) NonNull(android.support.annotation.NonNull) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) CapabilitiesJob(com.nextcloud.talk.jobs.CapabilitiesJob) BindView(butterknife.BindView) Inject(javax.inject.Inject) ApiUtils(com.nextcloud.talk.utils.ApiUtils) BaseController(com.nextcloud.talk.controllers.base.BaseController) Handler(android.os.Handler) ActivityInfo(android.content.pm.ActivityInfo) View(android.view.View) Schedulers(io.reactivex.schedulers.Schedulers) NcApi(com.nextcloud.talk.api.NcApi) R(com.nextcloud.talk.R) LayoutInflater(android.view.LayoutInflater) CompletableObserver(io.reactivex.CompletableObserver) TextUtils(android.text.TextUtils) ViewGroup(android.view.ViewGroup) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler) BundleKeys(com.nextcloud.talk.utils.bundle.BundleKeys) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) CookieManager(java.net.CookieManager) Nullable(android.support.annotation.Nullable) ApplicationWideMessageHolder(com.nextcloud.talk.utils.ApplicationWideMessageHolder) NextcloudTalkApplication(com.nextcloud.talk.application.NextcloudTalkApplication) RouterTransaction(com.bluelinelabs.conductor.RouterTransaction) JobRequest(com.evernote.android.job.JobRequest) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) HorizontalChangeHandler(com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler)

Example 24 with PersistableBundleCompat

use of com.evernote.android.job.util.support.PersistableBundleCompat in project talk-android by nextcloud.

the class NotificationJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    Context context = getContext();
    PersistableBundleCompat persistableBundleCompat = getParams().getExtras();
    String subject = persistableBundleCompat.getString(BundleKeys.KEY_NOTIFICATION_SUBJECT, "");
    String signature = persistableBundleCompat.getString(BundleKeys.KEY_NOTIFICATION_SIGNATURE, "");
    if (!TextUtils.isEmpty(subject) && !TextUtils.isEmpty(signature)) {
        try {
            byte[] base64DecodedSubject = Base64.decode(subject, Base64.DEFAULT);
            byte[] base64DecodedSignature = Base64.decode(signature, Base64.DEFAULT);
            PushUtils pushUtils = new PushUtils();
            PrivateKey privateKey = (PrivateKey) pushUtils.readKeyFromFile(false);
            try {
                SignatureVerification signatureVerification = pushUtils.verifySignature(base64DecodedSignature, base64DecodedSubject);
                if (signatureVerification.isSignatureValid()) {
                    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
                    cipher.init(Cipher.DECRYPT_MODE, privateKey);
                    byte[] decryptedSubject = cipher.doFinal(base64DecodedSubject);
                    DecryptedPushMessage decryptedPushMessage = LoganSquare.parse(new String(decryptedSubject), DecryptedPushMessage.class);
                    if (decryptedPushMessage.getApp().equals("spreed")) {
                        int smallIcon;
                        Bitmap largeIcon;
                        String category = "";
                        int priority = Notification.PRIORITY_DEFAULT;
                        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Intent intent = new Intent(context, CallActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString(BundleKeys.KEY_ROOM_TOKEN, decryptedPushMessage.getId());
                        bundle.putParcelable(BundleKeys.KEY_USER_ENTITY, Parcels.wrap(signatureVerification.getUserEntity()));
                        bundle.putBoolean("fromNotification", true);
                        intent.putExtras(bundle);
                        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                        switch(decryptedPushMessage.getType()) {
                            case "call":
                                smallIcon = R.drawable.ic_call_black_24dp;
                                category = Notification.CATEGORY_CALL;
                                priority = Notification.PRIORITY_HIGH;
                                soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                                break;
                            case "room":
                                smallIcon = R.drawable.ic_notifications_black_24dp;
                                category = Notification.CATEGORY_CALL;
                                priority = Notification.PRIORITY_HIGH;
                                break;
                            case "chat":
                                smallIcon = R.drawable.ic_chat_black_24dp;
                                category = Notification.CATEGORY_MESSAGE;
                                break;
                            default:
                                smallIcon = R.drawable.ic_logo;
                        }
                        largeIcon = BitmapFactory.decodeResource(context.getResources(), smallIcon);
                        CRC32 crc32 = new CRC32();
                        Notification.Builder notificationBuilder = new Notification.Builder(context).setLargeIcon(largeIcon).setSmallIcon(smallIcon).setCategory(category).setPriority(priority).setWhen(Calendar.getInstance().getTimeInMillis()).setShowWhen(true).setSubText(signatureVerification.getUserEntity().getDisplayName()).setContentTitle(decryptedPushMessage.getSubject()).setSound(soundUri).setAutoCancel(true);
                        if (Build.VERSION.SDK_INT >= 23) {
                            // This method should exist since API 21, but some phones don't have it
                            // So as a safeguard, we don't use it until 23
                            notificationBuilder.setColor(context.getResources().getColor(R.color.colorPrimary));
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            String groupName = String.format(context.getResources().getString(R.string.nc_notification_channel), signatureVerification.getUserEntity().getDisplayName(), signatureVerification.getUserEntity().getBaseUrl());
                            crc32.update(groupName.getBytes());
                            NotificationUtils.createNotificationChannelGroup(notificationManager, Long.toString(crc32.getValue()), groupName);
                            if (category.equals(Notification.CATEGORY_CALL)) {
                                NotificationUtils.createNotificationChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_CALLS, context.getResources().getString(R.string.nc_notification_channel_calls), context.getResources().getString(R.string.nc_notification_channel_calls_description), true, NotificationManager.IMPORTANCE_HIGH, soundUri);
                                notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_CALLS);
                            } else {
                                NotificationUtils.createNotificationChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES, context.getResources().getString(R.string.nc_notification_channel_messages), context.getResources().getString(R.string.nc_notification_channel_messages_description), true, NotificationManager.IMPORTANCE_DEFAULT, soundUri);
                                notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MESSAGES);
                            }
                            notificationBuilder.setGroup(Long.toString(crc32.getValue()));
                        }
                        notificationBuilder.setContentIntent(pendingIntent);
                        String stringForCrc = decryptedPushMessage.getSubject() + " " + signatureVerification.getUserEntity().getDisplayName() + " " + signatureVerification.getUserEntity().getBaseUrl();
                        crc32 = new CRC32();
                        crc32.update(stringForCrc.getBytes());
                        if (notificationManager != null) {
                            notificationManager.notify((int) crc32.getValue(), notificationBuilder.build());
                        }
                    }
                }
            } catch (NoSuchAlgorithmException e1) {
                Log.d(TAG, "No proper algorithm to decrypt the message " + e1.getLocalizedMessage());
            } catch (NoSuchPaddingException e1) {
                Log.d(TAG, "No proper padding to decrypt the message " + e1.getLocalizedMessage());
            } catch (InvalidKeyException e1) {
                Log.d(TAG, "Invalid private key " + e1.getLocalizedMessage());
            }
        } catch (Exception exception) {
            Log.d(TAG, "Something went very wrong" + exception.getLocalizedMessage());
        }
    }
    return Result.SUCCESS;
}
Also used : Context(android.content.Context) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) PushUtils(com.nextcloud.talk.utils.PushUtils) PrivateKey(java.security.PrivateKey) NotificationManager(android.app.NotificationManager) CRC32(java.util.zip.CRC32) Bundle(android.os.Bundle) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) SignatureVerification(com.nextcloud.talk.models.SignatureVerification) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Uri(android.net.Uri) Notification(android.app.Notification) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) DecryptedPushMessage(com.nextcloud.talk.models.json.push.DecryptedPushMessage) Bitmap(android.graphics.Bitmap) Cipher(javax.crypto.Cipher) PendingIntent(android.app.PendingIntent) NonNull(android.support.annotation.NonNull)

Example 25 with PersistableBundleCompat

use of com.evernote.android.job.util.support.PersistableBundleCompat in project orgzly-android by orgzly.

the class SnoozeJob method scheduleJob.

public static void scheduleJob(Context context, long noteId, int noteTimeType, long timestamp) {
    PersistableBundleCompat extras = new PersistableBundleCompat();
    long snoozeTime = AppPreferences.remindersSnoozeTime(context) * 60 * 1000;
    String snoozeRelativeTo = AppPreferences.remindersSnoozeRelativeTo(context);
    long exactMs;
    if (snoozeRelativeTo.equals("button")) {
        exactMs = snoozeTime;
    } else if (snoozeRelativeTo.equals("alarm")) {
        timestamp += snoozeTime;
        exactMs = timestamp - System.currentTimeMillis();
        // someone lets the alarm go off for more that one snoozeTime interval
        while (exactMs <= 0) {
            exactMs += snoozeTime;
            timestamp += snoozeTime;
        }
    } else {
        // should never happen
        Log.e(TAG, "unhandled snoozeRelativeTo " + snoozeRelativeTo);
        return;
    }
    if (BuildConfig.LOG_DEBUG)
        LogUtils.d(TAG, noteId, noteTimeType, timestamp, exactMs);
    extras.putLong(AppIntent.EXTRA_NOTE_ID, noteId);
    extras.putInt(AppIntent.EXTRA_NOTE_TIME_TYPE, noteTimeType);
    extras.putLong(AppIntent.EXTRA_SNOOZE_TIMESTAMP, timestamp);
    new JobRequest.Builder(SnoozeJob.TAG).setExact(exactMs).setExtras(extras).build().schedule();
}
Also used : PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat)

Aggregations

PersistableBundleCompat (com.evernote.android.job.util.support.PersistableBundleCompat)25 JobRequest (com.evernote.android.job.JobRequest)11 NonNull (android.support.annotation.NonNull)7 Context (android.content.Context)5 Account (android.accounts.Account)4 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)4 Test (org.junit.Test)4 Intent (android.content.Intent)3 File (java.io.File)3 Bundle (android.os.Bundle)2 Handler (android.os.Handler)2 LargeTest (android.support.test.filters.LargeTest)2 SmallTest (android.support.test.filters.SmallTest)2 FilesystemDataProvider (com.owncloud.android.datamodel.FilesystemDataProvider)2 SyncedFolder (com.owncloud.android.datamodel.SyncedFolder)2 SyncedFolderProvider (com.owncloud.android.datamodel.SyncedFolderProvider)2 FileUploader (com.owncloud.android.files.services.FileUploader)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 PrivateKey (java.security.PrivateKey)2