aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/activities/LoginActivity.kt
blob: 949f1ddd114ac96d0cfa9f5aad4e1e9d91a81f31 (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
/*
 * 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.activities

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.Toolbar
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import ca.allanwang.kau.utils.bindView
import ca.allanwang.kau.utils.fadeIn
import ca.allanwang.kau.utils.fadeOut
import ca.allanwang.kau.utils.withMainContext
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.pitchedapps.frost.R
import com.pitchedapps.frost.db.CookieDao
import com.pitchedapps.frost.db.CookieEntity
import com.pitchedapps.frost.db.save
import com.pitchedapps.frost.db.selectAll
import com.pitchedapps.frost.facebook.FbItem
import com.pitchedapps.frost.facebook.profilePictureUrl
import com.pitchedapps.frost.glide.FrostGlide
import com.pitchedapps.frost.glide.GlideApp
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.frostEvent
import com.pitchedapps.frost.utils.frostJsoup
import com.pitchedapps.frost.utils.launchNewTask
import com.pitchedapps.frost.utils.logFrostEvent
import com.pitchedapps.frost.utils.uniqueOnly
import com.pitchedapps.frost.web.LoginWebView
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.net.UnknownHostException
import javax.inject.Inject
import kotlin.coroutines.resume

/**
 * Created by Allan Wang on 2017-06-01.
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity() {

    @Inject
    lateinit var cookieDao: CookieDao

    private val toolbar: Toolbar by bindView(R.id.toolbar)
    private val web: LoginWebView by bindView(R.id.login_webview)
    private val swipeRefresh: SwipeRefreshLayout by bindView(R.id.swipe_refresh)
    private val textview: AppCompatTextView by bindView(R.id.textview)
    private val profile: ImageView by bindView(R.id.profile)

    private lateinit var profileLoader: RequestManager
    private val refreshChannel = Channel<Boolean>(10)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setSupportActionBar(toolbar)
        setTitle(R.string.kau_login)
        activityThemer.setFrostColors {
            toolbar(toolbar)
        }
        profileLoader = GlideApp.with(profile)
        launch {
            for (refreshing in refreshChannel.uniqueOnly(this)) {
                swipeRefresh.isRefreshing = refreshing
            }
        }
        launch {
            val cookie = web.loadLogin { refresh(it != 100) }.await()
            L.d { "Login found" }
            fbCookie.save(cookie.id)
            webFadeOut()
            profile.fadeIn()
            loadInfo(cookie)
        }
    }

    private suspend fun webFadeOut(): Unit = suspendCancellableCoroutine { cont ->
        web.fadeOut { cont.resume(Unit) }
    }

    private fun refresh(refreshing: Boolean) {
        refreshChannel.offer(refreshing)
    }

    private suspend fun loadInfo(cookie: CookieEntity): Unit = withMainContext {
        refresh(true)

        val imageDeferred = async { loadProfile(cookie.id) }
        val nameDeferred = async { loadUsername(cookie) }

        val name: String? = nameDeferred.await()
        val foundImage: Boolean = imageDeferred.await()

        L._d { "Logged in and received data" }
        refresh(false)

        if (!foundImage) {
            L.e { "Could not get profile photo; Invalid userId?" }
            L._i { cookie }
        }

        textview.text = String.format(getString(R.string.welcome), name ?: "")
        textview.fadeIn()
        frostEvent("Login", "success" to true)

        /*
         * The user may have logged into an account that is already in the database
         * We will let the db handle duplicates and load it now after the new account has been saved
         */
        val cookies = ArrayList(cookieDao.selectAll())
        delay(1000)
        if (prefs.intro)
            launchNewTask<IntroActivity>(cookies, true)
        else
            launchNewTask<MainActivity>(cookies, true)
    }

    private suspend fun loadProfile(id: Long): Boolean = withMainContext {
        suspendCancellableCoroutine<Boolean> { cont ->
            profileLoader.load(profilePictureUrl(id))
                .transform(FrostGlide.circleCrop).listener(object : RequestListener<Drawable> {
                    override fun onResourceReady(
                        resource: Drawable?,
                        model: Any?,
                        target: Target<Drawable>?,
                        dataSource: DataSource?,
                        isFirstResource: Boolean
                    ): Boolean {
                        cont.resume(true)
                        return false
                    }

                    override fun onLoadFailed(
                        e: GlideException?,
                        model: Any?,
                        target: Target<Drawable>?,
                        isFirstResource: Boolean
                    ): Boolean {
                        e.logFrostEvent("Profile loading exception")
                        cont.resume(false)
                        return false
                    }
                }).into(profile)
        }
    }

    private suspend fun loadUsername(cookie: CookieEntity): String? = withContext(Dispatchers.IO) {
        val result: String? = try {
            withTimeout(5000) {
                frostJsoup(cookie.cookie, FbItem.PROFILE.url).title()
            }
        } catch (e: Exception) {
            if (e !is UnknownHostException)
                e.logFrostEvent("Fetch username failed")
            null
        }

        if (result != null) {
            cookieDao.save(cookie.copy(name = result))
            return@withContext result
        }

        return@withContext cookie.name
    }

    override fun backConsumer(): Boolean {
        if (web.canGoBack()) {
            web.goBack()
            return true
        }
        return false
    }

    override fun onResume() {
        super.onResume()
        web.resumeTimers()
    }

    override fun onPause() {
        web.pauseTimers()
        super.onPause()
    }
}