From 65bb9233b2a0d8734c1d13e8f3a01bee0f6c3b17 Mon Sep 17 00:00:00 2001 From: Allan Wang Date: Tue, 5 Mar 2019 21:06:24 -0500 Subject: Convert fbcookies to room entities --- app/build.gradle | 6 +-- .../main/kotlin/com/pitchedapps/frost/FrostApp.kt | 3 ++ .../kotlin/com/pitchedapps/frost/StartActivity.kt | 19 ++++++-- .../frost/activities/BaseMainActivity.kt | 54 +++++++++++++--------- .../pitchedapps/frost/activities/LoginActivity.kt | 15 +++--- .../kotlin/com/pitchedapps/frost/db/CookiesDb.kt | 50 ++++---------------- .../kotlin/com/pitchedapps/frost/db/Database.kt | 14 ++++++ .../com/pitchedapps/frost/facebook/FbCookie.kt | 31 ++++++++----- .../frost/facebook/parsers/FrostParser.kt | 3 +- .../frost/facebook/parsers/MessageParser.kt | 3 +- .../frost/facebook/parsers/NotifParser.kt | 3 +- .../frost/services/FrostNotifications.kt | 7 +-- .../frost/services/NotificationService.kt | 11 +++-- .../pitchedapps/frost/settings/Notifications.kt | 11 +++-- .../com/pitchedapps/frost/utils/Downloader.kt | 7 +-- .../kotlin/com/pitchedapps/frost/utils/Utils.kt | 10 ++-- .../com/pitchedapps/frost/views/AccountItem.kt | 4 +- .../pitchedapps/frost/views/FrostVideoViewer.kt | 11 ++++- .../kotlin/com/pitchedapps/frost/web/FrostJSI.kt | 3 +- .../com/pitchedapps/frost/web/LoginWebView.kt | 16 ++++--- 20 files changed, 158 insertions(+), 123 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 82f0c6b1..d5dcf87e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -204,9 +204,9 @@ dependencies { implementation "androidx.core:core-ktx:${KTX}" -// implementation "org.koin:koin-android:${KOIN}" -// testImplementation "org.koin:koin-test:${KOIN}" -// androidTestImplementation "org.koin:koin-test:${KOIN}" + implementation "org.koin:koin-android:${KOIN}" + testImplementation "org.koin:koin-test:${KOIN}" + androidTestImplementation "org.koin:koin-test:${KOIN}" // androidTestImplementation "io.mockk:mockk:${MOCKK}" diff --git a/app/src/main/kotlin/com/pitchedapps/frost/FrostApp.kt b/app/src/main/kotlin/com/pitchedapps/frost/FrostApp.kt index ba92a345..7669ef46 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/FrostApp.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/FrostApp.kt @@ -31,6 +31,7 @@ import com.mikepenz.materialdrawer.util.AbstractDrawerImageLoader import com.mikepenz.materialdrawer.util.DrawerImageLoader import com.pitchedapps.frost.db.CookiesDb import com.pitchedapps.frost.db.FbTabsDb +import com.pitchedapps.frost.db.FrostDatabase import com.pitchedapps.frost.db.NotificationDb import com.pitchedapps.frost.glide.GlideApp import com.pitchedapps.frost.services.scheduleNotifications @@ -44,6 +45,7 @@ import com.raizlabs.android.dbflow.config.DatabaseConfig import com.raizlabs.android.dbflow.config.FlowConfig import com.raizlabs.android.dbflow.config.FlowManager import com.raizlabs.android.dbflow.runtime.ContentResolverNotifier +import org.koin.android.ext.android.startKoin import java.util.Random import kotlin.reflect.KClass @@ -132,6 +134,7 @@ class FrostApp : Application() { L.d { "Activity ${activity.localClassName} created" } } }) + startKoin(this, listOf(FrostDatabase.module(this))) } private fun initBugsnag() { diff --git a/app/src/main/kotlin/com/pitchedapps/frost/StartActivity.kt b/app/src/main/kotlin/com/pitchedapps/frost/StartActivity.kt index 86596843..fe859f95 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/StartActivity.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/StartActivity.kt @@ -32,6 +32,8 @@ import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.pitchedapps.frost.activities.LoginActivity import com.pitchedapps.frost.activities.MainActivity import com.pitchedapps.frost.activities.SelectorActivity +import com.pitchedapps.frost.db.CookieDao +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.db.loadFbCookiesSync import com.pitchedapps.frost.facebook.FbCookie @@ -43,6 +45,7 @@ import com.pitchedapps.frost.utils.loadAssets import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import org.koin.android.ext.android.inject import java.util.ArrayList /** @@ -50,6 +53,8 @@ import java.util.ArrayList */ class StartActivity : KauBaseActivity() { + private val cookieDao: CookieDao by inject() + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -67,12 +72,11 @@ class StartActivity : KauBaseActivity() { launch { try { + migrate() FbCookie.switchBackUser() - val cookies = ArrayList(withContext(Dispatchers.IO) { - loadFbCookiesSync() - }) + val cookies = ArrayList(cookieDao.selectAll()) L.i { "Cookies loaded at time ${System.currentTimeMillis()}" } - L._d { "Cookies: ${cookies.joinToString("\t", transform = CookieModel::toSensitiveString)}" } + L._d { "Cookies: ${cookies.joinToString("\t", transform = CookieEntity::toSensitiveString)}" } loadAssets() when { cookies.isEmpty() -> launchNewTask() @@ -90,6 +94,13 @@ class StartActivity : KauBaseActivity() { } } + /** + * Migrate from dbflow to room + */ + private suspend fun migrate() { + + } + private fun showInvalidWebView() = showInvalidView(R.string.error_webview) diff --git a/app/src/main/kotlin/com/pitchedapps/frost/activities/BaseMainActivity.kt b/app/src/main/kotlin/com/pitchedapps/frost/activities/BaseMainActivity.kt index 33fc2078..4669418d 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/activities/BaseMainActivity.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/activities/BaseMainActivity.kt @@ -69,9 +69,11 @@ import com.pitchedapps.frost.contracts.FileChooserContract import com.pitchedapps.frost.contracts.FileChooserDelegate import com.pitchedapps.frost.contracts.MainActivityContract import com.pitchedapps.frost.contracts.VideoViewHolder +import com.pitchedapps.frost.db.CookieDao +import com.pitchedapps.frost.db.FbTabDao import com.pitchedapps.frost.db.TAB_COUNT -import com.pitchedapps.frost.db.loadFbCookie -import com.pitchedapps.frost.db.loadFbTabs +import com.pitchedapps.frost.db.currentCookie +import com.pitchedapps.frost.db.selectAll import com.pitchedapps.frost.enums.MainActivityLayout import com.pitchedapps.frost.facebook.FbCookie import com.pitchedapps.frost.facebook.FbItem @@ -109,6 +111,7 @@ import kotlinx.android.synthetic.main.view_main_toolbar.* import kotlinx.android.synthetic.main.view_main_viewpager.* import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch +import org.koin.android.ext.android.inject /** * Created by Allan Wang on 20/12/17. @@ -123,6 +126,8 @@ abstract class BaseMainActivity : BaseActivity(), MainActivityContract, protected lateinit var adapter: SectionsPagerAdapter override val frameWrapper: FrameLayout get() = frame_wrapper val viewPager: FrostViewPager get() = container + val cookieDao: CookieDao by inject() + val tabDao: FbTabDao by inject() /* * Components with the same id in multiple layout files @@ -151,9 +156,11 @@ abstract class BaseMainActivity : BaseActivity(), MainActivityContract, background(viewPager) } setSupportActionBar(toolbar) - adapter = SectionsPagerAdapter(loadFbTabs()) - viewPager.adapter = adapter - viewPager.offscreenPageLimit = TAB_COUNT + launch { + adapter = SectionsPagerAdapter(tabDao.selectAll()) + viewPager.adapter = adapter + viewPager.offscreenPageLimit = TAB_COUNT + } tabs.setBackgroundColor(Prefs.mainActivityLayout.backgroundColor()) onNestedCreate(savedInstanceState) L.i { "Main finished loading UI in ${System.currentTimeMillis() - start} ms" } @@ -274,27 +281,28 @@ abstract class BaseMainActivity : BaseActivity(), MainActivityContract, if (current) launchWebOverlay(FbItem.PROFILE.url) else when (profile.identifier) { -2L -> { - val currentCookie = loadFbCookie(Prefs.userId) - if (currentCookie == null) { - toast(R.string.account_not_found) - launch { + // TODO no backpressure support + launch { + val currentCookie = cookieDao.currentCookie() + if (currentCookie == null) { + toast(R.string.account_not_found) FbCookie.reset() launchLogin(cookies(), true) - } - } else { - materialDialogThemed { - title(R.string.kau_logout) - content( - String.format( - string(R.string.kau_logout_confirm_as_x), currentCookie.name - ?: Prefs.userId.toString() + } else { + materialDialogThemed { + title(R.string.kau_logout) + content( + String.format( + string(R.string.kau_logout_confirm_as_x), + currentCookie.name ?: Prefs.userId.toString() + ) ) - ) - positiveText(R.string.kau_yes) - negativeText(R.string.kau_no) - onPositive { _, _ -> - launch { - FbCookie.logout(this@BaseMainActivity) + positiveText(R.string.kau_yes) + negativeText(R.string.kau_no) + onPositive { _, _ -> + this@BaseMainActivity.launch { + FbCookie.logout(this@BaseMainActivity) + } } } } diff --git a/app/src/main/kotlin/com/pitchedapps/frost/activities/LoginActivity.kt b/app/src/main/kotlin/com/pitchedapps/frost/activities/LoginActivity.kt index 7ff22a5a..5649cc73 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/activities/LoginActivity.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/activities/LoginActivity.kt @@ -32,9 +32,8 @@ 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.CookieModel -import com.pitchedapps.frost.db.loadFbCookiesSuspend -import com.pitchedapps.frost.db.saveFbCookie +import com.pitchedapps.frost.db.CookieDao +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.facebook.FbCookie import com.pitchedapps.frost.facebook.FbItem import com.pitchedapps.frost.facebook.profilePictureUrl @@ -58,6 +57,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import org.koin.android.ext.android.inject import java.net.UnknownHostException import kotlin.coroutines.resume @@ -71,6 +71,7 @@ class LoginActivity : BaseActivity() { 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 val cookieDao: CookieDao by inject() private lateinit var profileLoader: RequestManager private val refreshChannel = Channel(10) @@ -109,7 +110,7 @@ class LoginActivity : BaseActivity() { refreshChannel.offer(refreshing) } - private suspend fun loadInfo(cookie: CookieModel): Unit = withMainContext { + private suspend fun loadInfo(cookie: CookieEntity): Unit = withMainContext { refresh(true) val imageDeferred = async { loadProfile(cookie.id) } @@ -134,7 +135,7 @@ class LoginActivity : BaseActivity() { * 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(loadFbCookiesSuspend()) + val cookies = ArrayList(cookieDao.selectAll()) delay(1000) if (Showcase.intro) launchNewTask(cookies, true) @@ -171,7 +172,7 @@ class LoginActivity : BaseActivity() { } } - private suspend fun loadUsername(cookie: CookieModel): String = withContext(Dispatchers.IO) { + private suspend fun loadUsername(cookie: CookieEntity): String = withContext(Dispatchers.IO) { val result: String = try { withTimeout(5000) { frostJsoup(cookie.cookie, FbItem.PROFILE.url).title() @@ -184,7 +185,7 @@ class LoginActivity : BaseActivity() { if (cookie.name?.isNotBlank() == false && result != cookie.name) { cookie.name = result - saveFbCookie(cookie) + cookieDao.insertCookie(cookie) } cookie.name ?: "" diff --git a/app/src/main/kotlin/com/pitchedapps/frost/db/CookiesDb.kt b/app/src/main/kotlin/com/pitchedapps/frost/db/CookiesDb.kt index 9deb57da..fb240fd3 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/db/CookiesDb.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/db/CookiesDb.kt @@ -23,6 +23,7 @@ import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.pitchedapps.frost.utils.L +import com.pitchedapps.frost.utils.Prefs import com.raizlabs.android.dbflow.annotation.ConflictAction import com.raizlabs.android.dbflow.annotation.Database import com.raizlabs.android.dbflow.annotation.PrimaryKey @@ -48,12 +49,12 @@ import kotlinx.coroutines.withContext data class CookieEntity( @androidx.room.PrimaryKey var id: Long, - var name: String, - var cookie: String + var name: String?, + var cookie: String? ) : Parcelable { - override fun toString(): String = "CookieModel(${hashCode()})" + override fun toString(): String = "CookieEntity(${hashCode()})" - fun toSensitiveString(): String = "CookieModel(id=$id, name=$name, cookie=$cookie)" + fun toSensitiveString(): String = "CookieEntity(id=$id, name=$name, cookie=$cookie)" } @Dao @@ -72,6 +73,8 @@ interface CookieDao { suspend fun deleteById(id: Long) } +suspend fun CookieDao.currentCookie() = selectById(Prefs.userId) + @Database(version = CookiesDb.VERSION) object CookiesDb { const val NAME = "Cookies" @@ -86,41 +89,4 @@ data class CookieModel(@PrimaryKey var id: Long = -1L, var name: String? = null, override fun toString(): String = "CookieModel(${hashCode()})" fun toSensitiveString(): String = "CookieModel(id=$id, name=$name, cookie=$cookie)" -} - -fun loadFbCookie(id: Long): CookieModel? = - (select from CookieModel::class where (CookieModel_Table.id eq id)).querySingle() - -fun loadFbCookie(name: String): CookieModel? = - (select from CookieModel::class where (CookieModel_Table.name eq name)).querySingle() - -/** - * Loads cookies sorted by name - */ -fun loadFbCookiesAsync(callback: (cookies: List) -> Unit) { - (select from CookieModel::class).orderBy(CookieModel_Table.name, true).async() - .queryListResultCallback { _, tResult -> callback(tResult) }.execute() -} - -fun loadFbCookiesSync(): List = - (select from CookieModel::class).orderBy(CookieModel_Table.name, true).queryList() - -// TODO temp method until dbflow supports coroutines -suspend fun loadFbCookiesSuspend(): List = withContext(Dispatchers.IO) { - loadFbCookiesSync() -} - -inline fun saveFbCookie(cookie: CookieModel, crossinline callback: (() -> Unit) = {}) { - cookie.async save { - L.d { "Fb cookie saved" } - L._d { cookie.toSensitiveString() } - callback() - } -} - -fun removeCookie(id: Long) { - loadFbCookie(id)?.async?.delete { - L.d { "Fb cookie deleted" } - L._d { id } - } -} +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/pitchedapps/frost/db/Database.kt b/app/src/main/kotlin/com/pitchedapps/frost/db/Database.kt index 34de5e07..161ed93d 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/db/Database.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/db/Database.kt @@ -5,6 +5,8 @@ import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters +import org.koin.dsl.module.module +import org.koin.standalone.StandAloneContext interface FrostPrivateDao { fun cookieDao(): CookieDao @@ -58,5 +60,17 @@ class FrostDatabase(private val privateDb: FrostPrivateDatabase, private val pub ).build() return FrostDatabase(privateDb, publicDb) } + + fun module(context: Context) = module { + single { create(context) } + single { get().cookieDao() } + single { get().tabDao() } + } + + /** + * Get from koin + * For the most part, you can retrieve directly from other koin components + */ + fun get(): FrostDatabase = StandAloneContext.getKoin().koinContext.get() } } diff --git a/app/src/main/kotlin/com/pitchedapps/frost/facebook/FbCookie.kt b/app/src/main/kotlin/com/pitchedapps/frost/facebook/FbCookie.kt index 349b415c..6f79da43 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/facebook/FbCookie.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/facebook/FbCookie.kt @@ -19,10 +19,10 @@ package com.pitchedapps.frost.facebook import android.app.Activity import android.content.Context import android.webkit.CookieManager -import com.pitchedapps.frost.db.CookieModel -import com.pitchedapps.frost.db.loadFbCookie +import com.pitchedapps.frost.db.CookieDao +import com.pitchedapps.frost.db.CookieEntity +import com.pitchedapps.frost.db.FrostDatabase import com.pitchedapps.frost.db.removeCookie -import com.pitchedapps.frost.db.saveFbCookie import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.Prefs import com.pitchedapps.frost.utils.cookies @@ -50,6 +50,10 @@ object FbCookie { inline val webCookie: String? get() = CookieManager.getInstance().getCookie(COOKIE_DOMAIN) + private val cookieDao: CookieDao by lazy { + FrostDatabase.get().cookieDao() + } + private suspend fun CookieManager.suspendSetWebCookie(cookie: String?): Boolean { cookie ?: return true return withContext(NonCancellable) { @@ -77,12 +81,12 @@ object FbCookie { } } - fun save(id: Long) { + suspend fun save(id: Long) { L.d { "New cookie found" } Prefs.userId = id CookieManager.getInstance().flush() - val cookie = CookieModel(Prefs.userId, "", webCookie) - saveFbCookie(cookie) + val cookie = CookieEntity(Prefs.userId, null, webCookie) + cookieDao.insertCookie(cookie) } suspend fun reset() { @@ -93,11 +97,12 @@ object FbCookie { } } - suspend fun switchUser(id: Long) = switchUser(loadFbCookie(id)) - - suspend fun switchUser(name: String) = switchUser(loadFbCookie(name)) + suspend fun switchUser(id: Long) { + val cookie = cookieDao.selectById(id) ?: return L.e { "No cookie for id" } + switchUser(cookie) + } - suspend fun switchUser(cookie: CookieModel?) { + suspend fun switchUser(cookie: CookieEntity?) { if (cookie == null) { L.d { "Switching User; null cookie" } return @@ -114,7 +119,7 @@ object FbCookie { * and launch the proper login page */ suspend fun logout(context: Context) { - val cookies = arrayListOf() + val cookies = arrayListOf() if (context is Activity) cookies.addAll(context.cookies().filter { it.id != Prefs.userId }) logout(Prefs.userId) @@ -126,7 +131,9 @@ object FbCookie { */ suspend fun logout(id: Long) { L.d { "Logging out user" } - removeCookie(id) + cookieDao.deleteById(id) + L.d { "Fb cookie deleted" } + L._d { id } reset() } diff --git a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/FrostParser.kt b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/FrostParser.kt index 57e7cc94..bf89a103 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/FrostParser.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/FrostParser.kt @@ -16,6 +16,7 @@ */ package com.pitchedapps.frost.facebook.parsers +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.facebook.FB_CSS_URL_MATCHER import com.pitchedapps.frost.facebook.formattedFbUrl @@ -81,7 +82,7 @@ data class ParseResponse(val cookie: String, val data: T) { } interface ParseNotification { - fun getUnreadNotifications(data: CookieModel): List + fun getUnreadNotifications(data: CookieEntity): List } internal fun List.toJsonString(tag: String, indent: Int) = StringBuilder().apply { diff --git a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/MessageParser.kt b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/MessageParser.kt index b2b59234..866cab10 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/MessageParser.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/MessageParser.kt @@ -16,6 +16,7 @@ */ package com.pitchedapps.frost.facebook.parsers +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.facebook.FB_EPOCH_MATCHER import com.pitchedapps.frost.facebook.FB_MESSAGE_NOTIF_ID_MATCHER @@ -54,7 +55,7 @@ data class FrostMessages( append("}") }.toString() - override fun getUnreadNotifications(data: CookieModel) = + override fun getUnreadNotifications(data: CookieEntity) = threads.asSequence().filter(FrostThread::unread).map { with(it) { NotificationContent( diff --git a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/NotifParser.kt b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/NotifParser.kt index 0474e35e..3449ac48 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/NotifParser.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/NotifParser.kt @@ -16,6 +16,7 @@ */ package com.pitchedapps.frost.facebook.parsers +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.facebook.FB_EPOCH_MATCHER import com.pitchedapps.frost.facebook.FB_NOTIF_ID_MATCHER @@ -43,7 +44,7 @@ data class FrostNotifs( append("}") }.toString() - override fun getUnreadNotifications(data: CookieModel) = + override fun getUnreadNotifications(data: CookieEntity) = notifs.asSequence().filter(FrostNotif::unread).map { with(it) { NotificationContent( diff --git a/app/src/main/kotlin/com/pitchedapps/frost/services/FrostNotifications.kt b/app/src/main/kotlin/com/pitchedapps/frost/services/FrostNotifications.kt index 994f9a18..abd871b3 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/services/FrostNotifications.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/services/FrostNotifications.kt @@ -31,6 +31,7 @@ import ca.allanwang.kau.utils.string import com.pitchedapps.frost.BuildConfig import com.pitchedapps.frost.R import com.pitchedapps.frost.activities.FrostWebActivity +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.db.NotificationModel import com.pitchedapps.frost.db.lastNotificationTime @@ -116,7 +117,7 @@ enum class NotificationType( * Returns the number of notifications generated, * or -1 if an error occurred */ - fun fetch(context: Context, data: CookieModel): Int { + fun fetch(context: Context, data: CookieEntity): Int { val response = try { parser.parse(data.cookie) } catch (ignored: Exception) { @@ -161,7 +162,7 @@ enum class NotificationType( return notifs.size } - fun debugNotification(context: Context, data: CookieModel) { + fun debugNotification(context: Context, data: CookieEntity) { val content = NotificationContent( data, System.currentTimeMillis(), @@ -247,7 +248,7 @@ enum class NotificationType( * Notification data holder */ data class NotificationContent( - val data: CookieModel, + val data: CookieEntity, val id: Long, val href: String, val title: String? = null, // defaults to frost title diff --git a/app/src/main/kotlin/com/pitchedapps/frost/services/NotificationService.kt b/app/src/main/kotlin/com/pitchedapps/frost/services/NotificationService.kt index a895900f..088d8e0a 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/services/NotificationService.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/services/NotificationService.kt @@ -21,8 +21,8 @@ import androidx.core.app.NotificationManagerCompat import ca.allanwang.kau.utils.string import com.pitchedapps.frost.BuildConfig import com.pitchedapps.frost.R -import com.pitchedapps.frost.db.CookieModel -import com.pitchedapps.frost.db.loadFbCookiesSync +import com.pitchedapps.frost.db.CookieDao +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.Prefs import com.pitchedapps.frost.utils.frostEvent @@ -31,6 +31,7 @@ import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.yield +import org.koin.android.ext.android.inject /** * Created by Allan Wang on 2017-06-14. @@ -42,6 +43,8 @@ import kotlinx.coroutines.yield */ class NotificationService : BaseJobService() { + val cookieDao: CookieDao by inject() + override fun onStopJob(params: JobParameters?): Boolean { super.onStopJob(params) prepareFinish(true) @@ -81,7 +84,7 @@ class NotificationService : BaseJobService() { private suspend fun sendNotifications(params: JobParameters?): Unit = withContext(Dispatchers.Default) { val currentId = Prefs.userId - val cookies = loadFbCookiesSync() + val cookies = cookieDao.selectAll() yield() val jobId = params?.extras?.getInt(NOTIFICATION_PARAM_ID, -1) ?: -1 var notifCount = 0 @@ -107,7 +110,7 @@ class NotificationService : BaseJobService() { * Implemented fetch to also notify when an error occurs * Also normalized the output to return the number of notifications received */ - private fun fetch(jobId: Int, type: NotificationType, cookie: CookieModel): Int { + private fun fetch(jobId: Int, type: NotificationType, cookie: CookieEntity): Int { val count = type.fetch(this, cookie) if (count < 0) { if (jobId == NOTIFICATION_JOB_NOW) diff --git a/app/src/main/kotlin/com/pitchedapps/frost/settings/Notifications.kt b/app/src/main/kotlin/com/pitchedapps/frost/settings/Notifications.kt index 774b0e7f..3444d0b0 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/settings/Notifications.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/settings/Notifications.kt @@ -29,14 +29,15 @@ import ca.allanwang.kau.utils.string import com.pitchedapps.frost.BuildConfig import com.pitchedapps.frost.R import com.pitchedapps.frost.activities.SettingsActivity +import com.pitchedapps.frost.db.FrostDatabase import com.pitchedapps.frost.db.NotificationModel -import com.pitchedapps.frost.db.loadFbCookiesAsync import com.pitchedapps.frost.services.fetchNotifications import com.pitchedapps.frost.services.scheduleNotifications import com.pitchedapps.frost.utils.Prefs import com.pitchedapps.frost.utils.frostSnackbar import com.pitchedapps.frost.utils.materialDialogThemed import com.pitchedapps.frost.views.Keywords +import kotlinx.coroutines.launch /** * Created by Allan Wang on 2017-06-29. @@ -171,8 +172,12 @@ fun SettingsActivity.getNotificationPrefs(): KPrefAdapterBuilder.() -> Unit = { if (BuildConfig.DEBUG) { plainText(R.string.reset_notif_epoch) { onClick = { - loadFbCookiesAsync { cookies -> - cookies.map { NotificationModel(it.id) }.forEach { it.save() } + launch { + FrostDatabase.get() + .cookieDao() + .selectAll() + .map { NotificationModel(it.id) } + .forEach { it.save() } } } } diff --git a/app/src/main/kotlin/com/pitchedapps/frost/utils/Downloader.kt b/app/src/main/kotlin/com/pitchedapps/frost/utils/Downloader.kt index 254297a6..64094d1e 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/utils/Downloader.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/utils/Downloader.kt @@ -29,7 +29,7 @@ import ca.allanwang.kau.utils.showAppInfo import ca.allanwang.kau.utils.string import ca.allanwang.kau.utils.toast import com.pitchedapps.frost.R -import com.pitchedapps.frost.db.loadFbCookie +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.facebook.USER_AGENT_BASIC /** @@ -38,6 +38,7 @@ import com.pitchedapps.frost.facebook.USER_AGENT_BASIC * With reference to Stack Overflow */ fun Context.frostDownload( + cookie: CookieEntity, url: String?, userAgent: String = USER_AGENT_BASIC, contentDisposition: String? = null, @@ -45,10 +46,11 @@ fun Context.frostDownload( contentLength: Long = 0L ) { url ?: return - frostDownload(Uri.parse(url), userAgent, contentDisposition, mimeType, contentLength) + frostDownload(cookie, Uri.parse(url), userAgent, contentDisposition, mimeType, contentLength) } fun Context.frostDownload( + cookie: CookieEntity, uri: Uri?, userAgent: String = USER_AGENT_BASIC, contentDisposition: String? = null, @@ -75,7 +77,6 @@ fun Context.frostDownload( if (!granted) return@kauRequestPermissions val request = DownloadManager.Request(uri) request.setMimeType(mimeType) - val cookie = loadFbCookie(Prefs.userId) ?: return@kauRequestPermissions val title = URLUtil.guessFileName(uri.toString(), contentDisposition, mimeType) request.addRequestHeader("Cookie", cookie.cookie) request.addRequestHeader("User-Agent", userAgent) diff --git a/app/src/main/kotlin/com/pitchedapps/frost/utils/Utils.kt b/app/src/main/kotlin/com/pitchedapps/frost/utils/Utils.kt index 1222e93b..5a104458 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/utils/Utils.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/utils/Utils.kt @@ -62,7 +62,7 @@ import com.pitchedapps.frost.activities.TabCustomizerActivity import com.pitchedapps.frost.activities.WebOverlayActivity import com.pitchedapps.frost.activities.WebOverlayActivityBase import com.pitchedapps.frost.activities.WebOverlayBasicActivity -import com.pitchedapps.frost.db.CookieModel +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.facebook.FACEBOOK_COM import com.pitchedapps.frost.facebook.FBCDN_NET import com.pitchedapps.frost.facebook.FbCookie @@ -103,7 +103,7 @@ internal inline val Context.ctxCoroutine: CoroutineScope get() = this as? CoroutineScope ?: GlobalScope inline fun Context.launchNewTask( - cookieList: ArrayList = arrayListOf(), + cookieList: ArrayList = arrayListOf(), clearStack: Boolean = false ) { startActivity(clearStack, intentBuilder = { @@ -111,13 +111,13 @@ inline fun Context.launchNewTask( }) } -fun Context.launchLogin(cookieList: ArrayList, clearStack: Boolean = true) { +fun Context.launchLogin(cookieList: ArrayList, clearStack: Boolean = true) { if (cookieList.isNotEmpty()) launchNewTask(cookieList, clearStack) else launchNewTask(clearStack = clearStack) } -fun Activity.cookies(): ArrayList { - return intent?.getParcelableArrayListExtra(EXTRA_COOKIES) ?: arrayListOf() +fun Activity.cookies(): ArrayList { + return intent?.getParcelableArrayListExtra(EXTRA_COOKIES) ?: arrayListOf() } /** diff --git a/app/src/main/kotlin/com/pitchedapps/frost/views/AccountItem.kt b/app/src/main/kotlin/com/pitchedapps/frost/views/AccountItem.kt index 8c7435ea..07eaed0a 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/views/AccountItem.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/views/AccountItem.kt @@ -33,7 +33,7 @@ import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.pitchedapps.frost.R -import com.pitchedapps.frost.db.CookieModel +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.facebook.profilePictureUrl import com.pitchedapps.frost.glide.FrostGlide import com.pitchedapps.frost.glide.GlideApp @@ -42,7 +42,7 @@ import com.pitchedapps.frost.utils.Prefs /** * Created by Allan Wang on 2017-06-05. */ -class AccountItem(val cookie: CookieModel?) : KauIItem +class AccountItem(val cookie: CookieEntity?) : KauIItem (R.layout.view_account, { ViewHolder(it) }, R.id.item_account) { override fun bindView(viewHolder: ViewHolder, payloads: MutableList) { diff --git a/app/src/main/kotlin/com/pitchedapps/frost/views/FrostVideoViewer.kt b/app/src/main/kotlin/com/pitchedapps/frost/views/FrostVideoViewer.kt index c2535940..288e2b40 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/views/FrostVideoViewer.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/views/FrostVideoViewer.kt @@ -32,6 +32,7 @@ import ca.allanwang.kau.utils.inflate import ca.allanwang.kau.utils.isColorDark import ca.allanwang.kau.utils.isGone import ca.allanwang.kau.utils.isVisible +import ca.allanwang.kau.utils.launchMain import ca.allanwang.kau.utils.setIcon import ca.allanwang.kau.utils.setMenuIcons import ca.allanwang.kau.utils.visible @@ -39,8 +40,12 @@ import ca.allanwang.kau.utils.withMinAlpha import com.devbrackets.android.exomedia.listener.VideoControlsVisibilityListener import com.mikepenz.google_material_typeface_library.GoogleMaterial import com.pitchedapps.frost.R +import com.pitchedapps.frost.db.CookieModel_Table.cookie +import com.pitchedapps.frost.db.FrostDatabase +import com.pitchedapps.frost.db.currentCookie import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.Prefs +import com.pitchedapps.frost.utils.ctxCoroutine import com.pitchedapps.frost.utils.frostDownload import kotlinx.android.synthetic.main.view_video.view.* @@ -96,7 +101,11 @@ class FrostVideoViewer @JvmOverloads constructor( video_toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_pip -> video.isExpanded = false - R.id.action_download -> context.frostDownload(video.videoUri) + R.id.action_download -> context.ctxCoroutine.launchMain { + val cookie = FrostDatabase.get().cookieDao().currentCookie() ?: return@launchMain + context.frostDownload(cookie, video.videoUri) + } + } true } diff --git a/app/src/main/kotlin/com/pitchedapps/frost/web/FrostJSI.kt b/app/src/main/kotlin/com/pitchedapps/frost/web/FrostJSI.kt index 663acfbb..4df84b63 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/web/FrostJSI.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/web/FrostJSI.kt @@ -21,6 +21,7 @@ import android.webkit.JavascriptInterface import com.pitchedapps.frost.activities.MainActivity import com.pitchedapps.frost.contracts.MainActivityContract import com.pitchedapps.frost.contracts.VideoViewHolder +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.facebook.FbCookie import com.pitchedapps.frost.utils.L @@ -44,7 +45,7 @@ class FrostJSI(val web: FrostWebView) { private val activity: MainActivity? = context as? MainActivity private val header: SendChannel? = activity?.headerBadgeChannel private val refresh: SendChannel = web.parent.refreshChannel - private val cookies: List = activity?.cookies() ?: arrayListOf() + private val cookies: List = activity?.cookies() ?: arrayListOf() /** * Attempts to load the url in an overlay diff --git a/app/src/main/kotlin/com/pitchedapps/frost/web/LoginWebView.kt b/app/src/main/kotlin/com/pitchedapps/frost/web/LoginWebView.kt index 11a53c36..07aafaf0 100644 --- a/app/src/main/kotlin/com/pitchedapps/frost/web/LoginWebView.kt +++ b/app/src/main/kotlin/com/pitchedapps/frost/web/LoginWebView.kt @@ -29,6 +29,7 @@ import android.webkit.WebView import ca.allanwang.kau.utils.fadeIn import ca.allanwang.kau.utils.isVisible import ca.allanwang.kau.utils.launchMain +import com.pitchedapps.frost.db.CookieEntity import com.pitchedapps.frost.db.CookieModel import com.pitchedapps.frost.facebook.FB_LOGIN_URL import com.pitchedapps.frost.facebook.FB_USER_MATCHER @@ -52,7 +53,7 @@ class LoginWebView @JvmOverloads constructor( defStyleAttr: Int = 0 ) : WebView(context, attrs, defStyleAttr) { - private val completable: CompletableDeferred = CompletableDeferred() + private val completable: CompletableDeferred = CompletableDeferred() private lateinit var progressCallback: (Int) -> Unit @SuppressLint("SetJavaScriptEnabled") @@ -63,7 +64,7 @@ class LoginWebView @JvmOverloads constructor( webChromeClient = LoginChromeClient() } - suspend fun loadLogin(progressCallback: (Int) -> Unit): CompletableDeferred = coroutineScope { + suspend fun loadLogin(progressCallback: (Int) -> Unit): CompletableDeferred = coroutineScope { this@LoginWebView.progressCallback = progressCallback L.d { "Begin loading login" } launchMain { @@ -78,18 +79,19 @@ class LoginWebView @JvmOverloads constructor( override fun onPageFinished(view: WebView, url: String?) { super.onPageFinished(view, url) - val cookieModel = checkForLogin(url) - if (cookieModel != null) - completable.complete(cookieModel) + val cookie = checkForLogin(url) + if (cookie != null) + completable.complete(cookie) if (!view.isVisible) view.fadeIn() } - fun checkForLogin(url: String?): CookieModel? { + fun checkForLogin(url: String?): CookieEntity? { if (!url.isFacebookUrl) return null val cookie = CookieManager.getInstance().getCookie(url) ?: return null L.d { "Checking cookie for login" } val id = FB_USER_MATCHER.find(cookie)[1]?.toLong() ?: return null - return CookieModel(id, "", cookie) + // TODO set name to null? + return CookieEntity(id, "", cookie) } override fun onPageCommitVisible(view: WebView, url: String?) { -- cgit v1.2.3