aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/World.kt
blob: aa37a6a63a80af07cdb11fab7083549981f6cfde (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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package net.lacolaco.smileessence

import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
import android.view.View
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.beust.klaxon.json
import com.bumptech.glide.Glide
import com.bumptech.glide.request.Request
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SizeReadyCallback
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import net.lacolaco.smileessence.activity.MainActivity
import net.lacolaco.smileessence.data.PageInfo
import net.lacolaco.smileessence.entity.Event
import net.lacolaco.smileessence.entity.SavedSearch
import net.lacolaco.smileessence.entity.Tweet
import net.lacolaco.smileessence.entity.User
import net.lacolaco.smileessence.twitter.*
import net.lacolaco.smileessence.util.launchBg
import net.lacolaco.smileessence.util.launchUi
import twitter4j.Twitter
import twitter4j.TwitterFactory
import twitter4j.auth.AccessToken
import twitter4j.conf.ConfigurationBuilder
import java.lang.ref.WeakReference
import java.util.*
import kotlin.coroutines.*

/**
 * World contains data that are specific to a profile.
 */
class World private constructor(private val persistentData: PersistentData) {
    val id = persistentData.id
    val user: User = User.makeSkeletonForInternalUseOnly(id, persistentData.screenName,
            persistentData.profileImageUrl)
    // XXX: Workaround for a bug in Android
    var mainActivityIntent: Intent? = null
    // Timelines
    private val tweets = HashMap<Long, Tweet>()
    private val tweetNotifiers = WeakHashMap<Any, (Tweet) -> Unit>()
    // Events
    private val events = ArrayList<Event>()
    private val eventNotifiers = WeakHashMap<Any, (Event) -> Unit>()
    // Streaming
    private lateinit var stream: PoePoeStreaming
    // Lists
    val listSubscriptions = HashSet<String>()
    // Mute
    private val muteUserIds = HashSet<Long>()
    // Saved searches
    val savedSearches = HashMap<Long, SavedSearch>()
    // Notification
    private var mainActivity: WeakReference<MainActivity>? = null
    private var isMainActivityActive: Boolean = false
    // Pages
    val pages = persistentData.pageInfos

    // Startup

    private var initialized = false
    fun setup() {
        if (initialized)
            return
        initialized = true

        launchBg {
            try {
                listSubscriptions += getUserListsAsync().await()
            } catch (e: TwitterTaskException) {
            }
        }
        launchBg {
            try {
                val blockIds = getBlocksIdsAsync()
                val muteIds = getMutesIdsAsync()
                muteUserIds += blockIds.await()
                muteUserIds += muteIds.await()
            } catch (e: TwitterTaskException) {
            }
        }
        launchBg {
            try {
                val ssl = getSavedSearchesAsync().await()
                savedSearches.clear()
                for (ss in ssl)
                    savedSearches[ss.id] = ss
            } catch (e: TwitterTaskException) {
            }
        }
        launchBg {
            try {
                val jobs = listOf(getHomeTimelineAsync(), getMentionsTimelineAsync())
                jobs.forEach { addTweetAll(it.await()) }
            } catch (e: TwitterTaskException) {
                notifyError(R.string.notice_error_get_home)
            }
        }

        stream = PoePoeStreaming(this)
        stream.start()
    }

    fun refreshStream() {
        stream.stop()
        stream.start()
    }

    private var refreshUserCallback: (() -> Unit)? = null
    fun refreshUser(callback: () -> Unit) {
        synchronized(this) {
            if (refreshUserCallback == null) {
                refreshUserCallback = callback
            } else {
                val orig = refreshUserCallback!!
                refreshUserCallback = { orig(); callback() }
            }
        }

        launchBg {
            try {
                getUserAsync(id).await()
            } catch (e: TwitterTaskException) {
            }
            synchronized(this@World) {
                refreshUserCallback.also { refreshUserCallback = null }
            }!!()
        }
    }

    suspend fun getProfileImageBitmap(size: Int) = suspendCoroutine<Bitmap> { cont ->
        Glide.with(Application.instance)
                .asBitmap()
                .load(user.profileImageUrl)
                .apply(RequestOptions().fitCenter().override(size, size))
                .into(object : Target<Bitmap> {
                    private var req: Request? = null

                    override fun onLoadStarted(placeholder: Drawable?) {
                    }

                    override fun getSize(cb: SizeReadyCallback) {
                    }

                    override fun getRequest(): Request? {
                        return req
                    }

                    override fun onStop() {
                    }

                    override fun setRequest(request: Request?) {
                        req = request
                    }

                    override fun removeCallback(cb: SizeReadyCallback) {
                        cb.onSizeReady(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                    }

                    override fun onStart() {
                    }

                    override fun onDestroy() {
                    }

                    override fun onResourceReady(resource: Bitmap, tran: Transition<in Bitmap>?) {
                        cont.resume(resource)
                    }

                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        cont.resumeWithException(
                                RuntimeException("Profile image could not be loaded"))
                    }
                })
    }


    fun checkpoint() = launchBg {
        persistentData.screenName = user.screenName
        persistentData.profileImageUrl = user.profileImageUrl
        persistentData.save()
    }

    var twitterEventStreamEndpoint
        get() = persistentData.twitterEventStreamEndpoint
        set(value) {
            persistentData.twitterEventStreamEndpoint = value
        }

    var useDarkTheme
        get() = persistentData.themeIndex == 0
        set(value) {
            persistentData.themeIndex = if (value) 0 else 1
        }

    var themeColor
        get() = persistentData.themeColor
        set(value) {
            persistentData.themeColor = value
        }

    val twitter: Twitter
        get() {
            val cb = ConfigurationBuilder()
            cb.setTweetModeExtended(true)
            val twitter = TwitterFactory(cb.build()).instance
            twitter.oAuthAccessToken = AccessToken(
                    persistentData.oauthToken, persistentData.oauthTokenSecret)
            return twitter
        }

    // MainActivity holder

    fun setMainActivity(activity: MainActivity) {
        mainActivity = WeakReference(activity)
    }

    fun getMainActivity(): MainActivity? = mainActivity?.get()

    fun setMainActivityActive(yes: Boolean) {
        isMainActivityActive = yes
    }

    // Timelines

    @Synchronized
    fun addTimeline(key: Any, callback: (Tweet) -> Unit) {
        for ((_, item) in tweets)
            callback(item)
        tweetNotifiers[key] = callback
    }

    @Synchronized
    fun addTweet(item: Tweet) {
        tweets[item.id] = item
        for ((_, callback) in tweetNotifiers)
            callback(item)
    }

    @Synchronized
    fun addTweetAll(collection: Collection<Tweet>) {
        for (item in collection) {
            tweets[item.id] = item
            for ((_, callback) in tweetNotifiers)
                callback(item)
        }
    }

    // Events

    @Synchronized
    fun addEventNotifier(key: Any, notify: (Event) -> Unit) {
        for (item in events)
            notify(item)
        eventNotifiers[key] = notify
    }

    private fun addEvent(item: Event) {
        events.add(item)
        for ((_, callback) in eventNotifiers)
            callback(item)
    }

    // Streaming APIs

    val isStreaming: Boolean
        get() = stream.connected

    // Notifications

    fun notify(text: String) {
        notify(Event.SimpleEvent("INFO", text))
    }

    fun notify(@StringRes resId: Int, vararg formatArgs: Any) {
        notify(Application.instance.getString(resId, *formatArgs))
    }

    fun notifyError(text: String) {
        notify(Event.SimpleEvent("ALERT", text))
    }

    fun notifyError(@StringRes resId: Int, vararg formatArgs: Any) {
        notifyError(Application.instance.getString(resId, *formatArgs))
    }

    fun notify(event: Event) {
        launchUi {
            if (isMainActivityActive) {
                val view: View = mainActivity!!.get()!!.findViewById(android.R.id.content)
                Logger.debug("notify(snackbar): ${event.summary}")
                Snackbar.make(view, event.summary, Snackbar.LENGTH_SHORT).show()
            } else {
                Logger.debug(String.format("notify(toast): %s", event.summary))
                Application.toast(event.summary)
            }
            addEvent(event)
        }
    }

    companion object {
        private val cache = LinkedHashMap<Long, World>()

        operator fun get(i: Long) =
                cache[i] ?: throw IllegalStateException("[BUG] World with id == $i not found")

        fun all() = ArrayList(cache.values)

        fun load() {
            if (cache.isNotEmpty())
                throw IllegalStateException("World.load called twice")
            PersistentData.fetchAll().forEach { cache[it.id] = World(it) }
            Logger.info("Loaded ${cache.size} profiles")
        }

        fun register(token: String, tokenSecret: String, userId: Long, screenName: String): World {
            val world = cache[userId]
                    ?: World(PersistentData(userId, token, tokenSecret, screenName))
            world.persistentData.oauthToken = token
            world.persistentData.oauthTokenSecret = tokenSecret
            world.persistentData.screenName = screenName
            world.persistentData.save()
            cache[userId] = world
            return world
        }
    }

    private class PersistentData(
            val id: Long,
            var oauthToken: String,
            var oauthTokenSecret: String,
            var screenName: String,
            var profileImageUrl: String = User.DEFAULT_PROFILE_IMAGE_URL,
            var pageInfos: MutableList<PageInfo> = makeDefaultPageInfos(screenName),
            var themeIndex: Int = 0,
            var themeColor: Int = 0,
            var twitterEventStreamEndpoint: String = "https://userstream.herokuapp.com/stream"
    ) {
        fun save() {
            val values = ContentValues()
            values.put("id", id)
            values.put("oauth_token", oauthToken)
            values.put("oauth_token_secret", oauthTokenSecret)
            values.put("screen_name", screenName)
            values.put("profile_image_url", profileImageUrl)
            values.put("page_infos", stringifyPageInfos())
            values.put("theme", themeIndex)
            values.put("theme_color", themeColor)
            values.put("twitter_event_stream_endpoint", twitterEventStreamEndpoint)
            if (Application.instance.db.replaceOrThrow("profiles", null, values) == -1L)
                throw RuntimeException("SQLiteDatabase#replaceOrThrow failed")
        }

        private fun stringifyPageInfos(): String {
            return json {
                array(pageInfos.filterNot { it.ephemeral }.map { PageInfo.toJsonObject(it) })
            }.toJsonString()
        }

        companion object {
            private fun makeDefaultPageInfos(screenName: String): MutableList<PageInfo> {
                val ret = arrayListOf<PageInfo>()
                ret.add(PageInfo.EventsPageInfo())
                ret.add(PageInfo.ComposePageInfo())
                ret.add(PageInfo.TweetsPageInfo("Home", arrayListOf("")))
                ret.add(PageInfo.TweetsPageInfo("Mentions", arrayListOf("@$screenName")))
                ret.add(PageInfo.SearchPageInfo(""))
                ret.add(PageInfo.ListPageInfo(null))
                return ret
            }

            private fun parsePageInfos(input: String): MutableList<PageInfo> {
                val json = Parser.default().parse(StringBuilder(input)) as JsonArray<*>
                return json.map { PageInfo.fromJsonObject(it as JsonObject) }.toMutableList()
            }

            fun fetchAll(): List<PersistentData> {
                val ret = arrayListOf<PersistentData>()
                Application.instance.db.query("profiles", null, null, null, null, null, null).use { cursor ->
                    while (cursor != null && cursor.moveToNext()) {
                        ret.add(PersistentData(
                                id = cursor.getLong(
                                        cursor.getColumnIndexOrThrow("id")),
                                oauthToken = cursor.getString(
                                        cursor.getColumnIndexOrThrow("oauth_token")),
                                oauthTokenSecret = cursor.getString(
                                        cursor.getColumnIndexOrThrow("oauth_token_secret")),
                                screenName = cursor.getString(
                                        cursor.getColumnIndexOrThrow("screen_name")),
                                profileImageUrl = cursor.getString(
                                        cursor.getColumnIndexOrThrow("profile_image_url")),
                                pageInfos = parsePageInfos(cursor.getString(
                                        cursor.getColumnIndexOrThrow("page_infos"))),
                                themeIndex = cursor.getInt(
                                        cursor.getColumnIndexOrThrow("theme")),
                                themeColor = cursor.getInt(
                                        cursor.getColumnIndexOrThrow("theme_color")),
                                twitterEventStreamEndpoint = cursor.getString(
                                        cursor.getColumnIndexOrThrow("twitter_event_stream_endpoint"))
                        ))
                    }
                }
                return ret
            }
        }
    }
}