Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate server and user info to database #221

Merged
merged 1 commit into from
Nov 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ dependencies {

// Core
implementation(Dependencies.Core.koin)
implementation(Dependencies.Core.koinViewModel)
implementation(Dependencies.Core.appCompat)
implementation(Dependencies.Core.androidx)
implementation(Dependencies.Core.activity)
Expand Down
121 changes: 121 additions & 0 deletions app/schemas/org.jellyfin.mobile.model.sql.JellyfinDatabase/2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
{
"formatVersion": 1,
"database": {
"version": 2,
"identityHash": "b88354b3000c5abb5c19bfea2813d43a",
"entities": [
{
"tableName": "Server",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `hostname` TEXT NOT NULL, `last_used_timestamp` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "hostname",
"columnName": "hostname",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "lastUsedTimestamp",
"columnName": "last_used_timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [
{
"name": "index_Server_hostname",
"unique": true,
"columnNames": [
"hostname"
],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Server_hostname` ON `${TABLE_NAME}` (`hostname`)"
}
],
"foreignKeys": []
},
{
"tableName": "User",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `server_id` INTEGER NOT NULL, `user_id` TEXT NOT NULL, `access_token` TEXT, `last_login_timestamp` INTEGER NOT NULL, FOREIGN KEY(`server_id`) REFERENCES `Server`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "serverId",
"columnName": "server_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "userId",
"columnName": "user_id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "accessToken",
"columnName": "access_token",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "lastLoginTimestamp",
"columnName": "last_login_timestamp",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [
{
"name": "index_User_server_id_user_id",
"unique": true,
"columnNames": [
"server_id",
"user_id"
],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_User_server_id_user_id` ON `${TABLE_NAME}` (`server_id`, `user_id`)"
}
],
"foreignKeys": [
{
"table": "Server",
"onDelete": "NO ACTION",
"onUpdate": "NO ACTION",
"columns": [
"server_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'b88354b3000c5abb5c19bfea2813d43a')"
]
}
}
19 changes: 10 additions & 9 deletions app/src/main/java/org/jellyfin/mobile/AppPreferences.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,28 @@ class AppPreferences(context: Context) {
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences("${context.packageName}_preferences", Context.MODE_PRIVATE)

var instanceUrl: String?
get() = sharedPreferences.getString(Constants.PREF_INSTANCE_URL, null)
var currentServerId: Long?
get() = sharedPreferences.getLong(Constants.PREF_SERVER_ID, -1).takeIf { it >= 0 }
set(value) {
sharedPreferences.edit {
if (value != null) putString(Constants.PREF_INSTANCE_URL, value) else remove(Constants.PREF_INSTANCE_URL)
if (value != null) putLong(Constants.PREF_SERVER_ID, value) else remove(Constants.PREF_SERVER_ID)
}
}

var instanceAccessToken: String?
get() = sharedPreferences.getString(Constants.PREF_INSTANCE_ACCESS_TOKEN, null)
var currentUserId: Long?
get() = sharedPreferences.getLong(Constants.PREF_USER_ID, -1).takeIf { it >= 0 }
set(value) {
sharedPreferences.edit {
if (value != null) putString(Constants.PREF_INSTANCE_ACCESS_TOKEN, value) else remove(Constants.PREF_INSTANCE_ACCESS_TOKEN)
if (value != null) putLong(Constants.PREF_USER_ID, value) else remove(Constants.PREF_USER_ID)
}
}

var instanceUserId: String?
get() = sharedPreferences.getString(Constants.PREF_INSTANCE_USER_ID, null)
@Deprecated(message = "Deprecated in favor of SQLite database - only kept for migration reasons")
var instanceUrl: String?
get() = sharedPreferences.getString(Constants.PREF_INSTANCE_URL, null)
set(value) {
sharedPreferences.edit {
if (value != null) putString(Constants.PREF_INSTANCE_USER_ID, value) else remove(Constants.PREF_INSTANCE_USER_ID)
if (value != null) putString(Constants.PREF_INSTANCE_URL, value) else remove(Constants.PREF_INSTANCE_URL)
}
}

Expand Down
9 changes: 9 additions & 0 deletions app/src/main/java/org/jellyfin/mobile/ApplicationModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ import org.jellyfin.apiclient.Jellyfin
import org.jellyfin.apiclient.android
import org.jellyfin.apiclient.interaction.AndroidDevice
import org.jellyfin.mobile.api.TimberLogger
import org.jellyfin.mobile.controller.ServerController
import org.jellyfin.mobile.fragment.ConnectFragment
import org.jellyfin.mobile.fragment.WebViewFragment
import org.jellyfin.mobile.player.PlayerEvent
import org.jellyfin.mobile.player.PlayerFragment
import org.jellyfin.mobile.utils.Constants
import org.jellyfin.mobile.utils.PermissionRequestHelper
import org.jellyfin.mobile.viewmodel.MainViewModel
import org.jellyfin.mobile.webapp.RemoteVolumeProvider
import org.jellyfin.mobile.webapp.WebappFunctionChannel
import org.koin.android.ext.koin.androidApplication
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.androidx.fragment.dsl.fragment
import org.koin.core.qualifier.named
import org.koin.dsl.module
Expand All @@ -42,6 +45,12 @@ val applicationModule = module {
single { RemoteVolumeProvider(get()) }
single(named(PLAYER_EVENT_CHANNEL)) { Channel<PlayerEvent>() }

// Controllers
single { ServerController(get(), get(), get(), get()) }

// ViewModels
viewModel { MainViewModel(get(), get(), get()) }

// Fragments
fragment { ConnectFragment() }
fragment { WebViewFragment() }
Expand Down
34 changes: 21 additions & 13 deletions app/src/main/java/org/jellyfin/mobile/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,24 @@ import android.os.IBinder
import android.view.OrientationEventListener
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.jellyfin.apiclient.interaction.ApiClient
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.jellyfin.mobile.cast.Chromecast
import org.jellyfin.mobile.cast.IChromecast
import org.jellyfin.mobile.fragment.ConnectFragment
import org.jellyfin.mobile.fragment.WebViewFragment
import org.jellyfin.mobile.player.PlayerFragment
import org.jellyfin.mobile.utils.PermissionRequestHelper
import org.jellyfin.mobile.utils.SmartOrientationListener
import org.jellyfin.mobile.utils.lazyView
import org.jellyfin.mobile.utils.replaceFragment
import org.jellyfin.mobile.utils.*
import org.jellyfin.mobile.viewmodel.MainViewModel
import org.jellyfin.mobile.viewmodel.ServerState
import org.jellyfin.mobile.webapp.RemotePlayerService
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import org.koin.androidx.fragment.android.setupKoinFragmentFactory

class MainActivity : AppCompatActivity() {
val apiClient: ApiClient by inject()
private val mainViewModel: MainViewModel by viewModel()
val appPreferences: AppPreferences by inject()
val chromecast: IChromecast = Chromecast()
private val permissionRequestHelper: PermissionRequestHelper by inject()
Expand Down Expand Up @@ -53,12 +54,19 @@ class MainActivity : AppCompatActivity() {
bindService(Intent(this, RemotePlayerService::class.java), serviceConnection, Service.BIND_AUTO_CREATE)

// Load UI
appPreferences.instanceUrl?.toHttpUrlOrNull().also { url ->
with(supportFragmentManager) {
if (url != null) {
replaceFragment<WebViewFragment>()
} else {
replaceFragment<ConnectFragment>()
lifecycleScope.launch {
mainViewModel.serverState.collect { state ->
with(supportFragmentManager) {
when (state) {
ServerState.Pending -> {
// TODO add loading indicator
}
Maxr1998 marked this conversation as resolved.
Show resolved Hide resolved
is ServerState.Unset -> replaceFragment<ConnectFragment>()
is ServerState.Available -> replaceFragment<WebViewFragment>(Bundle().apply {
putLong(Constants.FRAGMENT_WEB_VIEW_EXTRA_SERVER_ID, state.server.id)
putString(Constants.FRAGMENT_WEB_VIEW_EXTRA_URL, state.server.hostname)
})
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package org.jellyfin.mobile.controller

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jellyfin.apiclient.interaction.ApiClient
import org.jellyfin.mobile.AppPreferences
import org.jellyfin.mobile.model.sql.dao.ServerDao
import org.jellyfin.mobile.model.sql.dao.UserDao
import org.jellyfin.mobile.model.sql.entity.ServerEntity
import org.jellyfin.mobile.model.sql.entity.ServerUser

class ServerController(
private val appPreferences: AppPreferences,
private val apiClient: ApiClient,
private val serverDao: ServerDao,
private val userDao: UserDao,
) {
/**
* Migrate from preferences if necessary
*/
@Suppress("DEPRECATION")
suspend fun migrateFromPreferences() {
appPreferences.instanceUrl?.let { url ->
setupServer(url)
appPreferences.instanceUrl = null
}
}

suspend fun setupServer(hostname: String) {
appPreferences.currentServerId = withContext(Dispatchers.IO) {
serverDao.insert(hostname)
}
}

suspend fun setupUser(serverId: Long, userId: String, accessToken: String) {
appPreferences.currentUserId = withContext(Dispatchers.IO) {
userDao.insert(serverId, userId, accessToken)
}
apiClient.SetAuthenticationInfo(accessToken, userId)
}

suspend fun loadCurrentServer(): ServerEntity? = withContext(Dispatchers.IO) {
val serverId = appPreferences.currentServerId ?: return@withContext null
serverDao.getServer(serverId)
}

suspend fun loadCurrentServerUser(): ServerUser? = withContext(Dispatchers.IO) {
val serverId = appPreferences.currentServerId ?: return@withContext null
val userId = appPreferences.currentUserId ?: return@withContext null
userDao.getServerUser(serverId, userId)
}
}
22 changes: 12 additions & 10 deletions app/src/main/java/org/jellyfin/mobile/fragment/ConnectFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,23 @@ import org.jellyfin.apiclient.discovery.DiscoveryServerInfo
import org.jellyfin.apiclient.discovery.ServerDiscovery
import org.jellyfin.apiclient.interaction.ApiClient
import org.jellyfin.apiclient.model.system.PublicSystemInfo
import org.jellyfin.mobile.AppPreferences
import org.jellyfin.mobile.R
import org.jellyfin.mobile.controller.ServerController
import org.jellyfin.mobile.databinding.FragmentConnectBinding
import org.jellyfin.mobile.utils.*
import org.jellyfin.mobile.utils.Constants
import org.jellyfin.mobile.utils.PRODUCT_NAME_SUPPORTED_SINCE
import org.jellyfin.mobile.utils.applyWindowInsetsAsMargins
import org.jellyfin.mobile.utils.getPublicSystemInfo
import org.jellyfin.mobile.viewmodel.MainViewModel
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.sharedViewModel
import timber.log.Timber

class ConnectFragment : Fragment() {
private val mainViewModel: MainViewModel by sharedViewModel()
private val jellyfin: Jellyfin by inject()
private val apiClient: ApiClient by inject()
private val appPreferences: AppPreferences by inject()
private val serverController: ServerController by inject()

// UI
private var _connectServerBinding: FragmentConnectBinding? = null
Expand All @@ -64,7 +70,7 @@ class ConnectFragment : Fragment() {
// Apply window insets
ViewCompat.requestApplyInsets(serverSetupLayout)

hostInput.setText(appPreferences.instanceUrl)
hostInput.setText(mainViewModel.serverState.value.server?.hostname)
hostInput.setSelection(hostInput.length())
hostInput.setOnEditorActionListener { _, action, event ->
when {
Expand Down Expand Up @@ -110,13 +116,9 @@ class ConnectFragment : Fragment() {
lifecycleScope.launch {
val httpUrl = checkServerUrlAndConnection(enteredUrl)
if (httpUrl != null) {
appPreferences.instanceUrl = httpUrl.toString()
clearServerList()
with(parentFragmentManager) {
if (backStackEntryCount > 0)
popBackStack()
replaceFragment<WebViewFragment>()
}
serverController.setupServer(httpUrl.toString())
mainViewModel.refreshServer()
}
hostInput.isEnabled = true
connectButton.isEnabled = true
Expand Down