Merge pull request #622 from Bnyro/master

[SILENT} migrate all prefs to PreferenceHelper
This commit is contained in:
Bnyro 2022-06-26 12:27:10 +02:00 committed by GitHub
commit 47fbd0d20f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 258 additions and 397 deletions

View File

@ -85,4 +85,5 @@ dependencies {
coreLibraryDesugaring libs.desugaring coreLibraryDesugaring libs.desugaring
implementation libs.cronet.embedded implementation libs.cronet.embedded
implementation libs.gson
} }

View File

@ -32,12 +32,11 @@ import androidx.fragment.app.Fragment
import androidx.navigation.NavController import androidx.navigation.NavController
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController import androidx.navigation.ui.setupWithNavController
import androidx.preference.PreferenceManager
import com.github.libretube.fragments.PlayerFragment import com.github.libretube.fragments.PlayerFragment
import com.github.libretube.fragments.isFullScreen import com.github.libretube.fragments.isFullScreen
import com.github.libretube.preferences.SponsorBlockSettings
import com.github.libretube.util.CronetHelper import com.github.libretube.util.CronetHelper
import com.github.libretube.util.LocaleHelper import com.github.libretube.util.LocaleHelper
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.github.libretube.util.ThemeHelper import com.github.libretube.util.ThemeHelper
import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomnavigation.BottomNavigationView
@ -54,32 +53,12 @@ class MainActivity : AppCompatActivity() {
DynamicColors.applyToActivityIfAvailable(this) DynamicColors.applyToActivityIfAvailable(this)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
CronetHelper.initCronet(this.applicationContext) CronetHelper.initCronet(this.applicationContext)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
RetrofitInstance.url =
sharedPreferences.getString("selectInstance", "https://pipedapi.kavin.rocks/")!!
SponsorBlockSettings.sponsorBlockEnabled =
sharedPreferences.getBoolean("sb_enabled_key", true)
SponsorBlockSettings.sponsorNotificationsEnabled =
sharedPreferences.getBoolean("sb_notifications_key", true)
SponsorBlockSettings.introEnabled =
sharedPreferences.getBoolean("intro_category_key", false)
SponsorBlockSettings.selfPromoEnabled =
sharedPreferences.getBoolean("selfpromo_category_key", false)
SponsorBlockSettings.interactionEnabled =
sharedPreferences.getBoolean("interaction_category_key", false)
SponsorBlockSettings.sponsorsEnabled =
sharedPreferences.getBoolean("sponsors_category_key", true)
SponsorBlockSettings.outroEnabled =
sharedPreferences.getBoolean("outro_category_key", false)
SponsorBlockSettings.fillerEnabled =
sharedPreferences.getBoolean("filler_category_key", false)
SponsorBlockSettings.musicOfftopicEnabled =
sharedPreferences.getBoolean("music_offtopic_category_key", false)
SponsorBlockSettings.previewEnabled =
sharedPreferences.getBoolean("preview_category_key", false)
ThemeHelper().updateTheme(this) RetrofitInstance.url =
LocaleHelper().updateLanguage(this) PreferenceHelper.getString(this, "selectInstance", "https://pipedapi.kavin.rocks/")!!
ThemeHelper.updateTheme(this)
LocaleHelper.updateLanguage(this)
// show noInternet Activity if no internet available on app startup // show noInternet Activity if no internet available on app startup
if (!isNetworkAvailable(this)) { if (!isNetworkAvailable(this)) {
@ -100,12 +79,11 @@ class MainActivity : AppCompatActivity() {
bottomNavigationView.setupWithNavController(navController) bottomNavigationView.setupWithNavController(navController)
// hide the trending page if enabled // hide the trending page if enabled
val hideTrendingPage = sharedPreferences.getBoolean("hide_trending_page", false) val hideTrendingPage = PreferenceHelper.getBoolean(this, "hide_trending_page", false)
if (hideTrendingPage) bottomNavigationView.menu.findItem(R.id.home2).isVisible = false if (hideTrendingPage) bottomNavigationView.menu.findItem(R.id.home2).isVisible = false
// navigate to the default start tab // navigate to the default start tab
val defaultTab = sharedPreferences.getString("default_tab", "home") when (PreferenceHelper.getString(this, "default_tab", "home")) {
when (defaultTab) {
"home" -> navController.navigate(R.id.home2) "home" -> navController.navigate(R.id.home2)
"subscriptions" -> navController.navigate(R.id.subscriptions) "subscriptions" -> navController.navigate(R.id.subscriptions)
"library" -> navController.navigate(R.id.library) "library" -> navController.navigate(R.id.library)

View File

@ -21,7 +21,7 @@ class RouterActivity : AppCompatActivity() {
handleSendText(uri!!) handleSendText(uri!!)
} else { } else {
// start app as normal if URI not in host list // start app as normal if URI not in host list
ThemeHelper().restartMainActivity(this) ThemeHelper.restartMainActivity(this)
} }
} }

View File

@ -19,7 +19,7 @@ class SettingsActivity : AppCompatActivity() {
val TAG = "SettingsActivity" val TAG = "SettingsActivity"
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
DynamicColors.applyToActivityIfAvailable(this) DynamicColors.applyToActivityIfAvailable(this)
ThemeHelper().updateTheme(this) ThemeHelper.updateTheme(this)
// makes the preference dialogs use material dialogs // makes the preference dialogs use material dialogs
setTheme(R.style.MaterialAlertDialog) setTheme(R.style.MaterialAlertDialog)
@ -54,7 +54,7 @@ class SettingsActivity : AppCompatActivity() {
val nManager = val nManager =
this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
nManager.cancelAll() nManager.cancelAll()
ThemeHelper().restartMainActivity(this) ThemeHelper.restartMainActivity(this)
ActivityCompat.finishAffinity(this) ActivityCompat.finishAffinity(this)
} else { } else {
super.onBackPressed() super.onBackPressed()

View File

@ -1,7 +1,6 @@
package com.github.libretube.adapters package com.github.libretube.adapters
import android.app.Activity import android.app.Activity
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.text.format.DateUtils import android.text.format.DateUtils
import android.util.Log import android.util.Log
@ -18,6 +17,7 @@ import com.github.libretube.dialogs.VideoOptionsDialog
import com.github.libretube.fragments.PlayerFragment import com.github.libretube.fragments.PlayerFragment
import com.github.libretube.obj.PlaylistId import com.github.libretube.obj.PlaylistId
import com.github.libretube.obj.StreamItem import com.github.libretube.obj.StreamItem
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.squareup.picasso.Picasso import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@ -81,11 +81,7 @@ class PlaylistAdapter(
val delete = holder.v.findViewById<ImageView>(R.id.delete_playlist) val delete = holder.v.findViewById<ImageView>(R.id.delete_playlist)
delete.visibility = View.VISIBLE delete.visibility = View.VISIBLE
delete.setOnClickListener { delete.setOnClickListener {
val sharedPref = holder.v.context.getSharedPreferences( val token = PreferenceHelper.getToken(holder.v.context)
"token",
Context.MODE_PRIVATE
)
val token = sharedPref?.getString("token", "")!!
removeFromPlaylist(token, position) removeFromPlaylist(token, position)
} }
} }

View File

@ -1,7 +1,6 @@
package com.github.libretube.adapters package com.github.libretube.adapters
import android.app.Activity import android.app.Activity
import android.content.Context
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
@ -14,6 +13,7 @@ import com.github.libretube.MainActivity
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.PlaylistId import com.github.libretube.obj.PlaylistId
import com.github.libretube.obj.Playlists import com.github.libretube.obj.Playlists
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.squareup.picasso.Picasso import com.squareup.picasso.Picasso
@ -57,11 +57,7 @@ class PlaylistsAdapter(
builder.setTitle(R.string.deletePlaylist) builder.setTitle(R.string.deletePlaylist)
builder.setMessage(R.string.areYouSure) builder.setMessage(R.string.areYouSure)
builder.setPositiveButton(R.string.yes) { _, _ -> builder.setPositiveButton(R.string.yes) { _, _ ->
val sharedPref = holder.v.context.getSharedPreferences( val token = PreferenceHelper.getToken(holder.v.context)
"token",
Context.MODE_PRIVATE
)
val token = sharedPref?.getString("token", "")!!
deletePlaylist(playlist.id!!, token, position) deletePlaylist(playlist.id!!, token, position)
} }
builder.setNegativeButton(R.string.cancel) { _, _ -> builder.setNegativeButton(R.string.cancel) { _, _ ->
@ -96,10 +92,6 @@ class PlaylistsAdapter(
playlists.removeAt(position) playlists.removeAt(position)
// FIXME: This needs to run on UI thread? // FIXME: This needs to run on UI thread?
activity.runOnUiThread { notifyDataSetChanged() } activity.runOnUiThread { notifyDataSetChanged() }
/*if(playlists.isEmpty()){
view.findViewById<ImageView>(R.id.boogh2).visibility=View.VISIBLE
}*/
} }
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, e.toString()) Log.e(TAG, e.toString())

View File

@ -6,10 +6,10 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.EditText import android.widget.EditText
import android.widget.TextView import android.widget.TextView
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.fragments.SearchFragment import com.github.libretube.fragments.SearchFragment
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.imageview.ShapeableImageView import com.google.android.material.imageview.ShapeableImageView
class SearchHistoryAdapter( class SearchHistoryAdapter(
@ -35,9 +35,8 @@ class SearchHistoryAdapter(
holder.v.findViewById<TextView>(R.id.history_text).text = history holder.v.findViewById<TextView>(R.id.history_text).text = history
holder.v.findViewById<ShapeableImageView>(R.id.delete_history).setOnClickListener { holder.v.findViewById<ShapeableImageView>(R.id.delete_history).setOnClickListener {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
historyList = historyList - history historyList = historyList - history
sharedPreferences.edit().putStringSet("search_history", HashSet(historyList)).apply() PreferenceHelper.saveHistory(context, historyList)
notifyDataSetChanged() notifyDataSetChanged()
} }

View File

@ -13,6 +13,7 @@ import com.github.libretube.MainActivity
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.Subscribe import com.github.libretube.obj.Subscribe
import com.github.libretube.obj.Subscription import com.github.libretube.obj.Subscription
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.squareup.picasso.Picasso import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@ -70,10 +71,9 @@ class SubscriptionChannelAdapter(private val subscriptions: MutableList<Subscrip
fun run() { fun run() {
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
val response = try { val response = try {
val sharedPref = context val token = PreferenceHelper.getToken(context)
.getSharedPreferences("token", Context.MODE_PRIVATE)
RetrofitInstance.api.subscribe( RetrofitInstance.api.subscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channelId) Subscribe(channelId)
) )
} catch (e: IOException) { } catch (e: IOException) {
@ -93,10 +93,9 @@ class SubscriptionChannelAdapter(private val subscriptions: MutableList<Subscrip
fun run() { fun run() {
CoroutineScope(Dispatchers.IO).launch { CoroutineScope(Dispatchers.IO).launch {
val response = try { val response = try {
val sharedPref = val token = PreferenceHelper.getToken(context)
context.getSharedPreferences("token", Context.MODE_PRIVATE)
RetrofitInstance.api.unsubscribe( RetrofitInstance.api.unsubscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channelId) Subscribe(channelId)
) )
} catch (e: IOException) { } catch (e: IOException) {

View File

@ -1,7 +1,6 @@
package com.github.libretube.dialogs package com.github.libretube.dialogs
import android.app.Dialog import android.app.Dialog
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.util.TypedValue import android.util.TypedValue
@ -17,6 +16,7 @@ import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.PlaylistId import com.github.libretube.obj.PlaylistId
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import retrofit2.HttpException import retrofit2.HttpException
@ -34,8 +34,7 @@ class AddtoPlaylistDialog : DialogFragment() {
val builder = MaterialAlertDialogBuilder(it) val builder = MaterialAlertDialogBuilder(it)
// Get the layout inflater // Get the layout inflater
val inflater = requireActivity().layoutInflater val inflater = requireActivity().layoutInflater
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) token = PreferenceHelper.getToken(requireContext())
token = sharedPref?.getString("token", "")!!
var view: View = inflater.inflate(R.layout.dialog_addtoplaylist, null) var view: View = inflater.inflate(R.layout.dialog_addtoplaylist, null)
spinner = view.findViewById(R.id.playlists_spinner) spinner = view.findViewById(R.id.playlists_spinner)
button = view.findViewById(R.id.addToPlaylist) button = view.findViewById(R.id.addToPlaylist)

View File

@ -1,7 +1,6 @@
package com.github.libretube.dialogs package com.github.libretube.dialogs
import android.app.Dialog import android.app.Dialog
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.util.TypedValue import android.util.TypedValue
@ -16,6 +15,7 @@ import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.Playlists import com.github.libretube.obj.Playlists
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
@ -46,8 +46,7 @@ class CreatePlaylistDialog : DialogFragment() {
dismiss() dismiss()
} }
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) token = PreferenceHelper.getToken(requireContext())
token = sharedPref?.getString("token", "")!!
val playlistName = view.findViewById<TextInputEditText>(R.id.playlist_name) val playlistName = view.findViewById<TextInputEditText>(R.id.playlist_name)
val createPlaylistBtn = view.findViewById<Button>(R.id.create_new_playlist) val createPlaylistBtn = view.findViewById<Button>(R.id.create_new_playlist)

View File

@ -9,8 +9,9 @@ import android.widget.TextView
import android.widget.Toast import android.widget.Toast
import androidx.core.text.HtmlCompat import androidx.core.text.HtmlCompat
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import androidx.preference.PreferenceManager
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.CustomInstance
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputEditText
import java.net.URL import java.net.URL
@ -36,17 +37,22 @@ class CustomInstanceDialog : DialogFragment() {
} }
addInstanceButton.setOnClickListener { addInstanceButton.setOnClickListener {
val instanceName = instanceNameEditText.text.toString() val customInstance = CustomInstance()
val instanceApiUrl = instanceApiUrlEditText.text.toString() customInstance.name = instanceNameEditText.text.toString()
val instanceFrontendUrl = instanceFrontendUrlEditText.text.toString() customInstance.apiUrl = instanceApiUrlEditText.text.toString()
customInstance.frontendUrl = instanceFrontendUrlEditText.text.toString()
if (instanceName != "" && instanceApiUrl != "" && instanceFrontendUrl != "") { if (
customInstance.name != "" &&
customInstance.apiUrl != "" &&
customInstance.frontendUrl != ""
) {
try { try {
// check whether the URL is valid, otherwise catch // check whether the URL is valid, otherwise catch
URL(instanceApiUrl).toURI() URL(customInstance.apiUrl).toURI()
URL(instanceFrontendUrl).toURI() URL(customInstance.frontendUrl).toURI()
saveCustomInstance(instanceName, instanceApiUrl, instanceFrontendUrl) PreferenceHelper.saveCustomInstance(requireContext(), customInstance)
activity?.recreate() activity?.recreate()
dismiss() dismiss()
} catch (e: Exception) { } catch (e: Exception) {
@ -80,49 +86,4 @@ class CustomInstanceDialog : DialogFragment() {
builder.create() builder.create()
} ?: throw IllegalStateException("Activity cannot be null") } ?: throw IllegalStateException("Activity cannot be null")
} }
private fun saveCustomInstance(
instanceName: String,
instanceApiUrl: String,
instanceFrontendApiUrl: String
) {
val sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(requireContext())
// get the names of the other custom instances
var customInstancesNames = try {
sharedPreferences
.getStringSet("custom_instances_name", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
// get the api urls of the other custom instances
var customInstancesUrls = try {
sharedPreferences
.getStringSet("custom_instances_url", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
// get the frontend urls of the other custom instances
var customInstancesFrontendUrls = try {
sharedPreferences
.getStringSet("custom_instances_url", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
// append new instance to the list
customInstancesNames += instanceName
customInstancesUrls += instanceApiUrl
customInstancesFrontendUrls += instanceFrontendApiUrl
// save them to the shared preferences
sharedPreferences.edit()
.putStringSet("custom_instances_name", HashSet(customInstancesNames))
.putStringSet("custom_instances_url", HashSet(customInstancesUrls))
.putStringSet("custom_instances_frontend_url", HashSet(customInstancesFrontendUrls))
.apply()
}
} }

View File

@ -1,7 +1,6 @@
package com.github.libretube.dialogs package com.github.libretube.dialogs
import android.app.Dialog import android.app.Dialog
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.util.TypedValue import android.util.TypedValue
@ -15,6 +14,7 @@ import androidx.lifecycle.lifecycleScope
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.DeleteUserRequest import com.github.libretube.obj.DeleteUserRequest
import com.github.libretube.requireMainActivityRestart import com.github.libretube.requireMainActivityRestart
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
@ -58,8 +58,7 @@ class DeleteAccountDialog : DialogFragment() {
private fun deleteAccount(password: String) { private fun deleteAccount(password: String) {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
val token = sharedPref?.getString("token", "")!!
try { try {
RetrofitInstance.api.deleteAccount(token, DeleteUserRequest(password)) RetrofitInstance.api.deleteAccount(token, DeleteUserRequest(password))
@ -78,13 +77,6 @@ class DeleteAccountDialog : DialogFragment() {
} }
private fun logout() { private fun logout() {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) PreferenceHelper.setToken(requireContext(), "")
val token = sharedPref?.getString("token", "")
if (token != "") {
with(sharedPref!!.edit()) {
putString("token", "")
apply()
}
}
} }
} }

View File

@ -1,7 +1,6 @@
package com.github.libretube.dialogs package com.github.libretube.dialogs
import android.app.Dialog import android.app.Dialog
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.util.TypedValue import android.util.TypedValue
@ -15,6 +14,7 @@ import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.Login import com.github.libretube.obj.Login
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import retrofit2.HttpException import retrofit2.HttpException
@ -29,23 +29,17 @@ class LoginDialog : DialogFragment() {
val builder = MaterialAlertDialogBuilder(it) val builder = MaterialAlertDialogBuilder(it)
// Get the layout inflater // Get the layout inflater
val inflater = requireActivity().layoutInflater val inflater = requireActivity().layoutInflater
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
val token = sharedPref?.getString("token", "")
var view: View var view: View
Log.e("dafaq", token!!) Log.e("dafaq", token!!)
if (token != "") { if (token != "") {
val sharedPref2 = context?.getSharedPreferences("username", Context.MODE_PRIVATE) val user = PreferenceHelper.getUsername(requireContext())
val user = sharedPref2?.getString("username", "")
view = inflater.inflate(R.layout.dialog_logout, null) view = inflater.inflate(R.layout.dialog_logout, null)
view.findViewById<TextView>(R.id.user).text = view.findViewById<TextView>(R.id.user).text =
view.findViewById<TextView>(R.id.user).text.toString() + " (" + user + ")" view.findViewById<TextView>(R.id.user).text.toString() + " (" + user + ")"
view.findViewById<Button>(R.id.logout).setOnClickListener { view.findViewById<Button>(R.id.logout).setOnClickListener {
Toast.makeText(context, R.string.loggedout, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.loggedout, Toast.LENGTH_SHORT).show()
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) PreferenceHelper.setToken(requireContext(), "")
with(sharedPref!!.edit()) {
putString("token", "")
apply()
}
dialog?.dismiss() dialog?.dismiss()
} }
} else { } else {
@ -99,24 +93,15 @@ class LoginDialog : DialogFragment() {
Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show()
return@launchWhenCreated return@launchWhenCreated
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "dafaq?" + e.toString()) Log.e(TAG, "dafaq?$e")
return@launchWhenCreated return@launchWhenCreated
} }
if (response.error != null) { if (response.error != null) {
Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show() Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show()
} else if (response.token != null) { } else if (response.token != null) {
Toast.makeText(context, R.string.loggedIn, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.loggedIn, Toast.LENGTH_SHORT).show()
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) PreferenceHelper.setToken(requireContext(), response.token!!)
with(sharedPref!!.edit()) { PreferenceHelper.setUsername(requireContext(), login.username!!)
putString("token", response.token)
apply()
}
val sharedPref2 =
context?.getSharedPreferences("username", Context.MODE_PRIVATE)
with(sharedPref2!!.edit()) {
putString("username", login.username)
apply()
}
dialog?.dismiss() dialog?.dismiss()
} }
} }
@ -139,24 +124,15 @@ class LoginDialog : DialogFragment() {
Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.server_error, Toast.LENGTH_SHORT).show()
return@launchWhenCreated return@launchWhenCreated
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "dafaq?" + e.toString()) Log.e(TAG, "dafaq?$e")
return@launchWhenCreated return@launchWhenCreated
} }
if (response.error != null) { if (response.error != null) {
Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show() Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show()
} else if (response.token != null) { } else if (response.token != null) {
Toast.makeText(context, R.string.registered, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.registered, Toast.LENGTH_SHORT).show()
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) PreferenceHelper.setToken(requireContext(), response.token!!)
with(sharedPref!!.edit()) { PreferenceHelper.setUsername(requireContext(), login.username!!)
putString("token", response.token)
apply()
}
val sharedPref2 =
context?.getSharedPreferences("username", Context.MODE_PRIVATE)
with(sharedPref2!!.edit()) {
putString("username", login.username)
apply()
}
dialog?.dismiss() dialog?.dismiss()
} }
} }

View File

@ -9,6 +9,7 @@ import android.widget.Toast
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.obj.PlaylistId import com.github.libretube.obj.PlaylistId
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@ -43,9 +44,7 @@ class PlaylistOptionsDialog(
when (which) { when (which) {
// Clone the playlist to the users Piped account // Clone the playlist to the users Piped account
0 -> { 0 -> {
val sharedPref = val token = PreferenceHelper.getToken(requireContext())
context?.getSharedPreferences("token", Context.MODE_PRIVATE)
val token = sharedPref?.getString("token", "")
if (token != "") { if (token != "") {
importPlaylist(token!!, playlistId) importPlaylist(token!!, playlistId)
} else { } else {

View File

@ -4,8 +4,8 @@ import android.app.Dialog
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import androidx.preference.PreferenceManager
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
class ShareDialog( class ShareDialog(
@ -54,35 +54,19 @@ class ShareDialog(
// get the frontend url if it's a custom instance // get the frontend url if it's a custom instance
private fun getCustomInstanceFrontendUrl(): String { private fun getCustomInstanceFrontendUrl(): String {
val sharedPreferences = val instancePref = PreferenceHelper.getString(
PreferenceManager.getDefaultSharedPreferences(requireContext()) requireContext(),
val instancePref = sharedPreferences.getString(
"selectInstance", "selectInstance",
"https://pipedapi.kavin.rocks" "https://pipedapi.kavin.rocks"
) )
// get the api urls of the other custom instances // get the api urls of the other custom instances
var customInstancesUrls = try { val customInstances = PreferenceHelper.getCustomInstances(requireContext())
sharedPreferences
.getStringSet("custom_instances_url", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
// get the frontend urls of the other custom instances
var customInstancesFrontendUrls = try {
sharedPreferences
.getStringSet("custom_instances_url", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
// return the custom instance frontend url if available // return the custom instance frontend url if available
return if (customInstancesUrls.contains(instancePref)) { customInstances.forEach { instance ->
val index = customInstancesUrls.indexOf(instancePref) if (instance.apiUrl == instancePref) return instance.apiUrl
return customInstancesFrontendUrls[index]
} else {
""
} }
return ""
} }
} }

View File

@ -8,6 +8,7 @@ import android.widget.Toast
import androidx.fragment.app.DialogFragment import androidx.fragment.app.DialogFragment
import com.github.libretube.BackgroundMode import com.github.libretube.BackgroundMode
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.util.PreferenceHelper
import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.dialog.MaterialAlertDialogBuilder
/** /**
@ -50,11 +51,7 @@ class VideoOptionsDialog(private val videoId: String, context: Context) : Dialog
} }
// Add Video to Playlist Dialog // Add Video to Playlist Dialog
1 -> { 1 -> {
val sharedPref = context?.getSharedPreferences( val token = PreferenceHelper.getToken(requireContext())
"token",
Context.MODE_PRIVATE
)
val token = sharedPref?.getString("token", "")
if (token != "") { if (token != "") {
val newFragment = AddtoPlaylistDialog() val newFragment = AddtoPlaylistDialog()
val bundle = Bundle() val bundle = Bundle()

View File

@ -1,7 +1,6 @@
package com.github.libretube.fragments package com.github.libretube.fragments
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
@ -18,6 +17,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.adapters.ChannelAdapter import com.github.libretube.adapters.ChannelAdapter
import com.github.libretube.obj.Subscribe import com.github.libretube.obj.Subscribe
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.github.libretube.util.formatShort import com.github.libretube.util.formatShort
import com.google.android.material.button.MaterialButton import com.google.android.material.button.MaterialButton
@ -63,9 +63,8 @@ class ChannelFragment : Fragment() {
val refreshChannel = { val refreshChannel = {
refreshLayout?.isRefreshing = true refreshLayout?.isRefreshing = true
fetchChannel(view) fetchChannel(view)
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE)
val subButton = view.findViewById<MaterialButton>(R.id.channel_subscribe) val subButton = view.findViewById<MaterialButton>(R.id.channel_subscribe)
if (sharedPref?.getString("token", "") != "") { if (PreferenceHelper.getToken(requireContext()) != "") {
isSubscribed(subButton) isSubscribed(subButton)
} }
} }
@ -95,10 +94,10 @@ class ChannelFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.isSubscribed( RetrofitInstance.api.isSubscribed(
channel_id!!, channel_id!!,
sharedPref?.getString("token", "")!! token
) )
} catch (e: IOException) { } catch (e: IOException) {
println(e) println(e)
@ -135,9 +134,9 @@ class ChannelFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.subscribe( RetrofitInstance.api.subscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channel_id) Subscribe(channel_id)
) )
} catch (e: IOException) { } catch (e: IOException) {
@ -158,9 +157,9 @@ class ChannelFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.unsubscribe( RetrofitInstance.api.unsubscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channel_id) Subscribe(channel_id)
) )
} catch (e: IOException) { } catch (e: IOException) {

View File

@ -1,6 +1,5 @@
package com.github.libretube.fragments package com.github.libretube.fragments
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
@ -17,6 +16,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.adapters.PlaylistsAdapter import com.github.libretube.adapters.PlaylistsAdapter
import com.github.libretube.dialogs.CreatePlaylistDialog import com.github.libretube.dialogs.CreatePlaylistDialog
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.floatingactionbutton.FloatingActionButton
import retrofit2.HttpException import retrofit2.HttpException
@ -47,8 +47,7 @@ class Library : Fragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
playlistRecyclerView = view.findViewById(R.id.playlist_recView) playlistRecyclerView = view.findViewById(R.id.playlist_recView)
playlistRecyclerView.layoutManager = LinearLayoutManager(view.context) playlistRecyclerView.layoutManager = LinearLayoutManager(view.context)
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) token = PreferenceHelper.getToken(requireContext())
token = sharedPref?.getString("token", "")!!
refreshLayout = view.findViewById(R.id.playlist_refresh) refreshLayout = view.findViewById(R.id.playlist_refresh)
if (token != "") { if (token != "") {
view.findViewById<ImageView>(R.id.boogh2).visibility = View.GONE view.findViewById<ImageView>(R.id.boogh2).visibility = View.GONE
@ -59,8 +58,7 @@ class Library : Fragment() {
Log.d(TAG, "hmm") Log.d(TAG, "hmm")
fetchPlaylists(view) fetchPlaylists(view)
} }
view.findViewById<com.google.android.material.floatingactionbutton view.findViewById<FloatingActionButton>(R.id.create_playlist).setOnClickListener {
.FloatingActionButton>(R.id.create_playlist).setOnClickListener {
val newFragment = CreatePlaylistDialog() val newFragment = CreatePlaylistDialog()
newFragment.show(childFragmentManager, "Create Playlist") newFragment.show(childFragmentManager, "Create Playlist")
} }

View File

@ -34,7 +34,6 @@ import androidx.core.os.bundleOf
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -52,10 +51,10 @@ import com.github.libretube.obj.ChapterSegment
import com.github.libretube.obj.PipedStream import com.github.libretube.obj.PipedStream
import com.github.libretube.obj.Segment import com.github.libretube.obj.Segment
import com.github.libretube.obj.Segments import com.github.libretube.obj.Segments
import com.github.libretube.obj.SponsorBlockPrefs
import com.github.libretube.obj.StreamItem import com.github.libretube.obj.StreamItem
import com.github.libretube.obj.Streams import com.github.libretube.obj.Streams
import com.github.libretube.obj.Subscribe import com.github.libretube.obj.Subscribe
import com.github.libretube.preferences.SponsorBlockSettings
import com.github.libretube.util.CronetHelper import com.github.libretube.util.CronetHelper
import com.github.libretube.util.DescriptionAdapter import com.github.libretube.util.DescriptionAdapter
import com.github.libretube.util.PreferenceHelper import com.github.libretube.util.PreferenceHelper
@ -131,6 +130,7 @@ class PlayerFragment : Fragment() {
private lateinit var title: String private lateinit var title: String
private lateinit var uploader: String private lateinit var uploader: String
private lateinit var thumbnailUrl: String private lateinit var thumbnailUrl: String
private val sponsorBlockPrefs = SponsorBlockPrefs()
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -152,6 +152,7 @@ class PlayerFragment : Fragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
hideKeyboard() hideKeyboard()
setSponsorBlockPrefs()
initializeTransitionLayout(view) initializeTransitionLayout(view)
fetchJsonAndInitPlayer(view) fetchJsonAndInitPlayer(view)
} }
@ -382,7 +383,7 @@ class PlayerFragment : Fragment() {
} }
private fun checkForSegments() { private fun checkForSegments() {
if (!exoPlayer.isPlaying || !SponsorBlockSettings.sponsorBlockEnabled) return if (!exoPlayer.isPlaying || !sponsorBlockPrefs.sponsorBlockEnabled) return
exoPlayerView.postDelayed(this::checkForSegments, 100) exoPlayerView.postDelayed(this::checkForSegments, 100)
@ -395,7 +396,7 @@ class PlayerFragment : Fragment() {
val segmentEnd = (segment.segment[1] * 1000.0f).toLong() val segmentEnd = (segment.segment[1] * 1000.0f).toLong()
val currentPosition = exoPlayer.currentPosition val currentPosition = exoPlayer.currentPosition
if (currentPosition in segmentStart until segmentEnd) { if (currentPosition in segmentStart until segmentEnd) {
if (SponsorBlockSettings.sponsorNotificationsEnabled) { if (sponsorBlockPrefs.sponsorNotificationsEnabled) {
Toast.makeText(context, R.string.segment_skipped, Toast.LENGTH_SHORT).show() Toast.makeText(context, R.string.segment_skipped, Toast.LENGTH_SHORT).show()
} }
exoPlayer.seekTo(segmentEnd) exoPlayer.seekTo(segmentEnd)
@ -424,10 +425,9 @@ class PlayerFragment : Fragment() {
thumbnailUrl = response.thumbnailUrl!! thumbnailUrl = response.thumbnailUrl!!
// check whether related streams and autoplay are enabled // check whether related streams and autoplay are enabled
val sharedPreferences = PreferenceManager autoplay = PreferenceHelper.getBoolean(requireContext(), "autoplay", false)
.getDefaultSharedPreferences(requireContext()) relatedStreamsEnabled =
autoplay = sharedPreferences.getBoolean("autoplay", false) PreferenceHelper.getBoolean(requireContext(), "related_streams_toggle", true)
relatedStreamsEnabled = sharedPreferences.getBoolean("related_streams_toggle", true)
// save related streams for autoplay // save related streams for autoplay
relatedStreams = response.relatedStreams relatedStreams = response.relatedStreams
runOnUiThread { runOnUiThread {
@ -452,33 +452,56 @@ class PlayerFragment : Fragment() {
run() run()
} }
private fun setSponsorBlockPrefs() {
sponsorBlockPrefs.sponsorBlockEnabled =
PreferenceHelper.getBoolean(requireContext(), "sb_enabled_key", true)
sponsorBlockPrefs.sponsorNotificationsEnabled =
PreferenceHelper.getBoolean(requireContext(), "sb_notifications_key", true)
sponsorBlockPrefs.introEnabled =
PreferenceHelper.getBoolean(requireContext(), "intro_category_key", false)
sponsorBlockPrefs.selfPromoEnabled =
PreferenceHelper.getBoolean(requireContext(), "selfpromo_category_key", false)
sponsorBlockPrefs.interactionEnabled =
PreferenceHelper.getBoolean(requireContext(), "interaction_category_key", false)
sponsorBlockPrefs.sponsorsEnabled =
PreferenceHelper.getBoolean(requireContext(), "sponsors_category_key", true)
sponsorBlockPrefs.outroEnabled =
PreferenceHelper.getBoolean(requireContext(), "outro_category_key", false)
sponsorBlockPrefs.fillerEnabled =
PreferenceHelper.getBoolean(requireContext(), "filler_category_key", false)
sponsorBlockPrefs.musicOffTopicEnabled =
PreferenceHelper.getBoolean(requireContext(), "music_offtopic_category_key", false)
sponsorBlockPrefs.previewEnabled =
PreferenceHelper.getBoolean(requireContext(), "preview_category_key", false)
}
private fun fetchSponsorBlockSegments() { private fun fetchSponsorBlockSegments() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
if (SponsorBlockSettings.sponsorBlockEnabled) { if (sponsorBlockPrefs.sponsorBlockEnabled) {
val categories: ArrayList<String> = arrayListOf() val categories: ArrayList<String> = arrayListOf()
if (SponsorBlockSettings.introEnabled) { if (sponsorBlockPrefs.introEnabled) {
categories.add("intro") categories.add("intro")
} }
if (SponsorBlockSettings.selfPromoEnabled) { if (sponsorBlockPrefs.selfPromoEnabled) {
categories.add("selfpromo") categories.add("selfpromo")
} }
if (SponsorBlockSettings.interactionEnabled) { if (sponsorBlockPrefs.interactionEnabled) {
categories.add("interaction") categories.add("interaction")
} }
if (SponsorBlockSettings.sponsorsEnabled) { if (sponsorBlockPrefs.sponsorsEnabled) {
categories.add("sponsor") categories.add("sponsor")
} }
if (SponsorBlockSettings.outroEnabled) { if (sponsorBlockPrefs.outroEnabled) {
categories.add("outro") categories.add("outro")
} }
if (SponsorBlockSettings.fillerEnabled) { if (sponsorBlockPrefs.fillerEnabled) {
categories.add("filler") categories.add("filler")
} }
if (SponsorBlockSettings.musicOfftopicEnabled) { if (sponsorBlockPrefs.musicOffTopicEnabled) {
categories.add("music_offtopic") categories.add("music_offtopic")
} }
if (SponsorBlockSettings.previewEnabled) { if (sponsorBlockPrefs.previewEnabled) {
categories.add("preview") categories.add("preview")
} }
if (categories.size > 0) { if (categories.size > 0) {
@ -534,7 +557,7 @@ class PlayerFragment : Fragment() {
// Listener for play and pause icon change // Listener for play and pause icon change
exoPlayer.addListener(object : Player.Listener { exoPlayer.addListener(object : Player.Listener {
override fun onIsPlayingChanged(isPlaying: Boolean) { override fun onIsPlayingChanged(isPlaying: Boolean) {
if (isPlaying && SponsorBlockSettings.sponsorBlockEnabled) { if (isPlaying && sponsorBlockPrefs.sponsorBlockEnabled) {
exoPlayerView.postDelayed( exoPlayerView.postDelayed(
this@PlayerFragment::checkForSegments, this@PlayerFragment::checkForSegments,
100 100
@ -656,8 +679,8 @@ class PlayerFragment : Fragment() {
activity.findViewById<MotionLayout>(R.id.mainMotionLayout).transitionToEnd() activity.findViewById<MotionLayout>(R.id.mainMotionLayout).transitionToEnd()
view.findViewById<MotionLayout>(R.id.playerMotionLayout).transitionToEnd() view.findViewById<MotionLayout>(R.id.playerMotionLayout).transitionToEnd()
} }
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
if (sharedPref?.getString("token", "") != "") { if (token != "") {
val channelId = response.uploaderUrl?.replace("/channel/", "") val channelId = response.uploaderUrl?.replace("/channel/", "")
val subButton = view.findViewById<MaterialButton>(R.id.player_subscribe) val subButton = view.findViewById<MaterialButton>(R.id.player_subscribe)
isSubscribed(subButton, channelId!!) isSubscribed(subButton, channelId!!)
@ -720,7 +743,8 @@ class PlayerFragment : Fragment() {
} }
private fun setResolutionAndSubtitles(view: View, response: Streams) { private fun setResolutionAndSubtitles(view: View, response: Streams) {
val videoFormatPreference = PreferenceHelper.getString(requireContext(), "player_video_format", "WEBM") val videoFormatPreference =
PreferenceHelper.getString(requireContext(), "player_video_format", "WEBM")
val defres = PreferenceHelper.getString(requireContext(), "default_res", "")!! val defres = PreferenceHelper.getString(requireContext(), "default_res", "")!!
val qualityText = view.findViewById<TextView>(R.id.quality_text) val qualityText = view.findViewById<TextView>(R.id.quality_text)
@ -835,11 +859,13 @@ class PlayerFragment : Fragment() {
} }
private fun createExoPlayer(view: View) { private fun createExoPlayer(view: View) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) val playbackSpeed =
val playbackSpeed = sharedPreferences.getString("playback_speed", "1F")?.toFloat() PreferenceHelper.getString(requireContext(), "playback_speed", "1F")?.toFloat()
// multiply by thousand: s -> ms // multiply by thousand: s -> ms
val bufferingGoal = sharedPreferences.getString("buffering_goal", "50")?.toInt()!! * 1000 val bufferingGoal =
val seekIncrement = sharedPreferences.getString("seek_increment", "5")?.toLong()!! * 1000 PreferenceHelper.getString(requireContext(), "buffering_goal", "50")?.toInt()!! * 1000
val seekIncrement =
PreferenceHelper.getString(requireContext(), "seek_increment", "5")?.toLong()!! * 1000
val cronetEngine: CronetEngine = CronetHelper.getCronetEngine() val cronetEngine: CronetEngine = CronetHelper.getCronetEngine()
val cronetDataSourceFactory: CronetDataSource.Factory = val cronetDataSourceFactory: CronetDataSource.Factory =
@ -918,10 +944,10 @@ class PlayerFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.isSubscribed( RetrofitInstance.api.isSubscribed(
channel_id, channel_id,
sharedPref?.getString("token", "")!! token
) )
} catch (e: IOException) { } catch (e: IOException) {
println(e) println(e)
@ -958,9 +984,9 @@ class PlayerFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.subscribe( RetrofitInstance.api.subscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channel_id) Subscribe(channel_id)
) )
} catch (e: IOException) { } catch (e: IOException) {
@ -981,9 +1007,9 @@ class PlayerFragment : Fragment() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
RetrofitInstance.api.unsubscribe( RetrofitInstance.api.unsubscribe(
sharedPref?.getString("token", "")!!, token,
Subscribe(channel_id) Subscribe(channel_id)
) )
} catch (e: IOException) { } catch (e: IOException) {

View File

@ -1,6 +1,5 @@
package com.github.libretube.fragments package com.github.libretube.fragments
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
@ -15,6 +14,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.adapters.PlaylistAdapter import com.github.libretube.adapters.PlaylistAdapter
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import retrofit2.HttpException import retrofit2.HttpException
import java.io.IOException import java.io.IOException
@ -75,9 +75,7 @@ class PlaylistFragment : Fragment() {
view.findViewById<TextView>(R.id.playlist_uploader).text = response.uploader view.findViewById<TextView>(R.id.playlist_uploader).text = response.uploader
view.findViewById<TextView>(R.id.playlist_totVideos).text = view.findViewById<TextView>(R.id.playlist_totVideos).text =
getString(R.string.videoCount, response.videos.toString()) getString(R.string.videoCount, response.videos.toString())
val sharedPref2 = val user = PreferenceHelper.getUsername(requireContext())
context?.getSharedPreferences("username", Context.MODE_PRIVATE)
val user = sharedPref2?.getString("username", "")
var isOwner = false var isOwner = false
if (response.uploaderUrl == null && response.uploader.equals(user, true)) { if (response.uploaderUrl == null && response.uploader.equals(user, true)) {
isOwner = true isOwner = true

View File

@ -18,7 +18,6 @@ import android.widget.TextView.OnEditorActionListener
import android.widget.TextView.VISIBLE import android.widget.TextView.VISIBLE
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -267,7 +266,7 @@ class SearchFragment : Fragment() {
private fun showHistory() { private fun showHistory() {
searchRecView.visibility = GONE searchRecView.visibility = GONE
val historyList = getHistory() val historyList = PreferenceHelper.getHistory(requireContext())
if (historyList.isNotEmpty()) { if (historyList.isNotEmpty()) {
historyRecView.adapter = historyRecView.adapter =
SearchHistoryAdapter(requireContext(), historyList, autoTextView, this) SearchHistoryAdapter(requireContext(), historyList, autoTextView, this)
@ -276,10 +275,10 @@ class SearchFragment : Fragment() {
} }
private fun addToHistory(query: String) { private fun addToHistory(query: String) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) val searchHistoryEnabled =
val searchHistoryEnabled = PreferenceHelper.getBoolean(requireContext(), "search_history_toggle", true) PreferenceHelper.getBoolean(requireContext(), "search_history_toggle", true)
if (searchHistoryEnabled) { if (searchHistoryEnabled) {
var historyList = getHistory() var historyList = PreferenceHelper.getHistory(requireContext())
if ((historyList.isNotEmpty() && historyList.contains(query)) || query == "") { if ((historyList.isNotEmpty() && historyList.contains(query)) || query == "") {
return return
@ -291,20 +290,7 @@ class SearchFragment : Fragment() {
historyList = historyList.takeLast(10) historyList = historyList.takeLast(10)
} }
val set: Set<String> = HashSet(historyList) PreferenceHelper.saveHistory(requireContext(), historyList)
sharedPreferences.edit().putStringSet("search_history", set)
.apply()
}
}
private fun getHistory(): List<String> {
return try {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val set: Set<String> = sharedPreferences.getStringSet("search_history", HashSet())!!
set.toList()
} catch (e: Exception) {
emptyList()
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.github.libretube.fragments package com.github.libretube.fragments
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import android.view.LayoutInflater import android.view.LayoutInflater
@ -15,7 +14,6 @@ import android.widget.Toast
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
@ -23,6 +21,7 @@ import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.adapters.SubscriptionAdapter import com.github.libretube.adapters.SubscriptionAdapter
import com.github.libretube.adapters.SubscriptionChannelAdapter import com.github.libretube.adapters.SubscriptionChannelAdapter
import com.github.libretube.util.PreferenceHelper
import com.github.libretube.util.RetrofitInstance import com.github.libretube.util.RetrofitInstance
import retrofit2.HttpException import retrofit2.HttpException
import java.io.IOException import java.io.IOException
@ -50,8 +49,7 @@ class Subscriptions : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) token = PreferenceHelper.getToken(requireContext())
token = sharedPref?.getString("token", "")!!
refreshLayout = view.findViewById(R.id.sub_refresh) refreshLayout = view.findViewById(R.id.sub_refresh)
if (token != "") { if (token != "") {
view.findViewById<RelativeLayout>(R.id.loginOrRegister).visibility = View.GONE view.findViewById<RelativeLayout>(R.id.loginOrRegister).visibility = View.GONE
@ -63,8 +61,8 @@ class Subscriptions : Fragment() {
var channelRecView = view.findViewById<RecyclerView>(R.id.sub_channels) var channelRecView = view.findViewById<RecyclerView>(R.id.sub_channels)
var feedRecView = view.findViewById<RecyclerView>(R.id.sub_feed) var feedRecView = view.findViewById<RecyclerView>(R.id.sub_feed)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) val grid = PreferenceHelper.getString(
val grid = sharedPreferences.getString( requireContext(),
"grid", "grid",
resources.getInteger(R.integer.grid_items).toString() resources.getInteger(R.integer.grid_items).toString()
)!! )!!

View File

@ -0,0 +1,7 @@
package com.github.libretube.obj
class CustomInstance(
var name: String = "",
var apiUrl: String = "",
var frontendUrl: String = ""
)

View File

@ -0,0 +1,14 @@
package com.github.libretube.obj
class SponsorBlockPrefs(
var sponsorBlockEnabled: Boolean = false,
var sponsorNotificationsEnabled: Boolean = false,
var sponsorsEnabled: Boolean = false,
var selfPromoEnabled: Boolean = false,
var interactionEnabled: Boolean = false,
var introEnabled: Boolean = false,
var outroEnabled: Boolean = false,
var fillerEnabled: Boolean = false,
var musicOffTopicEnabled: Boolean = false,
var previewEnabled: Boolean = false
)

View File

@ -1,6 +1,5 @@
package com.github.libretube.preferences package com.github.libretube.preferences
import android.content.Context
import android.os.Bundle import android.os.Bundle
import android.widget.TextView import android.widget.TextView
import androidx.preference.Preference import androidx.preference.Preference
@ -39,9 +38,7 @@ class AdvancedSettings : PreferenceFragmentCompat() {
PreferenceHelper.clearPreferences(requireContext()) PreferenceHelper.clearPreferences(requireContext())
// clear login token // clear login token
val sharedPrefToken = PreferenceHelper.setToken(requireContext(), "")
context?.getSharedPreferences("token", Context.MODE_PRIVATE)
sharedPrefToken?.edit()?.clear()?.commit()
requireMainActivityRestart = true requireMainActivityRestart = true
activity?.recreate() activity?.recreate()

View File

@ -21,7 +21,7 @@ class AppearanceSettings : PreferenceFragmentCompat() {
val themeToggle = findPreference<ListPreference>("theme_togglee") val themeToggle = findPreference<ListPreference>("theme_togglee")
themeToggle?.setOnPreferenceChangeListener { _, _ -> themeToggle?.setOnPreferenceChangeListener { _, _ ->
requireMainActivityRestart = true requireMainActivityRestart = true
ThemeHelper().restartMainActivity(requireContext()) ThemeHelper.restartMainActivity(requireContext())
true true
} }
@ -34,7 +34,7 @@ class AppearanceSettings : PreferenceFragmentCompat() {
val iconChange = findPreference<ListPreference>("icon_change") val iconChange = findPreference<ListPreference>("icon_change")
iconChange?.setOnPreferenceChangeListener { _, newValue -> iconChange?.setOnPreferenceChangeListener { _, newValue ->
ThemeHelper().changeIcon(requireContext(), newValue.toString()) ThemeHelper.changeIcon(requireContext(), newValue.toString())
true true
} }

View File

@ -2,7 +2,6 @@ package com.github.libretube.preferences
import android.Manifest import android.Manifest
import android.content.ContentResolver import android.content.ContentResolver
import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.os.Build import android.os.Build
@ -19,7 +18,6 @@ import androidx.lifecycle.lifecycleScope
import androidx.preference.ListPreference import androidx.preference.ListPreference
import androidx.preference.Preference import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import com.github.libretube.R import com.github.libretube.R
import com.github.libretube.dialogs.CustomInstanceDialog import com.github.libretube.dialogs.CustomInstanceDialog
import com.github.libretube.dialogs.DeleteAccountDialog import com.github.libretube.dialogs.DeleteAccountDialog
@ -135,9 +133,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val clearCustomInstances = findPreference<Preference>("clearCustomInstances") val clearCustomInstances = findPreference<Preference>("clearCustomInstances")
clearCustomInstances?.setOnPreferenceClickListener { clearCustomInstances?.setOnPreferenceClickListener {
PreferenceHelper.removePreference(requireContext(), "custom_instances_name") PreferenceHelper.removePreference(requireContext(), "customInstances")
PreferenceHelper.removePreference(requireContext(), "custom_instances_url")
PreferenceHelper.removePreference(requireContext(), "custom_instances_frontend_url")
activity?.recreate() activity?.recreate()
true true
} }
@ -152,8 +148,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val deleteAccount = findPreference<Preference>("delete_account") val deleteAccount = findPreference<Preference>("delete_account")
deleteAccount?.setOnPreferenceClickListener { deleteAccount?.setOnPreferenceClickListener {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
val token = sharedPref?.getString("token", "")
if (token != "") { if (token != "") {
val newFragment = DeleteAccountDialog() val newFragment = DeleteAccountDialog()
newFragment.show(childFragmentManager, "DeleteAccountDialog") newFragment.show(childFragmentManager, "DeleteAccountDialog")
@ -165,8 +160,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val importFromYt = findPreference<Preference>("import_from_yt") val importFromYt = findPreference<Preference>("import_from_yt")
importFromYt?.setOnPreferenceClickListener { importFromYt?.setOnPreferenceClickListener {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) val token = PreferenceHelper.getToken(requireContext())
val token = sharedPref?.getString("token", "")
// check StorageAccess // check StorageAccess
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Log.d("myz", "" + Build.VERSION.SDK_INT) Log.d("myz", "" + Build.VERSION.SDK_INT)
@ -218,27 +212,15 @@ class InstanceSettings : PreferenceFragmentCompat() {
} }
private fun initCustomInstances() { private fun initCustomInstances() {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) val customInstances = PreferenceHelper.getCustomInstances(requireContext())
// get the names of the custom instances var instanceNames = resources.getStringArray(R.array.instances)
val customInstancesNames = try { var instanceValues = resources.getStringArray(R.array.instancesValue)
sharedPreferences customInstances.forEach { instance ->
.getStringSet("custom_instances_name", HashSet())!!.toList() instanceNames += instance.name
} catch (e: Exception) { instanceValues += instance.apiUrl
emptyList()
} }
// get the urls of the custom instances
val customInstancesUrls = try {
sharedPreferences
.getStringSet("custom_instances_url", HashSet())!!.toList()
} catch (e: Exception) {
emptyList()
}
val instanceNames = resources.getStringArray(R.array.instances) + customInstancesNames
val instanceValues = resources.getStringArray(R.array.instancesValue) + customInstancesUrls
// add custom instances to the list preference // add custom instances to the list preference
val instance = findPreference<ListPreference>("selectInstance") val instance = findPreference<ListPreference>("selectInstance")
instance?.entries = instanceNames instance?.entries = instanceNames
@ -255,15 +237,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
} }
private fun logout() { private fun logout() {
val sharedPref = context?.getSharedPreferences("token", Context.MODE_PRIVATE) PreferenceHelper.setToken(requireContext(), "")
val token = sharedPref?.getString("token", "")
if (token != "") {
with(sharedPref!!.edit()) {
putString("token", "")
apply()
}
Toast.makeText(context, R.string.loggedout, Toast.LENGTH_SHORT).show()
}
} }
private fun fetchInstance() { private fun fetchInstance() {
@ -319,11 +293,10 @@ class InstanceSettings : PreferenceFragmentCompat() {
fun run() { fun run() {
lifecycleScope.launchWhenCreated { lifecycleScope.launchWhenCreated {
val response = try { val response = try {
val sharedPref = val token = PreferenceHelper.getToken(requireContext())
context?.getSharedPreferences("token", Context.MODE_PRIVATE)
RetrofitInstance.api.importSubscriptions( RetrofitInstance.api.importSubscriptions(
false, false,
sharedPref?.getString("token", "")!!, token,
channels channels
) )
} catch (e: IOException) { } catch (e: IOException) {

View File

@ -31,7 +31,7 @@ class MainSettings : PreferenceFragmentCompat() {
val language = findPreference<ListPreference>("language") val language = findPreference<ListPreference>("language")
language?.setOnPreferenceChangeListener { _, _ -> language?.setOnPreferenceChangeListener { _, _ ->
ThemeHelper().restartMainActivity(requireContext()) ThemeHelper.restartMainActivity(requireContext())
true true
} }

View File

@ -3,88 +3,15 @@ package com.github.libretube.preferences
import android.os.Bundle import android.os.Bundle
import android.widget.TextView import android.widget.TextView
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.github.libretube.R import com.github.libretube.R
class SponsorBlockSettings : PreferenceFragmentCompat() { class SponsorBlockSettings : PreferenceFragmentCompat() {
private val TAG = "SponsorBlockSettings" private val TAG = "SponsorBlockSettings"
companion object {
var sponsorBlockEnabled: Boolean = false
var sponsorNotificationsEnabled: Boolean = false
var sponsorsEnabled: Boolean = false
var selfPromoEnabled: Boolean = false
var interactionEnabled: Boolean = false
var introEnabled: Boolean = false
var outroEnabled: Boolean = false
var fillerEnabled: Boolean = false
var musicOfftopicEnabled: Boolean = false
var previewEnabled: Boolean = false
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.sponsorblock_settings, rootKey) setPreferencesFromResource(R.xml.sponsorblock_settings, rootKey)
val topBarTextView = activity?.findViewById<TextView>(R.id.topBar_textView) val topBarTextView = activity?.findViewById<TextView>(R.id.topBar_textView)
topBarTextView?.text = getString(R.string.sponsorblock) topBarTextView?.text = getString(R.string.sponsorblock)
val sponsorBlockToggle = findPreference<SwitchPreferenceCompat>("sb_enabled_key")
sponsorBlockToggle?.setOnPreferenceChangeListener { _, newValue ->
sponsorBlockEnabled = newValue as Boolean
true
}
val notificationsToggle = findPreference<SwitchPreferenceCompat>("sb_notifications_key")
notificationsToggle?.setOnPreferenceChangeListener { _, newValue ->
sponsorNotificationsEnabled = newValue as Boolean
true
}
val sponsorToggle = findPreference<SwitchPreferenceCompat>("sponsors_category_key")
sponsorToggle?.setOnPreferenceChangeListener { _, newValue ->
sponsorsEnabled = newValue as Boolean
true
}
val selfPromoToggle = findPreference<SwitchPreferenceCompat>("selfpromo_category_key")
selfPromoToggle?.setOnPreferenceChangeListener { _, newValue ->
selfPromoEnabled = newValue as Boolean
true
}
val interactionToggle = findPreference<SwitchPreferenceCompat>("interaction_category_key")
interactionToggle?.setOnPreferenceChangeListener { _, newValue ->
interactionEnabled = newValue as Boolean
true
}
val introToggle = findPreference<SwitchPreferenceCompat>("intro_category_key")
introToggle?.setOnPreferenceChangeListener { _, newValue ->
introEnabled = newValue as Boolean
true
}
val outroToggle = findPreference<SwitchPreferenceCompat>("outro_category_key")
outroToggle?.setOnPreferenceChangeListener { _, newValue ->
outroEnabled = newValue as Boolean
true
}
val fillerToggle = findPreference<SwitchPreferenceCompat>("filler_category_key")
fillerToggle?.setOnPreferenceChangeListener { _, newValue ->
fillerEnabled = newValue as Boolean
true
}
val musicToggle = findPreference<SwitchPreferenceCompat>("music_offtopic_category_key")
musicToggle?.setOnPreferenceChangeListener { _, newValue ->
musicOfftopicEnabled = newValue as Boolean
true
}
val previewToggle = findPreference<SwitchPreferenceCompat>("preview_category_key")
previewToggle?.setOnPreferenceChangeListener { _, newValue ->
previewEnabled = newValue as Boolean
true
}
} }
} }

View File

@ -4,7 +4,7 @@ import android.content.Context
import android.os.Build import android.os.Build
import java.util.* import java.util.*
class LocaleHelper { object LocaleHelper {
fun updateLanguage(context: Context) { fun updateLanguage(context: Context) {
val languageName = PreferenceHelper.getString(context, "language", "en") val languageName = PreferenceHelper.getString(context, "language", "en")

View File

@ -3,6 +3,10 @@ package com.github.libretube.util
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import com.github.libretube.obj.CustomInstance
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import java.lang.reflect.Type
object PreferenceHelper { object PreferenceHelper {
fun setString(context: Context, key: String?, value: String?) { fun setString(context: Context, key: String?, value: String?) {
@ -61,9 +65,69 @@ object PreferenceHelper {
editor.commit() editor.commit()
} }
fun getToken(context: Context): String {
val sharedPref = context.getSharedPreferences("token", Context.MODE_PRIVATE)
return sharedPref?.getString("token", "")!!
}
fun setToken(context: Context, newValue: String) {
val editor = context.getSharedPreferences("token", Context.MODE_PRIVATE).edit()
editor.putString("token", newValue)
}
fun getUsername(context: Context): String {
val sharedPref = context.getSharedPreferences("username", Context.MODE_PRIVATE)
return sharedPref.getString("username", "")!!
}
fun setUsername(context: Context, newValue: String) {
val editor = context.getSharedPreferences("username", Context.MODE_PRIVATE).edit()
editor.putString("username", newValue)
}
fun saveCustomInstance(context: Context, customInstance: CustomInstance) {
val editor = getDefaultSharedPreferencesEditor(context)
val gson = Gson()
val customInstancesList = getCustomInstances(context)
customInstancesList += customInstance
val json = gson.toJson(customInstancesList)
editor.putString("customInstances", json).commit()
}
fun getCustomInstances(context: Context): ArrayList<CustomInstance> {
val settings = getDefaultSharedPreferences(context)
val gson = Gson()
val json: String = settings.getString("customInstances", "")!!
val type: Type = object : TypeToken<List<CustomInstance?>?>() {}.type
return try {
gson.fromJson(json, type)
} catch (e: Exception) {
arrayListOf()
}
}
fun getHistory(context: Context): List<String> {
return try {
val settings = getDefaultSharedPreferences(context)
val set: Set<String> = settings.getStringSet("search_history", HashSet())!!
set.toList()
} catch (e: Exception) {
emptyList()
}
}
fun saveHistory(context: Context, historyList: List<String>) {
val editor = getDefaultSharedPreferencesEditor(context)
val set: Set<String> = HashSet(historyList)
editor.putStringSet("search_history", set).apply()
}
private fun getDefaultSharedPreferences(context: Context): SharedPreferences { private fun getDefaultSharedPreferences(context: Context): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(context) return PreferenceManager.getDefaultSharedPreferences(context)
} }
private fun getDefaultSharedPreferencesEditor(context: Context): SharedPreferences.Editor { private fun getDefaultSharedPreferencesEditor(context: Context): SharedPreferences.Editor {
return getDefaultSharedPreferences(context).edit() return getDefaultSharedPreferences(context).edit()
} }

View File

@ -9,7 +9,7 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate
import com.github.libretube.R import com.github.libretube.R
class ThemeHelper { object ThemeHelper {
fun updateTheme(context: Context) { fun updateTheme(context: Context) {
updateAccentColor(context) updateAccentColor(context)

View File

@ -6,7 +6,7 @@
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:paddingVertical="5dp" > android:paddingVertical="5dp">
<ImageButton <ImageButton
android:id="@+id/back_imageButton" android:id="@+id/back_imageButton"

View File

@ -24,6 +24,6 @@
android:id="@+id/addToPlaylist" android:id="@+id/addToPlaylist"
android:text="@string/addToPlaylist" android:text="@string/addToPlaylist"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -41,7 +41,7 @@
android:id="@+id/create_new_playlist" android:id="@+id/create_new_playlist"
android:text="@string/createPlaylist" android:text="@string/createPlaylist"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -62,7 +62,7 @@
android:id="@+id/addInstance" android:id="@+id/addInstance"
android:text="@string/addInstance" android:text="@string/addInstance"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -40,7 +40,7 @@
android:id="@+id/delete_account_confirm" android:id="@+id/delete_account_confirm"
android:text="@string/deleteAccount" android:text="@string/deleteAccount"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -30,6 +30,6 @@
android:id="@+id/download" android:id="@+id/download"
android:text="@string/download" android:text="@string/download"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -52,7 +52,7 @@
android:id="@+id/login" android:id="@+id/login"
android:text="@string/login" android:text="@string/login"
style="@style/CustomDialogButton" style="@style/CustomDialogButton"
android:layout_marginRight="16dp"/> android:layout_marginRight="16dp" />
</LinearLayout> </LinearLayout>

View File

@ -54,7 +54,7 @@
android:padding="@dimen/exo_icon_padding" android:padding="@dimen/exo_icon_padding"
android:background="#00FFFFFF" android:background="#00FFFFFF"
app:tint="@android:color/white" app:tint="@android:color/white"
android:layout_marginRight="10dp"/> android:layout_marginRight="10dp" />
<ImageButton <ImageButton
android:id="@+id/lock_player" android:id="@+id/lock_player"
@ -162,7 +162,7 @@
<ImageButton <ImageButton
android:id="@+id/fullscreen" android:id="@+id/fullscreen"
style="@style/ExoStyledControls.Button.Bottom.FullScreen" style="@style/ExoStyledControls.Button.Bottom.FullScreen"
android:src="@drawable/ic_fullscreen"/> android:src="@drawable/ic_fullscreen" />
</LinearLayout> </LinearLayout>

View File

@ -17,6 +17,7 @@ mobileffmpeg = "4.5.1.LTS"
desugaring = "1.1.5" desugaring = "1.1.5"
cronetEmbedded = "101.4951.41" cronetEmbedded = "101.4951.41"
leakcanary = "2.8.1" leakcanary = "2.8.1"
gson = "2.9.0"
[libraries] [libraries]
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
@ -41,3 +42,4 @@ desugaring = { group = "com.android.tools", name = "desugar_jdk_libs", version.r
exoplayer-extension-cronet = { group = "com.google.android.exoplayer", name = "extension-cronet", version.ref = "exoplayer" } exoplayer-extension-cronet = { group = "com.google.android.exoplayer", name = "extension-cronet", version.ref = "exoplayer" }
cronet-embedded = { group = "org.chromium.net", name = "cronet-embedded", version.ref = "cronetEmbedded" } cronet-embedded = { group = "org.chromium.net", name = "cronet-embedded", version.ref = "cronetEmbedded" }
square-leakcanary = { group = "com.squareup.leakcanary", name = "leakcanary-android", version.ref = "leakcanary" } square-leakcanary = { group = "com.squareup.leakcanary", name = "leakcanary-android", version.ref = "leakcanary" }
gson = { group = "com.google.code.gson", name="gson", version.ref = "gson"}