aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/services/FrostNotifications.kt
blob: 6ff20bfb2da81d16eb9d3e70a729b4b93281aa69 (plain)
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
/*
 * Copyright 2018 Allan Wang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.pitchedapps.frost.services

import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.BaseBundle
import android.os.Build
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import ca.allanwang.kau.utils.dpToPx
import ca.allanwang.kau.utils.string
import com.pitchedapps.frost.BuildConfig
import com.pitchedapps.frost.R
import com.pitchedapps.frost.activities.FrostWebActivity
import com.pitchedapps.frost.db.CookieEntity
import com.pitchedapps.frost.db.FrostDatabase
import com.pitchedapps.frost.db.latestEpoch
import com.pitchedapps.frost.db.saveNotifications
import com.pitchedapps.frost.enums.OverlayContext
import com.pitchedapps.frost.facebook.FbItem
import com.pitchedapps.frost.facebook.parsers.FrostParser
import com.pitchedapps.frost.facebook.parsers.MessageParser
import com.pitchedapps.frost.facebook.parsers.NotifParser
import com.pitchedapps.frost.facebook.parsers.ParseNotification
import com.pitchedapps.frost.glide.FrostGlide
import com.pitchedapps.frost.glide.GlideApp
import com.pitchedapps.frost.settings.hasNotifications
import com.pitchedapps.frost.utils.ARG_USER_ID
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.Prefs
import com.pitchedapps.frost.utils.frostEvent
import com.pitchedapps.frost.utils.isIndependent
import java.util.Locale
import kotlin.math.abs

/**
 * Created by Allan Wang on 2017-07-08.
 *
 * Logic for build notifications, scheduling notifications, and showing notifications
 */
private val _40_DP = 40.dpToPx

/**
 * Enum to handle notification creations
 */
enum class NotificationType(
    val channelId: String,
    private val overlayContext: OverlayContext,
    private val fbItem: FbItem,
    private val parser: FrostParser<ParseNotification>,
    private val ringtone: () -> String
) {

    GENERAL(
        NOTIF_CHANNEL_GENERAL,
        OverlayContext.NOTIFICATION,
        FbItem.NOTIFICATIONS,
        NotifParser,
        Prefs::notificationRingtone
    ) {

        override fun bindRequest(content: NotificationContent, cookie: String) =
            FrostRunnable.prepareMarkNotificationRead(content.id, cookie)
    },

    MESSAGE(
        NOTIF_CHANNEL_MESSAGES,
        OverlayContext.MESSAGE,
        FbItem.MESSAGES,
        MessageParser,
        Prefs::messageRingtone
    );

    private val groupPrefix = "frost_${name.toLowerCase(Locale.CANADA)}"

    /**
     * Optional binder to return the request bundle builder
     */
    internal open fun bindRequest(
        content: NotificationContent,
        cookie: String
    ): (BaseBundle.() -> Unit)? = null

    private fun bindRequest(intent: Intent, content: NotificationContent) {
        val cookie = content.data.cookie ?: return
        val binder = bindRequest(content, cookie) ?: return
        val bundle = Bundle()
        bundle.binder()
        intent.putExtras(bundle)
    }

    /**
     * Get unread data from designated parser
     * Display notifications for those after old epoch
     * Save new epoch
     *
     * Returns the number of notifications generated,
     * or -1 if an error occurred
     */
    suspend fun fetch(context: Context, data: CookieEntity): Int {
        val notifDao = FrostDatabase.get().notifDao()
        val response = try {
            parser.parse(data.cookie)
        } catch (ignored: Exception) {
            null
        }
        if (response == null) {
            L.v { "$name notification data not found" }
            return -1
        }

        /**
         * Checks that the text doesn't contain any blacklisted keywords
         */
        fun validText(text: String?): Boolean {
            val t = text ?: return true
            return Prefs.notificationKeywords.none {
                t.contains(it, true)
            }
        }

        val notifContents = response.data.getUnreadNotifications(data).filter { notif ->
            validText(notif.title) && validText(notif.text)
        }
        if (notifContents.isEmpty()) return 0

        val userId = data.id
        val prevLatestEpoch = notifDao.latestEpoch(userId, channelId)
        L.v { "Notif $name prev epoch $prevLatestEpoch" }

        if (!notifDao.saveNotifications(channelId, notifContents)) {
            L.d { "Skip notifs for $name as saving failed" }
            return -1
        }

        if (prevLatestEpoch == -1L && !BuildConfig.DEBUG) {
            L.d { "Skipping first notification fetch" }
            return 0 // do not notify the first time
        }

        val newNotifContents = notifContents.filter { it.timestamp > prevLatestEpoch }

        if (newNotifContents.isEmpty()) {
            L.d { "No new notifs found for $name" }
            return 0
        }

        L.d { "${newNotifContents.size} new notifs found for $name" }

        val notifs = newNotifContents.map { createNotification(context, it) }

        frostEvent("Notifications", "Type" to name, "Count" to notifs.size)
        if (notifs.size > 1)
            summaryNotification(context, userId, notifs.size).notify(context)
        val ringtone = ringtone()
        notifs.forEachIndexed { i, notif ->
            // Ring at most twice
            notif.withAlert(context, i < 2, ringtone).notify(context)
        }
        return notifs.size
    }

    fun debugNotification(context: Context, data: CookieEntity) {
        val content = NotificationContent(
            data,
            System.currentTimeMillis(),
            "https://github.com/AllanWang/Frost-for-Facebook",
            "Debug Notif",
            "Test 123",
            System.currentTimeMillis() / 1000,
            "https://www.iconexperience.com/_img/v_collection_png/256x256/shadow/dog.png",
            false
        )
        createNotification(context, content).notify(context)
    }

    /**
     * Attach content related data to an intent
     */
    fun putContentExtra(intent: Intent, content: NotificationContent): Intent {
        // We will show the notification page for dependent urls. We can trigger a click next time
        intent.data =
            Uri.parse(if (content.href.isIndependent) content.href else FbItem.NOTIFICATIONS.url)
        bindRequest(intent, content)
        return intent
    }

    /**
     * Create a generic content for the provided type and user id.
     * No content related data is added
     */
    fun createCommonIntent(context: Context, userId: Long): Intent {
        val intent = Intent(context, FrostWebActivity::class.java)
        intent.putExtra(ARG_USER_ID, userId)
        overlayContext.put(intent)
        return intent
    }

    /**
     * Create and submit a new notification with the given [content]
     */
    private fun createNotification(
        context: Context,
        content: NotificationContent
    ): FrostNotification =
        with(content) {
            val intent = createCommonIntent(context, content.data.id)
            putContentExtra(intent, content)
            val group = "${groupPrefix}_${data.id}"
            val pendingIntent =
                PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
            val notifBuilder = context.frostNotification(channelId)
                .setContentTitle(title ?: context.string(R.string.frost_name))
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .setCategory(Notification.CATEGORY_SOCIAL)
                .setSubText(data.name)
                .setGroup(group)

            if (timestamp != -1L) notifBuilder.setWhen(timestamp * 1000)
            L.v { "Notif load $content" }

            if (profileUrl != null) {
                try {
                    val profileImg = GlideApp.with(context)
                        .asBitmap()
                        .load(profileUrl)
                        .transform(FrostGlide.circleCrop)
                        .submit(_40_DP, _40_DP)
                        .get()
                    notifBuilder.setLargeIcon(profileImg)
                } catch (e: Exception) {
                    L.e { "Failed to get image $profileUrl" }
                }
            }

            FrostNotification(group, notifId, notifBuilder)
        }

    /**
     * Create a summary notification to wrap the previous ones
     * This will always produce sound, vibration, and lights based on preferences
     * and will only show if we have at least 2 notifications
     */
    private fun summaryNotification(context: Context, userId: Long, count: Int): FrostNotification {
        val intent = Intent(context, FrostWebActivity::class.java)
        intent.data = Uri.parse(fbItem.url)
        intent.putExtra(ARG_USER_ID, userId)
        val group = "${groupPrefix}_$userId"
        val pendingIntent =
            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        val notifBuilder = context.frostNotification(channelId)
            .setContentTitle(context.string(R.string.frost_name))
            .setContentText("$count ${context.string(fbItem.titleId)}")
            .setGroup(group)
            .setGroupSummary(true)
            .setContentIntent(pendingIntent)
            .setCategory(Notification.CATEGORY_SOCIAL)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notifBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
        }

        return FrostNotification(group, 1, notifBuilder)
    }
}

/**
 * Notification data holder
 */
data class NotificationContent(
    // TODO replace data with userId?
    val data: CookieEntity,
    val id: Long,
    val href: String,
    val title: String? = null, // defaults to frost title
    val text: String,
    val timestamp: Long,
    val profileUrl: String?,
    val unread: Boolean
) {

    val notifId = abs(id.toInt())
}

/**
 * Wrapper for a complete notification builder and identifier
 * which can be immediately notified when given a [Context]
 */
data class FrostNotification(
    private val tag: String,
    private val id: Int,
    val notif: NotificationCompat.Builder
) {

    fun withAlert(context: Context, enable: Boolean, ringtone: String): FrostNotification {
        notif.setFrostAlert(context, enable, ringtone)
        return this
    }

    fun notify(context: Context) =
        NotificationManagerCompat.from(context).notify(tag, id, notif.build())
}

fun Context.scheduleNotificationsFromPrefs(): Boolean {
    val shouldSchedule = Prefs.hasNotifications
    return if (shouldSchedule) scheduleNotifications(Prefs.notificationFreq)
    else scheduleNotifications(-1)
}

fun Context.scheduleNotifications(minutes: Long): Boolean =
    scheduleJob<NotificationService>(NOTIFICATION_PERIODIC_JOB, minutes)

fun Context.fetchNotifications(): Boolean =
    fetchJob<NotificationService>(NOTIFICATION_JOB_NOW)