-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathNotificationWork.kt
More file actions
367 lines (349 loc) · 17.5 KB
/
Copy pathNotificationWork.kt
File metadata and controls
367 lines (349 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.nextcloud.client.jobs
import android.Manifest
import android.accounts.AuthenticatorException
import android.accounts.OperationCanceledException
import android.app.Activity
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.text.TextUtils
import android.util.Base64
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.integrations.deck.DeckApi
import com.owncloud.android.R
import com.owncloud.android.datamodel.DecryptedPushMessage
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.OwnCloudClientFactory
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.lib.resources.notifications.DeleteNotificationRemoteOperation
import com.owncloud.android.lib.resources.notifications.GetNotificationRemoteOperation
import com.owncloud.android.lib.resources.notifications.models.Notification
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.ui.navigation.NavigatorActivity
import com.owncloud.android.ui.navigation.NavigatorScreen
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.PushUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
import dagger.android.AndroidInjection
import org.apache.commons.httpclient.HttpMethod
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.httpclient.methods.DeleteMethod
import org.apache.commons.httpclient.methods.GetMethod
import org.apache.commons.httpclient.methods.PutMethod
import org.apache.commons.httpclient.methods.Utf8PostMethod
import java.io.IOException
import java.security.GeneralSecurityException
import java.security.PrivateKey
import java.security.SecureRandom
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.inject.Inject
@Suppress("LongParameterList")
class NotificationWork constructor(
private val context: Context,
params: WorkerParameters,
private val notificationManager: NotificationManager,
private val accountManager: UserAccountManager,
private val deckApi: DeckApi,
private val viewThemeUtils: ViewThemeUtils
) : Worker(context, params) {
companion object {
const val TAG = "NotificationJob"
const val KEY_NOTIFICATION_ACCOUNT = "KEY_NOTIFICATION_ACCOUNT"
const val KEY_NOTIFICATION_SUBJECT = "subject"
const val KEY_NOTIFICATION_SIGNATURE = "signature"
private const val KEY_NOTIFICATION_ACTION_LINK = "KEY_NOTIFICATION_ACTION_LINK"
private const val KEY_NOTIFICATION_ACTION_TYPE = "KEY_NOTIFICATION_ACTION_TYPE"
private const val PUSH_NOTIFICATION_ID = "PUSH_NOTIFICATION_ID"
private const val NUMERIC_NOTIFICATION_ID = "NUMERIC_NOTIFICATION_ID"
}
@Suppress("TooGenericExceptionCaught", "NestedBlockDepth", "ComplexMethod", "LongMethod") // legacy code
override fun doWork(): Result {
val subject = inputData.getString(KEY_NOTIFICATION_SUBJECT) ?: ""
val signature = inputData.getString(KEY_NOTIFICATION_SIGNATURE) ?: ""
if (!TextUtils.isEmpty(subject) && !TextUtils.isEmpty(signature)) {
try {
val base64DecodedSubject = Base64.decode(subject, Base64.DEFAULT)
val base64DecodedSignature = Base64.decode(signature, Base64.DEFAULT)
val privateKey = PushUtils.readKeyFromFile(false) as PrivateKey
try {
val signatureVerification = PushUtils.verifySignature(
context,
accountManager,
base64DecodedSignature,
base64DecodedSubject
)
if (signatureVerification != null && signatureVerification.signatureValid) {
val decryptedSubject = decryptSubject(privateKey, base64DecodedSubject)
val gson = Gson()
val decryptedPushMessage = gson.fromJson(
String(decryptedSubject),
DecryptedPushMessage::class.java
)
if (decryptedPushMessage.delete) {
notificationManager.cancel(decryptedPushMessage.nid)
} else if (decryptedPushMessage.deleteAll) {
notificationManager.cancelAll()
} else {
val user = accountManager.getUser(signatureVerification.account?.name)
.orElseThrow { RuntimeException() }
fetchCompleteNotification(user, decryptedPushMessage)
}
}
} catch (e1: GeneralSecurityException) {
Log_OC.d(TAG, "Error decrypting message ${e1.javaClass.name} ${e1.localizedMessage}")
}
} catch (exception: Exception) {
Log_OC.d(TAG, "Something went very wrong" + exception.localizedMessage)
}
}
return Result.success()
}
private fun decryptSubject(privateKey: PrivateKey, base64DecodedSubject: ByteArray): ByteArray = try {
val cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
cipher.doFinal(base64DecodedSubject)
} catch (e: BadPaddingException) {
Log_OC.e(TAG, "OAEP padding failed, trying PKCS1 for compatibility", e)
val cipher = Cipher.getInstance("RSA/None/PKCS1Padding")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
cipher.doFinal(base64DecodedSubject)
}
@Suppress("LongMethod") // legacy code
private fun sendNotification(notification: Notification, user: User) {
val randomId = SecureRandom()
val file = notification.subjectRichParameters["file"]
val deckActionOverrideIntent = deckApi.createForwardToDeckActionIntent(notification, user)
val pendingIntent: PendingIntent?
if (deckActionOverrideIntent.isPresent) {
pendingIntent = deckActionOverrideIntent.get()
} else {
val intent: Intent
if (file == null) {
intent = NavigatorActivity.intent(context, NavigatorScreen.Notifications)
} else {
intent = Intent(context, FileDisplayActivity::class.java)
intent.action = Intent.ACTION_VIEW
intent.putExtra(FileDisplayActivity.KEY_FILE_ID, file.id)
}
intent.putExtra(KEY_NOTIFICATION_ACCOUNT, user.accountName)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
pendingIntent = PendingIntent.getActivity(
context,
notification.getNotificationId(),
intent,
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
)
}
val pushNotificationId = randomId.nextInt()
val notificationBuilder = NotificationCompat.Builder(context, NotificationUtils.NOTIFICATION_CHANNEL_PUSH)
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.notification_icon))
.setShowWhen(true)
.setSubText(user.accountName)
.setContentTitle(notification.getSubject())
.setContentText(notification.getMessage())
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setContentIntent(pendingIntent)
viewThemeUtils.androidx.themeNotificationCompatBuilder(context, notificationBuilder)
// Remove
if (notification.getActions().isEmpty()) {
val disableDetection = Intent(context, NotificationReceiver::class.java)
disableDetection.putExtra(NUMERIC_NOTIFICATION_ID, notification.getNotificationId())
disableDetection.putExtra(PUSH_NOTIFICATION_ID, pushNotificationId)
disableDetection.putExtra(KEY_NOTIFICATION_ACCOUNT, user.accountName)
val disableIntent = PendingIntent.getBroadcast(
context,
pushNotificationId,
disableDetection,
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
notificationBuilder.addAction(
NotificationCompat.Action(
R.drawable.ic_close,
context.getString(R.string.remove_push_notification),
disableIntent
)
)
} else {
// Actions
for (action in notification.getActions()) {
val actionIntent = Intent(context, NotificationReceiver::class.java)
actionIntent.putExtra(NUMERIC_NOTIFICATION_ID, notification.getNotificationId())
actionIntent.putExtra(PUSH_NOTIFICATION_ID, pushNotificationId)
actionIntent.putExtra(KEY_NOTIFICATION_ACCOUNT, user.accountName)
actionIntent.putExtra(KEY_NOTIFICATION_ACTION_LINK, action.link)
actionIntent.putExtra(KEY_NOTIFICATION_ACTION_TYPE, action.type)
val actionPendingIntent = PendingIntent.getBroadcast(
context,
randomId.nextInt(),
actionIntent,
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
var icon: Int
icon = if (action.primary) {
R.drawable.ic_check_circle
} else {
R.drawable.ic_check_circle_outline
}
notificationBuilder.addAction(NotificationCompat.Action(icon, action.label, actionPendingIntent))
}
}
notificationBuilder.setPublicVersion(
NotificationCompat.Builder(context, NotificationUtils.NOTIFICATION_CHANNEL_PUSH)
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.notification_icon))
.setShowWhen(true)
.setSubText(user.accountName)
.setContentTitle(context.getString(R.string.new_notification))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.also {
viewThemeUtils.androidx.themeNotificationCompatBuilder(context, it)
}
.build()
)
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
Log_OC.w(this, "Missing permission to post notifications")
} else {
val notificationManager = NotificationManagerCompat.from(context)
notificationManager.notify(notification.getNotificationId(), notificationBuilder.build())
}
}
@Suppress("TooGenericExceptionCaught") // legacy code
private fun fetchCompleteNotification(account: User, decryptedPushMessage: DecryptedPushMessage) {
val optionalUser = accountManager.getUser(account.accountName)
if (!optionalUser.isPresent) {
Log_OC.e(this, "Account may not be null")
return
}
val user = optionalUser.get()
try {
val client = OwnCloudClientFactory.createNextcloudClient(user, context)
val result = GetNotificationRemoteOperation(decryptedPushMessage.nid)
.execute(client)
if (result.isSuccess) {
val notification = result.resultData
sendNotification(notification, account)
}
} catch (e: Exception) {
Log_OC.e(this, "Error creating account", e)
}
}
class NotificationReceiver : BroadcastReceiver() {
private lateinit var accountManager: UserAccountManager
/**
* This is a workaround for a Dagger compiler bug - it cannot inject
* into a nested Kotlin class for some reason, but the helper
* works.
*/
@Inject
fun inject(accountManager: UserAccountManager) {
this.accountManager = accountManager
}
@Suppress("ComplexMethod") // legacy code
override fun onReceive(context: Context, intent: Intent) {
AndroidInjection.inject(this, context)
val numericNotificationId = intent.getIntExtra(NUMERIC_NOTIFICATION_ID, 0)
val accountName = intent.getStringExtra(KEY_NOTIFICATION_ACCOUNT)
if (numericNotificationId != 0) {
Thread(
Runnable {
val notificationManager = context.getSystemService(
Activity.NOTIFICATION_SERVICE
) as NotificationManager
var oldNotification: android.app.Notification? = null
for (statusBarNotification in notificationManager.activeNotifications) {
if (numericNotificationId == statusBarNotification.id) {
oldNotification = statusBarNotification.notification
break
}
}
cancel(context, numericNotificationId)
try {
val optionalUser = accountManager.getUser(accountName)
if (optionalUser.isPresent) {
val user = optionalUser.get()
val client = OwnCloudClientManagerFactory.getDefaultSingleton()
.getClientFor(user.toOwnCloudAccount(), context)
val nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, context)
val actionType = intent.getStringExtra(KEY_NOTIFICATION_ACTION_TYPE)
val actionLink = intent.getStringExtra(KEY_NOTIFICATION_ACTION_LINK)
val success: Boolean = if (!actionType.isNullOrEmpty() && !actionLink.isNullOrEmpty()) {
val resultCode = executeAction(actionType, actionLink, client)
resultCode == HttpStatus.SC_OK || resultCode == HttpStatus.SC_ACCEPTED
} else {
DeleteNotificationRemoteOperation(numericNotificationId)
.execute(nextcloudClient).isSuccess
}
if (success) {
if (oldNotification == null) {
cancel(context, numericNotificationId)
}
} else {
notificationManager.notify(numericNotificationId, oldNotification)
}
}
} catch (e: IOException) {
Log_OC.e(TAG, "Error initializing client", e)
} catch (e: OperationCanceledException) {
Log_OC.e(TAG, "Error initializing client", e)
} catch (e: AuthenticatorException) {
Log_OC.e(TAG, "Error initializing client", e)
}
}
).start()
}
}
@Suppress("ReturnCount") // legacy code
private fun executeAction(actionType: String, actionLink: String, client: OwnCloudClient): Int {
val method: HttpMethod
method = when (actionType) {
"GET" -> GetMethod(actionLink)
"POST" -> Utf8PostMethod(actionLink)
"DELETE" -> DeleteMethod(actionLink)
"PUT" -> PutMethod(actionLink)
else -> return 0 // do nothing
}
method.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE)
try {
return client.executeMethod(method)
} catch (e: IOException) {
Log_OC.e(TAG, "Execution of notification action failed: $e")
}
return 0
}
private fun cancel(context: Context, notificationId: Int) {
val notificationManager = context.getSystemService(Activity.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notificationId)
}
}
}