aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/activity/MainActivity.kt
blob: 21f96254ea376120df56efb9a02f38697ce47d0c (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
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2014 lacolaco.net
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package net.lacolaco.smileessence.activity

import android.app.Activity
import android.app.ActivityManager
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.view.ViewPager
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.WindowManager
import android.widget.ImageView
import de.keyboardsurfer.android.widget.crouton.Crouton
import kotlinx.android.synthetic.main.layout_main.*
import net.lacolaco.smileessence.*
import net.lacolaco.smileessence.data.ExtractionWord
import net.lacolaco.smileessence.entity.Tweet
import net.lacolaco.smileessence.logging.Logger
import net.lacolaco.smileessence.twitter.task.Users
import net.lacolaco.smileessence.util.BitmapURLTask
import net.lacolaco.smileessence.view.DialogHelper
import net.lacolaco.smileessence.view.adapter.PageListAdapter
import net.lacolaco.smileessence.view.dialog.ConfirmDialogFragment
import net.lacolaco.smileessence.view.dialog.StatusDetailDialogFragment
import net.lacolaco.smileessence.view.dialog.UserDetailDialogFragment
import net.lacolaco.smileessence.view.page.*
import org.jetbrains.anko.browse
import org.jetbrains.anko.startActivity
import java.util.regex.Pattern

class MainActivity : Activity(), ViewPager.OnPageChangeListener {
    val world: World by lazy {
        val uri = intent.data ?: throw IllegalStateException("[BUG] data not set")
        val userIdValue = uri.getQueryParameter("user_id") ?: throw IllegalStateException("[BUG] user_id not set")
        val userId = java.lang.Long.parseLong(userIdValue)
        Application.getWorld(userId)
    }
    private val pagerAdapter by lazy { PageListAdapter(this) }
    private val currentAccountIconImageView by lazy { findViewById<ImageView>(android.R.id.home) }

    private fun setSelectedPageIndex(position: Int, smooth: Boolean = true) {
        viewPager.setCurrentItem(position, smooth)
    }

    fun openHomePage() {
        setSelectedPageIndex(pagerAdapter.getIndex(HomeFragment::class.java))
    }

    fun openPostPage() {
        setSelectedPageIndex(pagerAdapter.getIndex(PostFragment::class.java))
    }

    private fun openPostPageWithImage(uri: Uri) {
        try {
            val c = contentResolver.query(uri, null, null, null, null)!!
            c.moveToFirst()
            val path = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA))
            world.postState.beginTransaction()
                    .setMediaFilePath(path)
                    .commitWithOpen(this)
            world.notify(R.string.notice_select_image_succeeded)
            c.close()
        } catch (e: Exception) {
            e.printStackTrace()
            world.notifyError(R.string.notice_select_image_failed)
        }

    }

    fun openSearchPage(query: String) {
        val fragment = pagerAdapter.getCachedFragment(pagerAdapter.getIndex(SearchFragment::class.java)) as SearchFragment?
        if (fragment != null) {
            fragment.startSearch(query)
            setSelectedPageIndex(pagerAdapter.getIndex(SearchFragment::class.java))
        }
    }

    fun openUserListPage(listFullName: String) {
        val fragment = pagerAdapter.getCachedFragment(pagerAdapter.getIndex(UserListFragment::class.java)) as UserListFragment?
        if (fragment != null) {
            fragment.startUserList(listFullName)
            setSelectedPageIndex(pagerAdapter.getIndex(UserListFragment::class.java))
        }
    }

    private fun setTitle() {
        title = String.format("%s / %s", world.account.user.screenName, pagerAdapter.getName(viewPager.currentItem))
        val label = getString(R.string.app_name) + " - @" + world.account.user.screenName
        setTaskDescription(ActivityManager.TaskDescription(label))
        BitmapURLTask(world.account.user.profileImageUrl, currentAccountIconImageView).execute()
    }

    private fun processIntent(intent: Intent) {
        val uri = intent.getParcelableExtra<Uri>(KEY_ORIGINAL_DATA)
        if (uri != null){
            if (uri.host == "twitter.com") {
                // /share and /intent/tweet: don't accept status parameter
                val postMatcher = TWITTER_POST_PATTERN.matcher(uri.path)
                if (postMatcher.find()) {
                    var text = uri.getQueryParameter("text") ?: ""
                    val url = uri.getQueryParameter("url")
                    if (!TextUtils.isEmpty(url))
                        text += " " + url
                    val hashtags = uri.getQueryParameter("hashtags")
                    if (!TextUtils.isEmpty(hashtags))
                        text += " " + hashtags.trim { it <= ' ' }.replace(",".toRegex(), " #")
                    val via = uri.getQueryParameter("via")
                    if (!TextUtils.isEmpty(via))
                        text += " via @" + via
                    world.postState.beginTransaction().setText(text).commitWithOpen(this)
                    return
                }
                val statusMatcher = TWITTER_STATUS_PATTERN.matcher(uri.path)
                if (statusMatcher.find()) {
                    Tweet.fetchTask(java.lang.Long.parseLong(statusMatcher.group(1)), world.account)
                            .onDoneUI { tweet -> DialogHelper.showDialog(this, StatusDetailDialogFragment.newInstance(tweet)) }
                            .onFail { _ -> world.notifyError(R.string.error_intent_status_cannot_load) }
                            .execute()
                    return
                }
                val userMatcher = TWITTER_USER_PATTERN.matcher(uri.path)
                if (userMatcher.find()) {
                    Users.GetTask(world.account, userMatcher.group(1))
                            .onDoneUI { user ->
                                DialogHelper.showDialog(this, UserDetailDialogFragment.newInstance(user))
                            }
                            .onFail { _ -> world.notifyError(R.string.notice_error_show_user) }
                            .execute()
                    return
                }
            }
        } else when (intent.action) {
            Intent.ACTION_SEND -> {
                val type = intent.getStringExtra(KEY_ORIGINAL_TYPE)
                if (type == "text/plain") {
                    val extra = intent.extras
                    if (extra != null) {
                        var text = extra.getCharSequence(Intent.EXTRA_TEXT).toString()
                        if (!TextUtils.isEmpty(extra.getCharSequence(Intent.EXTRA_SUBJECT))) {
                            text = extra.getCharSequence(Intent.EXTRA_SUBJECT).toString() + " " + text
                        }
                        world.postState.beginTransaction().setText(text).commitWithOpen(this)
                        return
                    }
                } else if (type != null && type.startsWith("image/")) {
                    openPostPageWithImage(intent.getParcelableExtra(Intent.EXTRA_STREAM))
                }
            }
        }
    }

    // ------------------------ OVERRIDE METHODS ------------------------

    override fun onBackPressed() {
        this.finish()
    }

    override fun finish() {
        val homeIndex = pagerAdapter.getIndex(HomeFragment::class.java)
        if (viewPager.currentItem != homeIndex) {
            viewPager.setCurrentItem(homeIndex, true)
        } else {
            ConfirmDialogFragment.show(this, getString(R.string.dialog_confirm_finish_app)) { super.finish() }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            REQUEST_GET_PICTURE_FROM_GALLERY -> {
                if (resultCode != Activity.RESULT_OK) {
                    Logger.error(requestCode)
                    world.notifyError(R.string.notice_select_image_failed)
                    finish()
                    return
                }
                openPostPageWithImage(data!!.data)
            }
        }
    }

    public override fun onCreate(savedInstanceState: Bundle?) {
        Logger.debug("onCreate")
        super.onCreate(savedInstanceState)

        world.setMainActivity(this)

        // XXX
        val account = world.account

        setTheme(if (account.themeIndex == 0) R.style.theme_dark else R.style.theme_light)
        setContentView(R.layout.layout_main)

        viewPager.addOnPageChangeListener(this)
        actionBar.setDisplayHomeAsUpEnabled(true)
        currentAccountIconImageView.scaleType = ImageView.ScaleType.FIT_XY

        // TODO: tab order?
        val args = Bundle()
        args.putLong(PageFragment.KEY_USER_ID, account.userId)
        pagerAdapter.addPage(PostFragment::class.java, getString(R.string.page_name_post), args, false)
        pagerAdapter.addPage(HomeFragment::class.java, getString(R.string.page_name_home), args, false)
        pagerAdapter.addPage(MentionsFragment::class.java, getString(R.string.page_name_mentions), args, false)
        pagerAdapter.addPage(HistoryFragment::class.java, getString(R.string.page_name_history), args, false)
        pagerAdapter.addPage(MessagesFragment::class.java, getString(R.string.page_name_messages), args, false)
        pagerAdapter.addPage(SearchFragment::class.java, getString(R.string.page_name_search), args, false)
        pagerAdapter.addPage(UserListFragment::class.java, getString(R.string.page_name_list), args, false)
        pagerAdapter.notifyDataSetChanged()
        viewPager.offscreenPageLimit = pagerAdapter.count
        viewPager.adapter = pagerAdapter
        setSelectedPageIndex(pagerAdapter.getIndex(HomeFragment::class.java), false)

        ExtractionWord.load()

        // update cache
        world.refreshListSubscriptions()
        world.refreshUserMuteList()
        world.refreshSavedSearches()
        Users.GetTask(account, account.userId).onDoneUI { setTitle() }.execute()

        // Set application title
        setTitle()

        // refresh all pages
        for (i in 0 until pagerAdapter.count) {
            val pf = pagerAdapter.getCachedFragment(i)
            if (pf != null && pf.isAdded) {
                Logger.debug(String.format("PageFragment %s is already attached; refreshing", pf.javaClass.name))
                pf.refresh()
            }
        }

        // start user stream
        world.setupStreaming()

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    override fun onDestroy() {
        Crouton.cancelAllCroutons()
        // Workaround for LeakCanary
        fixCroutonLeak()
        Logger.debug("onDestroy")
        super.onDestroy()
    }

    private fun fixCroutonLeak() {
        try {
            val klass = Class.forName("de.keyboardsurfer.android.widget.crouton.DefaultAnimationsBuilder")
            val slideInDownAnimation = klass.getDeclaredField("slideInDownAnimation")
            slideInDownAnimation.isAccessible = true
            slideInDownAnimation.set(null, null)
            val slideOutUpAnimation = klass.getDeclaredField("slideOutUpAnimation")
            slideOutUpAnimation.isAccessible = true
            slideOutUpAnimation.set(null, null)
        } catch (e: Exception) {
            Logger.error("crouton fix error: " + e)
        }
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home ->
                startActivity<ManageAccountsActivity>(ManageAccountsActivity.INTENT_KEY_NOINIT to true)
            R.id.actionbar_setting -> startActivity<SettingActivity>()
            R.id.actionbar_edit_extraction -> startActivity<EditExtractionActivity>()
            R.id.actionbar_aclog -> browse(world.account.user.aclogTimelineURL)
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    override fun onPause() {
        Logger.debug("onPause")
        super.onPause()
        world.setMainActivityActive(false)
    }

    override fun onResume() {
        Logger.debug("onResume")
        super.onResume()
        Application.currentWorld = world
        world.setMainActivityActive(true)
        val intent = world.mainActivityIntent
        if (intent != null) {
            world.mainActivityIntent = null
            processIntent(intent)
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        // With the current releases (~ 7) of Android, onNewIntent() doesn't seem to be called properly
        if (false) processIntent(intent)
    }

    // --------------------- Interface OnPageChangeListener ---------------------

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

    override fun onPageSelected(position: Int) {
        Logger.debug("Page selected: " + position)
        setTitle()
    }

    override fun onPageScrollStateChanged(state: Int) {}

    companion object {
        val REQUEST_GET_PICTURE_FROM_GALLERY = 11
        val KEY_ORIGINAL_DATA = "originalData"
        val KEY_ORIGINAL_TYPE = "originalType"
        private val TWITTER_POST_PATTERN = Pattern.compile("\\A/(intent/tweet|share)\\z", Pattern.CASE_INSENSITIVE)
        private val TWITTER_STATUS_PATTERN = Pattern.compile("\\A(?:/#!)?/(?:\\w{1,15})/status(?:es)?/(\\d+)\\z", Pattern.CASE_INSENSITIVE)
        private val TWITTER_USER_PATTERN = Pattern.compile("\\A(?:/#!)?/(\\w{1,15})/?\\z", Pattern.CASE_INSENSITIVE)

    }
}