Merge pull request #1326 from Bnyro/master

Code cleanup, performance improvements
This commit is contained in:
Bnyro 2022-09-18 19:29:47 +02:00 committed by GitHub
commit c04eab339d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
25 changed files with 98 additions and 75 deletions

View File

@ -34,7 +34,7 @@ class LibreTubeApp : Application() {
/**
* Initialize the [DatabaseHolder]
*/
DatabaseHolder.initializeDatabase(this)
DatabaseHolder().initializeDatabase(this)
/**
* Bypassing fileUriExposedException, see https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed

View File

@ -247,7 +247,8 @@ class MainActivity : BaseActivity() {
lastSeenVideoId == it.url?.toID()
} ?: return@observe
if (lastSeenVideoIndex < 1) return@observe
binding.bottomNav.getOrCreateBadge(R.id.subscriptionsFragment).number = lastSeenVideoIndex
binding.bottomNav.getOrCreateBadge(R.id.subscriptionsFragment).number =
lastSeenVideoIndex
}
}

View File

@ -23,8 +23,14 @@ class BottomSheetAdapter(
override fun onBindViewHolder(holder: BottomSheetViewHolder, position: Int) {
val item = items[position]
holder.binding.apply {
title.text = if (item.currentValue != null) "${item.title} (${item.currentValue})" else item.title
if (item.drawable != null) drawable.setImageResource(item.drawable) else drawable.visibility = View.GONE
title.text =
if (item.currentValue != null) "${item.title} (${item.currentValue})" else item.title
if (item.drawable != null) {
drawable.setImageResource(item.drawable)
} else {
drawable.visibility =
View.GONE
}
root.setOnClickListener {
listener.invoke(position)

View File

@ -38,8 +38,9 @@ class PlaylistAdapter(
}
fun updateItems(newItems: List<StreamItem>) {
val oldSize = videoFeed.size
videoFeed.addAll(newItems)
notifyDataSetChanged()
notifyItemRangeInserted(oldSize, videoFeed.size)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder {

View File

@ -34,8 +34,9 @@ class PlaylistsAdapter(
}
fun updateItems(newItems: List<Playlists>) {
val oldSize = playlists.size
playlists.addAll(newItems)
notifyDataSetChanged()
notifyItemRangeInserted(oldSize, playlists.size)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistsViewHolder {
@ -102,7 +103,9 @@ class PlaylistsAdapter(
try {
if (response.message == "ok") {
playlists.removeAt(position)
activity.runOnUiThread { notifyDataSetChanged() }
activity.runOnUiThread {
notifyItemRemoved(position)
}
}
} catch (e: Exception) {
Log.e(TAG(), e.toString())

View File

@ -5,7 +5,7 @@ import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.RecyclerView
import com.github.libretube.databinding.SearchhistoryRowBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.SearchHistoryItem
class SearchHistoryAdapter(
@ -30,13 +30,14 @@ class SearchHistoryAdapter(
historyText.text = historyQuery
deleteHistory.setOnClickListener {
val itemIndex = historyList.indexOf(historyQuery)
historyList -= historyQuery
Thread {
DatabaseHolder.db.searchHistoryDao().delete(
Database.searchHistoryDao().delete(
SearchHistoryItem(query = historyQuery)
)
}.start()
notifyDataSetChanged()
notifyItemRemoved(itemIndex)
}
root.setOnClickListener {

View File

@ -34,8 +34,9 @@ class TrendingAdapter(
}
fun updateItems() {
val oldSize = index
index += 10
notifyDataSetChanged()
notifyItemRangeInserted(oldSize, index)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubscriptionViewHolder {

View File

@ -22,7 +22,7 @@ class WatchHistoryAdapter(
fun removeFromWatchHistory(position: Int) {
DatabaseHelper.removeFromWatchHistory(position)
watchHistory.removeAt(position)
notifyDataSetChanged()
notifyItemRemoved(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WatchHistoryViewHolder {

View File

@ -1,7 +1,7 @@
package com.github.libretube.api
import android.util.Log
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.LocalSubscription
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.await
@ -27,7 +27,7 @@ object SubscriptionHelper {
}
} else {
Thread {
DatabaseHolder.db.localSubscriptionDao().insertAll(
Database.localSubscriptionDao().insertAll(
LocalSubscription(channelId)
)
}.start()
@ -48,7 +48,7 @@ object SubscriptionHelper {
}
} else {
Thread {
DatabaseHolder.db.localSubscriptionDao().delete(
Database.localSubscriptionDao().delete(
LocalSubscription(channelId)
)
}.start()
@ -70,7 +70,7 @@ object SubscriptionHelper {
} else {
var isSubscribed = false
Thread {
isSubscribed = DatabaseHolder.db.localSubscriptionDao().includes(channelId)
isSubscribed = Database.localSubscriptionDao().includes(channelId)
}.await()
return isSubscribed
}
@ -94,7 +94,7 @@ object SubscriptionHelper {
newLocalSubscriptions += LocalSubscription(channelId = it)
}
Thread {
DatabaseHolder.db.localSubscriptionDao().insertAll(
Database.localSubscriptionDao().insertAll(
*newChannels.map { LocalSubscription(it) }.toTypedArray()
)
}.start()
@ -104,7 +104,7 @@ object SubscriptionHelper {
fun getLocalSubscriptions(): List<LocalSubscription> {
var localSubscriptions = listOf<LocalSubscription>()
Thread {
localSubscriptions = DatabaseHolder.db.localSubscriptionDao().getAll()
localSubscriptions = Database.localSubscriptionDao().getAll()
}.await()
return localSubscriptions
}

View File

@ -1,6 +1,7 @@
package com.github.libretube.db
import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.SearchHistoryItem
import com.github.libretube.db.obj.WatchHistoryItem
import com.github.libretube.db.obj.WatchPosition
@ -21,15 +22,15 @@ object DatabaseHelper {
streams.duration
)
Thread {
DatabaseHolder.db.watchHistoryDao().insertAll(watchHistoryItem)
Database.watchHistoryDao().insertAll(watchHistoryItem)
val maxHistorySize =
PreferenceHelper.getString(PreferenceKeys.WATCH_HISTORY_SIZE, "unlimited")
if (maxHistorySize == "unlimited") return@Thread
// delete the first watch history entry if the limit is reached
val watchHistory = DatabaseHolder.db.watchHistoryDao().getAll()
val watchHistory = Database.watchHistoryDao().getAll()
if (watchHistory.size > maxHistorySize.toInt()) {
DatabaseHolder.db.watchHistoryDao()
Database.watchHistoryDao()
.delete(watchHistory.first())
}
}.start()
@ -37,8 +38,8 @@ object DatabaseHelper {
fun removeFromWatchHistory(index: Int) {
Thread {
DatabaseHolder.db.watchHistoryDao().delete(
DatabaseHolder.db.watchHistoryDao().getAll()[index]
Database.watchHistoryDao().delete(
Database.watchHistoryDao().getAll()[index]
)
}.start()
}
@ -49,27 +50,27 @@ object DatabaseHelper {
position
)
Thread {
DatabaseHolder.db.watchPositionDao().insertAll(watchPosition)
Database.watchPositionDao().insertAll(watchPosition)
}.start()
}
fun removeWatchPosition(videoId: String) {
Thread {
DatabaseHolder.db.watchPositionDao().delete(
DatabaseHolder.db.watchPositionDao().findById(videoId)
Database.watchPositionDao().delete(
Database.watchPositionDao().findById(videoId)
)
}.start()
}
fun addToSearchHistory(searchHistoryItem: SearchHistoryItem) {
Thread {
DatabaseHolder.db.searchHistoryDao().insertAll(searchHistoryItem)
Database.searchHistoryDao().insertAll(searchHistoryItem)
val maxHistorySize = 20
// delete the first watch history entry if the limit is reached
val searchHistory = DatabaseHolder.db.searchHistoryDao().getAll()
val searchHistory = Database.searchHistoryDao().getAll()
if (searchHistory.size > maxHistorySize) {
DatabaseHolder.db.searchHistoryDao()
Database.searchHistoryDao()
.delete(searchHistory.first())
}
}.start()

View File

@ -4,11 +4,9 @@ import android.content.Context
import androidx.room.Room
import com.github.libretube.constants.DATABASE_NAME
object DatabaseHolder {
lateinit var db: AppDatabase
class DatabaseHolder {
fun initializeDatabase(context: Context) {
db = Room.databaseBuilder(
Database = Room.databaseBuilder(
context,
AppDatabase::class.java,
DATABASE_NAME
@ -16,4 +14,8 @@ object DatabaseHolder {
.fallbackToDestructiveMigration()
.build()
}
companion object {
lateinit var Database: AppDatabase
}
}

View File

@ -7,7 +7,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import com.github.libretube.R
import com.github.libretube.adapters.BackupOptionsAdapter
import com.github.libretube.databinding.DialogBackupBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.extensions.await
import com.github.libretube.obj.BackupFile
import com.google.android.material.dialog.MaterialAlertDialogBuilder
@ -32,7 +32,8 @@ class BackupDialog(
binding = DialogBackupBinding.inflate(layoutInflater)
binding.backupOptionsRecycler.layoutManager = LinearLayoutManager(context)
binding.backupOptionsRecycler.adapter = BackupOptionsAdapter(backupOptions) { position, isChecked ->
binding.backupOptionsRecycler.adapter =
BackupOptionsAdapter(backupOptions) { position, isChecked ->
selected[position] = isChecked
}
@ -44,23 +45,23 @@ class BackupDialog(
Thread {
if (selected[0]) {
backupFile.watchHistory =
DatabaseHolder.db.watchHistoryDao().getAll()
Database.watchHistoryDao().getAll()
}
if (selected[1]) {
backupFile.watchPositions =
DatabaseHolder.db.watchPositionDao().getAll()
Database.watchPositionDao().getAll()
}
if (selected[2]) {
backupFile.searchHistory =
DatabaseHolder.db.searchHistoryDao().getAll()
Database.searchHistoryDao().getAll()
}
if (selected[3]) {
backupFile.localSubscriptions =
DatabaseHolder.db.localSubscriptionDao().getAll()
Database.localSubscriptionDao().getAll()
}
if (selected[4]) {
backupFile.customInstances =
DatabaseHolder.db.customInstanceDao().getAll()
Database.customInstanceDao().getAll()
}
}.await()

View File

@ -6,7 +6,7 @@ import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.github.libretube.R
import com.github.libretube.databinding.DialogCustomInstanceBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.CustomInstance
import com.github.libretube.util.ThemeHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder
@ -40,7 +40,7 @@ class CustomInstanceDialog : DialogFragment() {
URL(customInstance.frontendUrl).toURI()
Thread {
DatabaseHolder.db.customInstanceDao().insertAll(customInstance)
Database.customInstanceDao().insertAll(customInstance)
}.start()
activity?.recreate()

View File

@ -9,7 +9,7 @@ import com.github.libretube.constants.PIPED_FRONTEND_URL
import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.constants.YOUTUBE_FRONTEND_URL
import com.github.libretube.databinding.DialogShareBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.CustomInstance
import com.github.libretube.extensions.await
import com.github.libretube.util.PreferenceHelper
@ -82,7 +82,7 @@ class ShareDialog(
// get the api urls of the other custom instances
var customInstances = listOf<CustomInstance>()
Thread {
customInstances = DatabaseHolder.db.customInstanceDao().getAll()
customInstances = Database.customInstanceDao().getAll()
}.await()
// return the custom instance frontend url if available

View File

@ -3,7 +3,7 @@ package com.github.libretube.extensions
import android.view.View
import android.view.ViewTreeObserver
import android.widget.LinearLayout
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
/**
* shows the already watched time under the video
@ -14,7 +14,7 @@ fun View?.setWatchProgressLength(videoId: String, duration: Long) {
Thread {
try {
progress = DatabaseHolder.db.watchPositionDao().findById(videoId).position
progress = Database.watchPositionDao().findById(videoId).position
} catch (e: Exception) {
progress = null
}

View File

@ -50,7 +50,7 @@ import com.github.libretube.databinding.DoubleTapOverlayBinding
import com.github.libretube.databinding.ExoStyledPlayerControlViewBinding
import com.github.libretube.databinding.FragmentPlayerBinding
import com.github.libretube.db.DatabaseHelper
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.dialogs.AddToPlaylistDialog
import com.github.libretube.dialogs.DownloadDialog
import com.github.libretube.dialogs.ShareDialog
@ -477,7 +477,8 @@ class PlayerFragment : BaseFragment() {
exoPlayer.setMediaItem(mediaItem)
} else {
val videoUri = videosUrlArray[which]
val audioUrl = PlayerHelper.getAudioSource(requireContext(), streams.audioStreams!!)
val audioUrl =
PlayerHelper.getAudioSource(requireContext(), streams.audioStreams!!)
setMediaSource(videoUri, audioUrl)
}
exoPlayer.seekTo(lastPosition)
@ -860,10 +861,11 @@ class PlayerFragment : BaseFragment() {
var position: Long? = null
Thread {
try {
position = DatabaseHolder.db.watchPositionDao().findById(videoId!!).position
position = Database.watchPositionDao().findById(videoId!!).position
// position is almost the end of the video => don't seek, start from beginning
if (position!! > streams.duration!! * 1000 * 0.9) position = null
} catch (e: Exception) {
e.printStackTrace()
}
}.await()
if (position != null) exoPlayer.seekTo(position!!)
@ -1290,7 +1292,8 @@ class PlayerFragment : BaseFragment() {
// search for quality preference in the available stream sources
if (pipedStream.contains(defRes)) {
val videoUri = videosUrlArray[index]
val audioUrl = PlayerHelper.getAudioSource(requireContext(), streams.audioStreams!!)
val audioUrl =
PlayerHelper.getAudioSource(requireContext(), streams.audioStreams!!)
setMediaSource(videoUri, audioUrl)
return
}

View File

@ -15,7 +15,7 @@ import com.github.libretube.adapters.SearchHistoryAdapter
import com.github.libretube.adapters.SearchSuggestionsAdapter
import com.github.libretube.api.RetrofitInstance
import com.github.libretube.databinding.FragmentSearchBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.extensions.BaseFragment
import com.github.libretube.extensions.TAG
import com.github.libretube.extensions.await
@ -97,7 +97,7 @@ class SearchFragment : BaseFragment() {
private fun showHistory() {
var historyList = listOf<String>()
Thread {
val history = DatabaseHolder.db.searchHistoryDao().getAll()
val history = Database.searchHistoryDao().getAll()
historyList = history.map { it.query }
}.await()
if (historyList.isNotEmpty()) {

View File

@ -9,7 +9,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.libretube.adapters.WatchHistoryAdapter
import com.github.libretube.databinding.FragmentWatchHistoryBinding
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.WatchHistoryItem
import com.github.libretube.extensions.BaseFragment
import com.github.libretube.extensions.await
@ -32,7 +32,7 @@ class WatchHistoryFragment : BaseFragment() {
var watchHistory = listOf<WatchHistoryItem>()
Thread {
watchHistory = DatabaseHolder.db.watchHistoryDao().getAll()
watchHistory = Database.watchHistoryDao().getAll()
}.await()
if (watchHistory.isEmpty()) return

View File

@ -5,7 +5,7 @@ import androidx.preference.Preference
import com.github.libretube.R
import com.github.libretube.activities.SettingsActivity
import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.views.MaterialPreferenceFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
@ -21,7 +21,7 @@ class HistorySettings : MaterialPreferenceFragment() {
val clearHistory = findPreference<Preference>(PreferenceKeys.CLEAR_SEARCH_HISTORY)
clearHistory?.setOnPreferenceClickListener {
showClearDialog(R.string.clear_history) {
DatabaseHolder.db.searchHistoryDao().deleteAll()
Database.searchHistoryDao().deleteAll()
}
true
}
@ -30,7 +30,7 @@ class HistorySettings : MaterialPreferenceFragment() {
val clearWatchHistory = findPreference<Preference>(PreferenceKeys.CLEAR_WATCH_HISTORY)
clearWatchHistory?.setOnPreferenceClickListener {
showClearDialog(R.string.clear_history) {
DatabaseHolder.db.watchHistoryDao().deleteAll()
Database.watchHistoryDao().deleteAll()
}
true
}
@ -39,7 +39,7 @@ class HistorySettings : MaterialPreferenceFragment() {
val clearWatchPositions = findPreference<Preference>(PreferenceKeys.CLEAR_WATCH_POSITIONS)
clearWatchPositions?.setOnPreferenceClickListener {
showClearDialog(R.string.reset_watch_positions) {
DatabaseHolder.db.watchPositionDao().deleteAll()
Database.watchPositionDao().deleteAll()
}
true
}

View File

@ -15,7 +15,7 @@ import com.github.libretube.R
import com.github.libretube.activities.SettingsActivity
import com.github.libretube.api.RetrofitInstance
import com.github.libretube.constants.PreferenceKeys
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.db.obj.CustomInstance
import com.github.libretube.dialogs.CustomInstanceDialog
import com.github.libretube.dialogs.DeleteAccountDialog
@ -111,7 +111,7 @@ class InstanceSettings : MaterialPreferenceFragment() {
val clearCustomInstances = findPreference<Preference>(PreferenceKeys.CLEAR_CUSTOM_INSTANCES)
clearCustomInstances?.setOnPreferenceClickListener {
Thread {
DatabaseHolder.db.customInstanceDao().deleteAll()
Database.customInstanceDao().deleteAll()
}.await()
activity?.recreate()
true
@ -158,7 +158,7 @@ class InstanceSettings : MaterialPreferenceFragment() {
lifecycleScope.launchWhenCreated {
var customInstances = listOf<CustomInstance>()
Thread {
customInstances = DatabaseHolder.db.customInstanceDao().getAll()
customInstances = Database.customInstanceDao().getAll()
}.await()
val instanceNames = arrayListOf<String>()

View File

@ -5,7 +5,7 @@ import android.net.Uri
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.libretube.db.DatabaseHolder
import com.github.libretube.db.DatabaseHolder.Companion.Database
import com.github.libretube.extensions.query
import com.github.libretube.obj.BackupFile
import java.io.FileInputStream
@ -101,19 +101,19 @@ class BackupHelper(private val context: Context) {
val backupFile = mapper.readValue(json, BackupFile::class.java)
query {
DatabaseHolder.db.watchHistoryDao().insertAll(
Database.watchHistoryDao().insertAll(
*backupFile.watchHistory?.toTypedArray().orEmpty()
)
DatabaseHolder.db.searchHistoryDao().insertAll(
Database.searchHistoryDao().insertAll(
*backupFile.searchHistory?.toTypedArray().orEmpty()
)
DatabaseHolder.db.watchPositionDao().insertAll(
Database.watchPositionDao().insertAll(
*backupFile.watchPositions?.toTypedArray().orEmpty()
)
DatabaseHolder.db.localSubscriptionDao().insertAll(
Database.localSubscriptionDao().insertAll(
*backupFile.localSubscriptions?.toTypedArray().orEmpty()
)
DatabaseHolder.db.customInstanceDao().insertAll(
Database.customInstanceDao().insertAll(
*backupFile.customInstances?.toTypedArray().orEmpty()
)
}

View File

@ -47,12 +47,14 @@ object NetworkHelper {
*/
@Suppress("DEPRECATION")
fun isNetworkMobile(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.getNetworkCapabilities(
connectivityManager.activeNetwork ?: return false
)
return networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ?: false
return networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
?: false
} else {
val activeNetwork = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
return activeNetwork != null && activeNetwork.isConnected

View File

@ -173,7 +173,8 @@ internal class CustomExoPlayerView(
BottomSheetItem(
context.getString(R.string.playback_speed),
R.drawable.ic_speed,
"${player?.playbackParameters?.speed
"${
player?.playbackParameters?.speed
.toString()
.replace(".0", "")
}x"

View File

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_height="match_parent"
android:orientation="vertical">
<com.github.libretube.views.CustomExoPlayerView
android:id="@+id/player"

View File

@ -385,8 +385,8 @@
android:layout_marginEnd="-10dp"
android:layout_marginBottom="60dp"
android:paddingEnd="10dp"
app:strokeWidth="1dp"
app:cardBackgroundColor="#88000000"
app:strokeWidth="1dp"
tools:ignore="RtlSymmetry">
<LinearLayout