aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/kotlin/com/pitchedapps/frost/facebook/FbCookie.kt
blob: ab041adcd0a76750952b0f3f7c057d0cb0d387bf (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
/*
 * 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.facebook

import android.app.Activity
import android.content.Context
import android.webkit.CookieManager
import com.pitchedapps.frost.db.CookieDao
import com.pitchedapps.frost.db.CookieEntity
import com.pitchedapps.frost.db.deleteById
import com.pitchedapps.frost.db.save
import com.pitchedapps.frost.db.selectById
import com.pitchedapps.frost.prefs.Prefs
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.cookies
import com.pitchedapps.frost.utils.launchLogin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext
import javax.inject.Inject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 * Created by Allan Wang on 2017-05-30.
 *
 * The following component manages all cookie transfers.
 */
class FbCookie @Inject internal constructor(
    private val prefs: Prefs,
    private val cookieDao: CookieDao
) {

    companion object {
        /**
         * Domain information. Dot prefix still matters for Android browsers.
         */
        private const val FB_COOKIE_DOMAIN = ".$FACEBOOK_COM"
        private const val MESSENGER_COOKIE_DOMAIN = ".$MESSENGER_COM"
    }

    /**
     * Retrieves the facebook cookie if it exists
     * Note that this is a synchronized call
     */
    val webCookie: String?
        get() = CookieManager.getInstance().getCookie(HTTPS_FACEBOOK_COM)

    val messengerCookie: String?
        get() = CookieManager.getInstance().getCookie(HTTPS_MESSENGER_COM)

    private suspend fun CookieManager.suspendSetWebCookie(
        domain: String,
        cookie: String?
    ): Boolean {
        cookie ?: return true
        return withContext(NonCancellable) {
            // Save all cookies regardless of result, then check if all succeeded
            val result = cookie.split(";")
                .map { async { setSingleWebCookie(domain, it) } }
                .awaitAll().all { it }
            L.d { "Cookies set" }
            L._d { "Set $cookie\n\tResult $webCookie" }
            result
        }
    }

    private suspend fun CookieManager.setSingleWebCookie(domain: String, cookie: String): Boolean =
        suspendCoroutine { cont ->
            setCookie(domain, cookie.trim()) {
                cont.resume(it)
            }
        }

    private suspend fun CookieManager.removeAllCookies(): Boolean = suspendCoroutine { cont ->
        removeAllCookies {
            cont.resume(it)
        }
    }

    suspend fun save(id: Long) {
        L.d { "New cookie found" }
        prefs.userId = id
        CookieManager.getInstance().flush()
        val cookie = CookieEntity(prefs.userId, null, webCookie)
        cookieDao.save(cookie)
    }

    suspend fun reset() {
        prefs.userId = -1L
        withContext(Dispatchers.Main + NonCancellable) {
            with(CookieManager.getInstance()) {
                removeAllCookies()
                flush()
            }
        }
    }

    suspend fun switchUser(id: Long) {
        val cookie = cookieDao.selectById(id) ?: return L.e { "No cookie for id" }
        switchUser(cookie)
    }

    suspend fun switchUser(cookie: CookieEntity?) {
        if (cookie?.cookie == null) {
            L.d { "Switching User; null cookie" }
            return
        }
        withContext(Dispatchers.Main + NonCancellable) {
            L.d { "Switching User" }
            prefs.userId = cookie.id
            CookieManager.getInstance().apply {
                removeAllCookies()
                suspendSetWebCookie(FB_COOKIE_DOMAIN, cookie.cookie)
                suspendSetWebCookie(MESSENGER_COOKIE_DOMAIN, cookie.cookieMessenger)
                flush()
            }
        }
    }

    /**
     * Helper function to remove the current cookies
     * and launch the proper login page
     */
    suspend fun logout(context: Context, deleteCookie: Boolean = true) {
        val cookies = arrayListOf<CookieEntity>()
        if (context is Activity)
            cookies.addAll(context.cookies().filter { it.id != prefs.userId })
        logout(prefs.userId, deleteCookie)
        context.launchLogin(cookies, true)
    }

    /**
     * Clear the cookies of the given id
     */
    suspend fun logout(id: Long, deleteCookie: Boolean = true) {
        L.d { "Logging out user" }
        if (deleteCookie) {
            cookieDao.deleteById(id)
            L.d { "Fb cookie deleted" }
            L._d { id }
        }
        reset()
    }

    /**
     * Notifications may come from different accounts, and we need to switch the cookies to load them
     * When coming back to the main app, switch back to our original account before continuing
     */
    suspend fun switchBackUser() {
        if (prefs.prevId == -1L) return
        val prevId = prefs.prevId
        prefs.prevId = -1L
        if (prevId != prefs.userId) {
            switchUser(prevId)
            L.d { "Switch back user" }
            L._d { "${prefs.userId} to $prevId" }
        }
    }
}