aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/World.kt
blob: 638607d1bef29655c90378e89d022cf90e6ef8b4 (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
package net.lacolaco.smileessence

import android.content.Intent
import android.support.annotation.StringRes
import de.keyboardsurfer.android.widget.crouton.Configuration
import de.keyboardsurfer.android.widget.crouton.Crouton
import de.keyboardsurfer.android.widget.crouton.Style
import net.lacolaco.smileessence.activity.MainActivity
import net.lacolaco.smileessence.compat.Twitter4J
import net.lacolaco.smileessence.data.Account
import net.lacolaco.smileessence.data.PostState
import net.lacolaco.smileessence.entity.DirectMessage
import net.lacolaco.smileessence.entity.Event
import net.lacolaco.smileessence.entity.SavedSearch
import net.lacolaco.smileessence.entity.Tweet
import net.lacolaco.smileessence.logging.Logger
import net.lacolaco.smileessence.twitter.UserStreamListener
import net.lacolaco.smileessence.twitter.task.Accounts
import net.lacolaco.smileessence.twitter.task.Searches
import net.lacolaco.smileessence.twitter.task.Users
import net.lacolaco.smileessence.util.*
import twitter4j.TwitterStream

import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.ConcurrentHashMap

/**
 * World contains data that are specific to an account.
 */
class World(val account: Account) {
    private val resId: Int = 0 // XXX: Fetch from Account
    // XXX: Move to MainActivity
    val postState = PostState()
    // XXX: Workaround for a bug in Android
    @Deprecated("A temporary workaround")
    var mainActivityIntent: Intent? = null
    // Timelines
    private val tweets = ArrayList<Tweet>()
    private val tweetNotifiers = WeakHashMap<Any, (Tweet) -> Unit>()
    // Direct messages
    private val directMessages = ConcurrentHashMap<Long, DirectMessage>()
    private val directMessageNotifiers = WeakHashMap<Any, (DirectMessage) -> Unit>()
    // Events
    val events = ArrayList<Event>()
    private val eventNotifiers = WeakHashMap<Any, () -> Unit>()
    // Streaming APIs
    private var stream: TwitterStream? = null
    private var userStreamListener: UserStreamListener? = null
    // Lists
    val listSubscriptions = Collections.newSetFromMap(ConcurrentHashMap<String, Boolean>())
    // Mute
    private val muteUserIds = Collections.newSetFromMap(ConcurrentHashMap<Long, Boolean>())
    // Saved searches
    val savedSearches = HashMap<Long, SavedSearch>()
    // Notification
    private var mainActivity: WeakReference<MainActivity>? = null
    private var isMainActivityActive: Boolean = false

    // Timelines

    @Synchronized
    fun addTimeline(key: Any, notify: (Tweet) -> Unit) {
        for (tweet in tweets)
            notify(tweet)
        tweetNotifiers.put(key, notify)
    }

    @Synchronized
    fun addTweet(tweet: Tweet) {
        tweets.add(tweet)
        tweetNotifiers.forEach { o, c -> c(tweet) }
    }

    @Synchronized
    fun addTweetAll(ts: Collection<Tweet>) {
        tweets.addAll(ts)
        for (tweet in ts) {
            tweetNotifiers.forEach { o, c -> c(tweet) }
        }
    }

    // Direct messages

    @Synchronized
    fun addDirectMessageTimeline(key: Any, notify: (DirectMessage) -> Unit) {
        directMessageNotifiers.put(key, notify)
    }

    fun addDirectMessage(entity: DirectMessage) {
        if (directMessages.put(entity.id, entity) == null)
            directMessageNotifiers.forEach { o, c -> c(entity) }
    }

    fun addDirectMessage(entities: Iterable<DirectMessage>) {
        entities.forEach { addDirectMessage(it) }
    }

    // Events

    @Synchronized
    fun addEventNotifier(key: Any, notify: () -> Unit) {
        eventNotifiers.put(key, notify)
    }

    fun addEvent(e: Event) {
        events.add(e)
        eventNotifiers.forEach { o, a -> a() }
    }

    // Streaming APIs

    fun setupStreaming() {
        if (stream == null) {
            stream = account.twitterStream
            userStreamListener = UserStreamListener(this)
            Twitter4J.twitterStreamAddListener(stream!!, userStreamListener!!)
            stream!!.addConnectionLifeCycleListener(userStreamListener)
            stream!!.user()
        }
    }

    val isStreaming: Boolean
        get() = stream != null && userStreamListener!!.isConnected

    // Lists

    fun refreshListSubscriptions(): BackgroundTask<List<String>, Void> {
        return Users.GetManyTask(account)
                .onDone { lists ->
                    listSubscriptions.clear()
                    listSubscriptions.addAll(lists)
                }
                // .onFail(x -> { }) // TODO: error message?
                .execute()
    }

    fun addListSubscription(fullName: String): Boolean {
        return listSubscriptions.add(fullName)
    }

    fun removeListSubscription(fullName: String): Boolean {
        return listSubscriptions.remove(fullName)
    }

    // Mute

    fun refreshUserMuteList(): List<BackgroundTask<*, *>> {
        val tasks = ArrayList<BackgroundTask<*, *>>()
        tasks.add(Accounts.BlockIDsTask(account).onDone { muteUserIds.addAll(it) }.execute())
        tasks.add(Accounts.MutesIDsTask(account).onDone { muteUserIds.addAll(it) }.execute())
        return tasks
    }

    fun isMutedUserListContains(id: Long): Boolean {
        return muteUserIds.contains(id)
    }

    // Saved search queries

    fun refreshSavedSearches(): BackgroundTask<List<SavedSearch>, Void> {
        return Searches.GetAllSavedSearchesTask(account).onDone { ssl ->
            savedSearches.clear()
            for (ss in ssl)
                savedSearches.put(ss.id, ss)
        }.execute()
    }

    // Notifications

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

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

    fun notify(text: String) {
        doNotify(NotificationType.INFO, text)
    }

    fun notify(@StringRes resId: Int, vararg formatArgs: Any) {
        doNotify(NotificationType.INFO, resId, *formatArgs)
    }

    fun notifyError(text: String) {
        doNotify(NotificationType.ALERT, text)
    }

    fun notifyError(@StringRes resId: Int, vararg formatArgs: Any) {
        doNotify(NotificationType.ALERT, resId, *formatArgs)
    }

    private fun doNotify(type: NotificationType, @StringRes resId: Int, vararg formatArgs: Any) {
        val context = mainActivity!!.get()
        if (context != null) {
            val text = context.getString(resId, *formatArgs)
            doNotify(type, text)
        } else {
            Logger.debug("MainActivity is dead")
        }
    }

    private fun doNotify(type: NotificationType, text: String) {
        val activity = mainActivity!!.get()
        if (activity == null || activity.isFinishing) {
            Logger.debug(String.format("notify(log): %s", text))
        } else {
            UIHandler().post {
                if (isMainActivityActive) {
                    Logger.debug(String.format("notify(crouton): %s", text))
                    val conf = Configuration.Builder()
                    conf.setDuration(NOTIFICATION_DURATION)
                    val bstyle = Style.Builder()
                    bstyle.setConfiguration(conf.build())
                    bstyle.setBackgroundColorValue(if (type == NotificationType.ALERT)
                        Style.holoRedLight
                    else
                        Style.holoBlueLight)
                    Crouton.makeText(activity, text, bstyle.build()).show()
                } else {
                    Logger.debug(String.format("notify(toast): %s", text))
                    Application.toast(text)
                }
            }
        }
    }

    internal enum class NotificationType {
        INFO,
        ALERT
    }

    companion object {
        private val NOTIFICATION_DURATION = 1000
    }
}