Merge pull request #811 from Bnyro/master

add aspect ratio mode, cleanup & bug fixes
This commit is contained in:
Bnyro 2022-07-17 17:40:30 +02:00 committed by GitHub
commit 1e75077b0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 154 additions and 163 deletions

View File

@ -4,12 +4,21 @@ import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import com.github.libretube.preferences.PreferenceHelper
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
/**
* initialize the needed [NotificationChannel]s for DownloadService and BackgroundMode
*/
initializeNotificationChannels()
/**
* set the applicationContext as context for the [PreferenceHelper]
*/
PreferenceHelper.setContext(applicationContext)
}
/**
@ -46,9 +55,4 @@ class MyApp : Application() {
notificationManager.createNotificationChannel(channel)
}
}
companion object {
@JvmField
var seekTo: Long? = 0
}
}

View File

@ -62,12 +62,11 @@ class MainActivity : AppCompatActivity() {
CronetHelper.initCronet(this.applicationContext)
RetrofitInstance.url =
PreferenceHelper.getString(this, "selectInstance", PIPED_API_URL)!!
PreferenceHelper.getString("selectInstance", PIPED_API_URL)!!
// set auth instance
RetrofitInstance.authUrl =
if (PreferenceHelper.getBoolean(this, "auth_instance_toggle", false)) {
if (PreferenceHelper.getBoolean("auth_instance_toggle", false)) {
PreferenceHelper.getString(
this,
"selectAuthInstance",
PIPED_API_URL
)!!
@ -77,7 +76,6 @@ class MainActivity : AppCompatActivity() {
// save whether the data saver mode is enabled
Globals.dataSaverModeEnabled = PreferenceHelper.getBoolean(
this,
"data_saver_mode",
false
)
@ -100,12 +98,12 @@ class MainActivity : AppCompatActivity() {
window.navigationBarColor = color
// hide the trending page if enabled
val hideTrendingPage = PreferenceHelper.getBoolean(this, "hide_trending_page", false)
val hideTrendingPage = PreferenceHelper.getBoolean("hide_trending_page", false)
if (hideTrendingPage) binding.bottomNav.menu.findItem(R.id.homeFragment).isVisible =
false
// save start tab fragment id
startFragmentId = when (PreferenceHelper.getString(this, "default_tab", "home")) {
startFragmentId = when (PreferenceHelper.getString("default_tab", "home")) {
"home" -> R.id.homeFragment
"subscriptions" -> R.id.subscriptionsFragment
"library" -> R.id.libraryFragment
@ -119,7 +117,7 @@ class MainActivity : AppCompatActivity() {
navController.navigate(startFragmentId)
val labelVisibilityMode = when (
PreferenceHelper.getString(this, "label_visibility", "always")
PreferenceHelper.getString("label_visibility", "always")
) {
"always" -> NavigationBarView.LABEL_VISIBILITY_LABELED
"selected" -> NavigationBarView.LABEL_VISIBILITY_SELECTED

View File

@ -80,7 +80,7 @@ class PlaylistAdapter(
if (isOwner) {
deletePlaylist.visibility = View.VISIBLE
deletePlaylist.setOnClickListener {
val token = PreferenceHelper.getToken(root.context)
val token = PreferenceHelper.getToken()
removeFromPlaylist(token, position)
}
}

View File

@ -57,7 +57,7 @@ class PlaylistsAdapter(
builder.setTitle(R.string.deletePlaylist)
builder.setMessage(R.string.areYouSure)
builder.setPositiveButton(R.string.yes) { _, _ ->
val token = PreferenceHelper.getToken(root.context)
val token = PreferenceHelper.getToken()
deletePlaylist(playlist.id!!, token, position)
}
builder.setNegativeButton(R.string.cancel) { _, _ ->

View File

@ -143,7 +143,7 @@ class SearchAdapter(
activity.navController.navigate(R.id.channelFragment, bundle)
}
val channelId = item.url?.replace("/channel/", "")!!
val token = PreferenceHelper.getToken(root.context)
val token = PreferenceHelper.getToken()
// only show subscribe button if logged in
if (token != "") isSubscribed(channelId, token, binding)

View File

@ -34,7 +34,7 @@ class SearchHistoryAdapter(
deleteHistory.setOnClickListener {
historyList = historyList - history
PreferenceHelper.saveHistory(context, historyList)
PreferenceHelper.saveHistory(historyList)
notifyDataSetChanged()
}

View File

@ -67,7 +67,7 @@ class SubscriptionChannelAdapter(private val subscriptions: MutableList<Subscrip
fun run() {
CoroutineScope(Dispatchers.IO).launch {
try {
val token = PreferenceHelper.getToken(context)
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.subscribe(
token,
Subscribe(channelId)
@ -86,7 +86,7 @@ class SubscriptionChannelAdapter(private val subscriptions: MutableList<Subscrip
fun run() {
CoroutineScope(Dispatchers.IO).launch {
try {
val token = PreferenceHelper.getToken(context)
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.unsubscribe(
token,
Subscribe(channelId)

View File

@ -32,7 +32,7 @@ class AddtoPlaylistDialog : DialogFragment() {
// Get the layout inflater
binding = DialogAddtoplaylistBinding.inflate(layoutInflater)
token = PreferenceHelper.getToken(requireContext())
token = PreferenceHelper.getToken()
if (token != "") fetchPlaylists()

View File

@ -33,7 +33,7 @@ class CreatePlaylistDialog : DialogFragment() {
dismiss()
}
token = PreferenceHelper.getToken(requireContext())
token = PreferenceHelper.getToken()
binding.createNewPlaylist.setOnClickListener {
// avoid creating the same playlist multiple times by spamming the button

View File

@ -41,7 +41,7 @@ class CustomInstanceDialog : DialogFragment() {
URL(customInstance.apiUrl).toURI()
URL(customInstance.frontendUrl).toURI()
PreferenceHelper.saveCustomInstance(requireContext(), customInstance)
PreferenceHelper.saveCustomInstance(customInstance)
activity?.recreate()
dismiss()
} catch (e: Exception) {

View File

@ -45,7 +45,7 @@ class DeleteAccountDialog : DialogFragment() {
private fun deleteAccount(password: String) {
fun run() {
lifecycleScope.launchWhenCreated {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
try {
RetrofitInstance.authApi.deleteAccount(token, DeleteUserRequest(password))
@ -64,6 +64,6 @@ class DeleteAccountDialog : DialogFragment() {
}
private fun logout() {
PreferenceHelper.setToken(requireContext(), "")
PreferenceHelper.setToken("")
}
}

View File

@ -79,8 +79,8 @@ class LoginDialog : DialogFragment() {
Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show()
} else if (response.token != null) {
Toast.makeText(context, R.string.loggedIn, Toast.LENGTH_SHORT).show()
PreferenceHelper.setToken(requireContext(), response.token!!)
PreferenceHelper.setUsername(requireContext(), login.username!!)
PreferenceHelper.setToken(response.token!!)
PreferenceHelper.setUsername(login.username!!)
val restartDialog = RequireRestartDialog()
restartDialog.show(parentFragmentManager, "RequireRestartDialog")
dialog?.dismiss()
@ -112,8 +112,8 @@ class LoginDialog : DialogFragment() {
Toast.makeText(context, response.error, Toast.LENGTH_SHORT).show()
} else if (response.token != null) {
Toast.makeText(context, R.string.registered, Toast.LENGTH_SHORT).show()
PreferenceHelper.setToken(requireContext(), response.token!!)
PreferenceHelper.setUsername(requireContext(), login.username!!)
PreferenceHelper.setToken(response.token!!)
PreferenceHelper.setUsername(login.username!!)
dialog?.dismiss()
}
}

View File

@ -19,13 +19,13 @@ class LogoutDialog : DialogFragment() {
val builder = MaterialAlertDialogBuilder(it)
binding = DialogLogoutBinding.inflate(layoutInflater)
val user = PreferenceHelper.getUsername(requireContext())
val user = PreferenceHelper.getUsername()
binding.user.text =
binding.user.text.toString() + " (" + user + ")"
binding.logout.setOnClickListener {
Toast.makeText(context, R.string.loggedout, Toast.LENGTH_SHORT).show()
PreferenceHelper.setToken(requireContext(), "")
PreferenceHelper.setToken("")
dialog?.dismiss()
activity?.recreate()
}

View File

@ -51,7 +51,7 @@ class PlaylistOptionsDialog(
when (optionsList[which]) {
// Clone the playlist to the users Piped account
context?.getString(R.string.clonePlaylist) -> {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
if (token != "") {
importPlaylist(token, playlistId)
} else {
@ -69,7 +69,7 @@ class PlaylistOptionsDialog(
shareDialog.show(parentFragmentManager, "ShareDialog")
}
context?.getString(R.string.deletePlaylist) -> {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
deletePlaylist(playlistId, token)
}
}

View File

@ -57,13 +57,12 @@ class ShareDialog(
// get the frontend url if it's a custom instance
private fun getCustomInstanceFrontendUrl(): String {
val instancePref = PreferenceHelper.getString(
requireContext(),
"selectInstance",
PIPED_FRONTEND_URL
)
// get the api urls of the other custom instances
val customInstances = PreferenceHelper.getCustomInstances(requireContext())
val customInstances = PreferenceHelper.getCustomInstances()
// return the custom instance frontend url if available
customInstances.forEach { instance ->

View File

@ -51,7 +51,7 @@ class VideoOptionsDialog(private val videoId: String, context: Context) : Dialog
}
// Add Video to Playlist Dialog
context?.getString(R.string.addToPlaylist) -> {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
if (token != "") {
val newFragment = AddtoPlaylistDialog()
val bundle = Bundle()

View File

@ -56,7 +56,7 @@ class ChannelFragment : Fragment() {
val refreshChannel = {
binding.channelRefresh.isRefreshing = true
fetchChannel()
if (PreferenceHelper.getToken(requireContext()) != "") {
if (PreferenceHelper.getToken() != "") {
isSubscribed()
}
}
@ -85,7 +85,7 @@ class ChannelFragment : Fragment() {
fun run() {
lifecycleScope.launchWhenCreated {
val response = try {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.isSubscribed(
channelId!!,
token
@ -123,7 +123,7 @@ class ChannelFragment : Fragment() {
fun run() {
lifecycleScope.launchWhenCreated {
try {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.subscribe(
token,
Subscribe(channelId)
@ -141,7 +141,7 @@ class ChannelFragment : Fragment() {
fun run() {
lifecycleScope.launchWhenCreated {
try {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.unsubscribe(
token,
Subscribe(channelId)

View File

@ -41,12 +41,11 @@ class HomeFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val grid = PreferenceHelper.getString(
requireContext(),
"grid",
resources.getInteger(R.integer.grid_items).toString()
)!!
val regionPref = PreferenceHelper.getString(requireContext(), "region", "sys")!!
val regionPref = PreferenceHelper.getString("region", "sys")!!
// get the system default country if auto region selected
region = if (regionPref == "sys") {

View File

@ -44,11 +44,11 @@ class LibraryFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.playlistRecView.layoutManager = LinearLayoutManager(view.context)
token = PreferenceHelper.getToken(requireContext())
token = PreferenceHelper.getToken()
// hide watch history button of history disabled
val watchHistoryEnabled =
PreferenceHelper.getBoolean(requireContext(), "watch_history_toggle", true)
PreferenceHelper.getBoolean("watch_history_toggle", true)
if (!watchHistoryEnabled) {
binding.showWatchHistory.visibility = View.GONE
} else {

View File

@ -228,83 +228,70 @@ class PlayerFragment : Fragment() {
}
private fun setUserPrefs() {
token = PreferenceHelper.getToken(requireContext())
token = PreferenceHelper.getToken()
// save whether auto rotation is enabled
autoRotationEnabled = PreferenceHelper.getBoolean(
requireContext(),
"auto_fullscreen",
false
)
// save whether related streams and autoplay are enabled
autoplayEnabled = PreferenceHelper.getBoolean(
requireContext(),
"autoplay",
false
)
relatedStreamsEnabled = PreferenceHelper.getBoolean(
requireContext(),
"related_streams_toggle",
true
)
playbackSpeed = PreferenceHelper.getString(
requireContext(),
"playback_speed",
"1F"
)!!
fullscreenOrientationPref = PreferenceHelper.getString(
requireContext(),
"fullscreen_orientation",
"ratio"
)!!
pausePlayerOnScreenOffEnabled = PreferenceHelper.getBoolean(
requireContext(),
"pause_screen_off",
false
)
watchPositionsEnabled = PreferenceHelper.getBoolean(
requireContext(),
"watch_positions_toggle",
true
)
watchHistoryEnabled = PreferenceHelper.getBoolean(
requireContext(),
"watch_history_toggle",
true
)
useSystemCaptionStyle = PreferenceHelper.getBoolean(
requireContext(),
"system_caption_style",
true
)
seekIncrement = PreferenceHelper.getString(
requireContext(),
"seek_increment",
"5"
)?.toLong()!! * 1000
videoFormatPreference = PreferenceHelper.getString(
requireContext(),
"player_video_format",
"WEBM"
)!!
defRes = PreferenceHelper.getString(
requireContext(),
"default_res",
""
)!!
bufferingGoal = PreferenceHelper.getString(
requireContext(),
"buffering_goal",
"50"
)?.toInt()!! * 1000
@ -312,25 +299,25 @@ class PlayerFragment : Fragment() {
private fun setSponsorBlockPrefs() {
sponsorBlockPrefs.sponsorBlockEnabled =
PreferenceHelper.getBoolean(requireContext(), "sb_enabled_key", true)
PreferenceHelper.getBoolean("sb_enabled_key", true)
sponsorBlockPrefs.sponsorNotificationsEnabled =
PreferenceHelper.getBoolean(requireContext(), "sb_notifications_key", true)
PreferenceHelper.getBoolean("sb_notifications_key", true)
sponsorBlockPrefs.introEnabled =
PreferenceHelper.getBoolean(requireContext(), "intro_category_key", false)
PreferenceHelper.getBoolean("intro_category_key", false)
sponsorBlockPrefs.selfPromoEnabled =
PreferenceHelper.getBoolean(requireContext(), "selfpromo_category_key", false)
PreferenceHelper.getBoolean("selfpromo_category_key", false)
sponsorBlockPrefs.interactionEnabled =
PreferenceHelper.getBoolean(requireContext(), "interaction_category_key", false)
PreferenceHelper.getBoolean("interaction_category_key", false)
sponsorBlockPrefs.sponsorsEnabled =
PreferenceHelper.getBoolean(requireContext(), "sponsors_category_key", true)
PreferenceHelper.getBoolean("sponsors_category_key", true)
sponsorBlockPrefs.outroEnabled =
PreferenceHelper.getBoolean(requireContext(), "outro_category_key", false)
PreferenceHelper.getBoolean("outro_category_key", false)
sponsorBlockPrefs.fillerEnabled =
PreferenceHelper.getBoolean(requireContext(), "filler_category_key", false)
PreferenceHelper.getBoolean("filler_category_key", false)
sponsorBlockPrefs.musicOffTopicEnabled =
PreferenceHelper.getBoolean(requireContext(), "music_offtopic_category_key", false)
PreferenceHelper.getBoolean("music_offtopic_category_key", false)
sponsorBlockPrefs.previewEnabled =
PreferenceHelper.getBoolean(requireContext(), "preview_category_key", false)
PreferenceHelper.getBoolean("preview_category_key", false)
}
private fun initializeTransitionLayout() {
@ -458,13 +445,17 @@ class PlayerFragment : Fragment() {
}
// switching between original aspect ratio (black bars) and zoomed to fill device screen
val aspectRatioModes = arrayOf(
AspectRatioFrameLayout.RESIZE_MODE_FIT,
AspectRatioFrameLayout.RESIZE_MODE_ZOOM,
AspectRatioFrameLayout.RESIZE_MODE_FILL
)
playerBinding.aspectRatioButton.setOnClickListener {
val isZoomed = exoPlayerView.resizeMode != AspectRatioFrameLayout.RESIZE_MODE_FIT
if (isZoomed) {
exoPlayerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
} else {
exoPlayerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
}
val index = aspectRatioModes.indexOf(exoPlayerView.resizeMode)
val newAspectRatioMode =
if (index + 1 < aspectRatioModes.size) aspectRatioModes[index + 1]
else aspectRatioModes[0]
exoPlayerView.resizeMode = newAspectRatioMode
}
// lock and unlock the player
@ -668,13 +659,12 @@ class PlayerFragment : Fragment() {
private fun saveWatchPosition() {
if (watchPositionsEnabled && exoPlayer.currentPosition != exoPlayer.duration) {
PreferenceHelper.saveWatchPosition(
requireContext(),
videoId!!,
exoPlayer.currentPosition
)
} else if (watchPositionsEnabled) {
// delete watch position if video has ended
PreferenceHelper.removeWatchPosition(requireContext(), videoId!!)
PreferenceHelper.removeWatchPosition(videoId!!)
}
}
@ -739,7 +729,7 @@ class PlayerFragment : Fragment() {
// prepare for autoplay
initAutoPlay()
if (watchHistoryEnabled) {
PreferenceHelper.addToWatchHistory(requireContext(), videoId!!, response)
PreferenceHelper.addToWatchHistory(videoId!!, response)
}
}
}
@ -749,7 +739,7 @@ class PlayerFragment : Fragment() {
private fun seekToWatchPosition() {
// seek to saved watch position if available
val watchPositions = PreferenceHelper.getWatchPositions(requireContext())
val watchPositions = PreferenceHelper.getWatchPositions()
var position: Long? = null
watchPositions.forEach {
if (it.videoId == videoId) position = it.position

View File

@ -74,7 +74,7 @@ class PlaylistFragment : Fragment() {
binding.playlistTotVideos.text =
getString(R.string.videoCount, response.videos.toString())
val user = PreferenceHelper.getUsername(requireContext())
val user = PreferenceHelper.getUsername()
// check whether the user owns the playlist
val isOwner = response.uploaderUrl == null &&
response.uploader.equals(user, true)

View File

@ -256,7 +256,7 @@ class SearchFragment : Fragment() {
private fun showHistory() {
binding.searchRecycler.visibility = GONE
val historyList = PreferenceHelper.getHistory(requireContext())
val historyList = PreferenceHelper.getHistory()
if (historyList.isNotEmpty()) {
binding.historyRecycler.adapter =
SearchHistoryAdapter(
@ -271,9 +271,9 @@ class SearchFragment : Fragment() {
private fun addToHistory(query: String) {
val searchHistoryEnabled =
PreferenceHelper.getBoolean(requireContext(), "search_history_toggle", true)
PreferenceHelper.getBoolean("search_history_toggle", true)
if (searchHistoryEnabled) {
var historyList = PreferenceHelper.getHistory(requireContext())
var historyList = PreferenceHelper.getHistory()
if ((historyList.isNotEmpty() && historyList.contains(query)) || query == "") {
return
@ -285,7 +285,7 @@ class SearchFragment : Fragment() {
historyList = historyList.takeLast(10)
}
PreferenceHelper.saveHistory(requireContext(), historyList)
PreferenceHelper.saveHistory(historyList)
}
}
}

View File

@ -47,7 +47,7 @@ class SubscriptionsFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
token = PreferenceHelper.getToken(requireContext())
token = PreferenceHelper.getToken()
if (token != "") {
binding.loginOrRegister.visibility = View.GONE
@ -56,7 +56,6 @@ class SubscriptionsFragment : Fragment() {
binding.subProgress.visibility = View.VISIBLE
val grid = PreferenceHelper.getString(
requireContext(),
"grid",
resources.getInteger(R.integer.grid_items).toString()
)!!

View File

@ -26,12 +26,12 @@ class WatchHistoryFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val watchHistory = PreferenceHelper.getWatchHistory(requireContext())
val watchHistory = PreferenceHelper.getWatchHistory()
val watchHistoryAdapter = WatchHistoryAdapter(watchHistory, childFragmentManager)
binding.watchHistoryRecView.adapter = watchHistoryAdapter
binding.clearHistory.setOnClickListener {
PreferenceHelper.removePreference(requireContext(), "watch_history")
PreferenceHelper.removePreference("watch_history")
watchHistoryAdapter.clear()
}

View File

@ -36,10 +36,10 @@ class AdvancedSettings : PreferenceFragmentCompat() {
MaterialAlertDialogBuilder(requireContext())
.setPositiveButton(R.string.reset) { _, _ ->
// clear default preferences
PreferenceHelper.clearPreferences(requireContext())
PreferenceHelper.clearPreferences()
// clear login token
PreferenceHelper.setToken(requireContext(), "")
PreferenceHelper.setToken("")
val restartDialog = RequireRestartDialog()
restartDialog.show(childFragmentManager, "RequireRestartDialog")

View File

@ -17,21 +17,21 @@ class HistorySettings : PreferenceFragmentCompat() {
// clear search history
val clearHistory = findPreference<Preference>("clear_history")
clearHistory?.setOnPreferenceClickListener {
PreferenceHelper.removePreference(requireContext(), "search_history")
PreferenceHelper.removePreference("search_history")
true
}
// clear watch history and positions
val clearWatchHistory = findPreference<Preference>("clear_watch_history")
clearWatchHistory?.setOnPreferenceClickListener {
PreferenceHelper.removePreference(requireContext(), "watch_history")
PreferenceHelper.removePreference("watch_history")
true
}
// clear watch positions
val clearWatchPositions = findPreference<Preference>("clear_watch_positions")
clearWatchPositions?.setOnPreferenceClickListener {
PreferenceHelper.removePreference(requireContext(), "watch_positions")
PreferenceHelper.removePreference("watch_positions")
true
}
}

View File

@ -122,7 +122,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val restartDialog = RequireRestartDialog()
restartDialog.show(childFragmentManager, "RequireRestartDialog")
RetrofitInstance.url = newValue.toString()
if (!PreferenceHelper.getBoolean(requireContext(), "auth_instance_toggle", false)) {
if (!PreferenceHelper.getBoolean("auth_instance_toggle", false)) {
RetrofitInstance.authUrl = newValue.toString()
logout()
}
@ -133,7 +133,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val authInstance = findPreference<ListPreference>("selectAuthInstance")
initCustomInstances(authInstance!!)
// hide auth instance if option deselected
if (!PreferenceHelper.getBoolean(requireContext(), "auth_instance_toggle", false)) {
if (!PreferenceHelper.getBoolean("auth_instance_toggle", false)) {
authInstance.isVisible = false
}
authInstance.setOnPreferenceChangeListener { _, newValue ->
@ -167,14 +167,14 @@ class InstanceSettings : PreferenceFragmentCompat() {
val clearCustomInstances = findPreference<Preference>("clearCustomInstances")
clearCustomInstances?.setOnPreferenceClickListener {
PreferenceHelper.removePreference(requireContext(), "customInstances")
PreferenceHelper.removePreference("customInstances")
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
true
}
val login = findPreference<Preference>("login_register")
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
if (token != "") login?.setTitle(R.string.logout)
login?.setOnPreferenceClickListener {
if (token == "") {
@ -190,7 +190,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
val deleteAccount = findPreference<Preference>("delete_account")
deleteAccount?.setOnPreferenceClickListener {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
if (token != "") {
val newFragment = DeleteAccountDialog()
newFragment.show(childFragmentManager, "DeleteAccountDialog")
@ -208,7 +208,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
}
private fun initCustomInstances(instancePref: ListPreference) {
val customInstances = PreferenceHelper.getCustomInstances(requireContext())
val customInstances = PreferenceHelper.getCustomInstances()
var instanceNames = resources.getStringArray(R.array.instances)
var instanceValues = resources.getStringArray(R.array.instancesValue)
@ -232,7 +232,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
}
private fun logout() {
PreferenceHelper.setToken(requireContext(), "")
PreferenceHelper.setToken("")
Toast.makeText(context, getString(R.string.loggedout), Toast.LENGTH_SHORT).show()
}
@ -286,7 +286,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
}
private fun importSubscriptions() {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
// check StorageAccess
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Log.d("myz", "" + Build.VERSION.SDK_INT)
@ -339,7 +339,7 @@ class InstanceSettings : PreferenceFragmentCompat() {
fun run() {
lifecycleScope.launchWhenCreated {
val response = try {
val token = PreferenceHelper.getToken(requireContext())
val token = PreferenceHelper.getToken()
RetrofitInstance.authApi.importSubscriptions(
false,
token,

View File

@ -21,7 +21,6 @@ class PlayerSettings : PreferenceFragmentCompat() {
// only show the player orientation option if auto fullscreen is disabled
playerOrientation?.isEnabled != PreferenceHelper.getBoolean(
requireContext(),
"auto_fullscreen",
false
)

View File

@ -14,93 +14,94 @@ import java.lang.reflect.Type
object PreferenceHelper {
private val TAG = "PreferenceHelper"
fun setString(context: Context, key: String?, value: String?) {
val editor = getDefaultSharedPreferencesEditor(context)
private lateinit var prefContext: Context
private lateinit var settings: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
/**
* set the context that is being used to access the shared preferences
*/
fun setContext(context: Context) {
prefContext = context
settings = getDefaultSharedPreferences(prefContext)
editor = getDefaultSharedPreferencesEditor(prefContext)
}
fun setString(key: String?, value: String?) {
editor.putString(key, value)
editor.apply()
}
fun setInt(context: Context, key: String?, value: Int) {
val editor = getDefaultSharedPreferencesEditor(context)
fun setInt(key: String?, value: Int) {
editor.putInt(key, value)
editor.apply()
}
fun setLong(context: Context, key: String?, value: Long) {
val editor = getDefaultSharedPreferencesEditor(context)
fun setLong(key: String?, value: Long) {
editor.putLong(key, value)
editor.apply()
}
fun setBoolean(context: Context, key: String?, value: Boolean) {
val editor = getDefaultSharedPreferencesEditor(context)
fun setBoolean(key: String?, value: Boolean) {
editor.putBoolean(key, value)
editor.apply()
}
fun getString(context: Context, key: String?, defValue: String?): String? {
val settings: SharedPreferences = getDefaultSharedPreferences(context)
fun getString(key: String?, defValue: String?): String? {
return settings.getString(key, defValue)
}
fun getInt(context: Context, key: String?, defValue: Int): Int {
val settings: SharedPreferences = getDefaultSharedPreferences(context)
fun getInt(key: String?, defValue: Int): Int {
return settings.getInt(key, defValue)
}
fun getLong(context: Context, key: String?, defValue: Long): Long {
val settings: SharedPreferences = getDefaultSharedPreferences(context)
fun getLong(key: String?, defValue: Long): Long {
return settings.getLong(key, defValue)
}
fun getBoolean(context: Context, key: String?, defValue: Boolean): Boolean {
val settings: SharedPreferences = getDefaultSharedPreferences(context)
fun getBoolean(key: String?, defValue: Boolean): Boolean {
return settings.getBoolean(key, defValue)
}
fun clearPreferences(context: Context) {
val editor = getDefaultSharedPreferencesEditor(context)
fun clearPreferences() {
editor.clear().apply()
}
fun removePreference(context: Context, value: String?) {
val editor = getDefaultSharedPreferencesEditor(context)
fun removePreference(value: String?) {
editor.remove(value).apply()
}
fun getToken(context: Context): String {
val sharedPref = context.getSharedPreferences("token", Context.MODE_PRIVATE)
fun getToken(): String {
val sharedPref = prefContext.getSharedPreferences("token", Context.MODE_PRIVATE)
return sharedPref?.getString("token", "")!!
}
fun setToken(context: Context, newValue: String) {
val editor = context.getSharedPreferences("token", Context.MODE_PRIVATE).edit()
fun setToken(newValue: String) {
val editor = prefContext.getSharedPreferences("token", Context.MODE_PRIVATE).edit()
editor.putString("token", newValue).apply()
}
fun getUsername(context: Context): String {
val sharedPref = context.getSharedPreferences("username", Context.MODE_PRIVATE)
fun getUsername(): String {
val sharedPref = prefContext.getSharedPreferences("username", Context.MODE_PRIVATE)
return sharedPref.getString("username", "")!!
}
fun setUsername(context: Context, newValue: String) {
val editor = context.getSharedPreferences("username", Context.MODE_PRIVATE).edit()
fun setUsername(newValue: String) {
val editor = prefContext.getSharedPreferences("username", Context.MODE_PRIVATE).edit()
editor.putString("username", newValue).apply()
}
fun saveCustomInstance(context: Context, customInstance: CustomInstance) {
val editor = getDefaultSharedPreferencesEditor(context)
fun saveCustomInstance(customInstance: CustomInstance) {
val gson = Gson()
val customInstancesList = getCustomInstances(context)
val customInstancesList = getCustomInstances()
customInstancesList += customInstance
val json = gson.toJson(customInstancesList)
editor.putString("customInstances", json).apply()
}
fun getCustomInstances(context: Context): ArrayList<CustomInstance> {
val settings = getDefaultSharedPreferences(context)
fun getCustomInstances(): ArrayList<CustomInstance> {
val gson = Gson()
val json: String = settings.getString("customInstances", "")!!
val type: Type = object : TypeToken<List<CustomInstance?>?>() {}.type
@ -111,9 +112,8 @@ object PreferenceHelper {
}
}
fun getHistory(context: Context): List<String> {
fun getHistory(): List<String> {
return try {
val settings = getDefaultSharedPreferences(context)
val set: Set<String> = settings.getStringSet("search_history", HashSet())!!
set.toList()
} catch (e: Exception) {
@ -121,14 +121,12 @@ object PreferenceHelper {
}
}
fun saveHistory(context: Context, historyList: List<String>) {
val editor = getDefaultSharedPreferencesEditor(context)
fun saveHistory(historyList: List<String>) {
val set: Set<String> = HashSet(historyList)
editor.putStringSet("search_history", set).apply()
}
fun addToWatchHistory(context: Context, videoId: String, streams: Streams) {
val editor = getDefaultSharedPreferencesEditor(context)
fun addToWatchHistory(videoId: String, streams: Streams) {
val gson = Gson()
val watchHistoryItem = WatchHistoryItem(
@ -142,7 +140,7 @@ object PreferenceHelper {
streams.duration
)
val watchHistory = getWatchHistory(context)
val watchHistory = getWatchHistory()
// delete entries that have the same videoId
var indexToRemove: Int? = null
@ -157,8 +155,7 @@ object PreferenceHelper {
editor.putString("watch_history", json).apply()
}
fun getWatchHistory(context: Context): ArrayList<WatchHistoryItem> {
val settings = getDefaultSharedPreferences(context)
fun getWatchHistory(): ArrayList<WatchHistoryItem> {
val gson = Gson()
val json: String = settings.getString("watch_history", "")!!
val type: Type = object : TypeToken<List<WatchHistoryItem?>?>() {}.type
@ -169,10 +166,8 @@ object PreferenceHelper {
}
}
fun saveWatchPosition(context: Context, videoId: String, position: Long) {
val editor = getDefaultSharedPreferencesEditor(context)
val watchPositions = getWatchPositions(context)
fun saveWatchPosition(videoId: String, position: Long) {
val watchPositions = getWatchPositions()
val watchPositionItem = WatchPosition(videoId, position)
var indexToRemove: Int? = null
@ -189,10 +184,8 @@ object PreferenceHelper {
editor.putString("watch_positions", json).commit()
}
fun removeWatchPosition(context: Context, videoId: String) {
val editor = getDefaultSharedPreferencesEditor(context)
val watchPositions = getWatchPositions(context)
fun removeWatchPosition(videoId: String) {
val watchPositions = getWatchPositions()
var indexToRemove: Int? = null
watchPositions.forEachIndexed { index, item ->
@ -206,11 +199,12 @@ object PreferenceHelper {
editor.putString("watch_positions", json).commit()
}
fun getWatchPositions(context: Context): ArrayList<WatchPosition> {
val settings = getDefaultSharedPreferences(context)
fun getWatchPositions(): ArrayList<WatchPosition> {
val gson = Gson()
val json: String = settings.getString("watch_positions", "")!!
val type: Type = object : TypeToken<List<WatchPosition?>?>() {}.type
return try {
gson.fromJson(json, type)
} catch (e: Exception) {

View File

@ -52,7 +52,7 @@ class DownloadService : Service() {
videoUrl = intent.getStringExtra("videoUrl")!!
audioUrl = intent.getStringExtra("audioUrl")!!
duration = intent.getIntExtra("duration", 1)
extension = PreferenceHelper.getString(this, "video_format", ".mp4")!!
extension = PreferenceHelper.getString("video_format", ".mp4")!!
downloadType = if (audioUrl != "" && videoUrl != "") DownloadType.MUX
else if (audioUrl != "") DownloadType.AUDIO
else if (videoUrl != "") DownloadType.VIDEO
@ -86,8 +86,8 @@ class DownloadService : Service() {
Log.e(TAG, "Directory already have")
}
val downloadLocationPref = PreferenceHelper.getString(this, "download_location", "")
val folderName = PreferenceHelper.getString(this, "download_folder", "LibreTube")
val downloadLocationPref = PreferenceHelper.getString("download_location", "")
val folderName = PreferenceHelper.getString("download_folder", "LibreTube")
val location = when (downloadLocationPref) {
"downloads" -> Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS)

View File

@ -71,7 +71,7 @@ class BackgroundMode {
*/
player!!.addListener(object : Player.Listener {
override fun onPlaybackStateChanged(@Player.State state: Int) {
val autoplay = PreferenceHelper.getBoolean(c, "autoplay", false)
val autoplay = PreferenceHelper.getBoolean("autoplay", false)
if (state == Player.STATE_ENDED) {
if (autoplay) playNextVideo(c)
}

View File

@ -9,7 +9,7 @@ import java.util.*
object LocaleHelper {
fun updateLanguage(context: Context) {
val languageName = PreferenceHelper.getString(context, "language", "sys")
val languageName = PreferenceHelper.getString("language", "sys")
if (languageName == "sys") updateLocaleConf(context, Locale.getDefault())
else if ("$languageName".length < 3) {
val locale = Locale(languageName.toString())

View File

@ -17,8 +17,8 @@ import com.google.android.material.color.DynamicColors
object ThemeHelper {
fun updateTheme(activity: AppCompatActivity) {
val themeMode = PreferenceHelper.getString(activity, "theme_toggle", "A")!!
val pureThemeEnabled = PreferenceHelper.getBoolean(activity, "pure_theme", false)
val themeMode = PreferenceHelper.getString("theme_toggle", "A")!!
val pureThemeEnabled = PreferenceHelper.getBoolean("pure_theme", false)
updateAccentColor(activity, pureThemeEnabled)
updateThemeMode(themeMode)
@ -30,7 +30,6 @@ object ThemeHelper {
) {
val theme = when (
PreferenceHelper.getString(
activity,
"accent_color",
"purple"
)
@ -72,15 +71,25 @@ object ThemeHelper {
val activityAliases = context.resources.getStringArray(R.array.iconsValue)
// Disable Old Icon(s)
for (activityAlias in activityAliases) {
val activityClass = "com.github.libretube." +
if (activityAlias == activityAliases[0]) "activities.MainActivity" // default icon/activity
else activityAlias
// remove old icons
context.packageManager.setComponentEnabledSetting(
ComponentName(context.packageName, "com.github.libretube.$activityAlias"),
ComponentName(context.packageName, activityClass),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
)
}
// set the class name for the activity alias
val newLogoActivityClass = "com.github.libretube." +
if (newLogoActivityAlias == activityAliases[0]) "activities.MainActivity" // default icon/activity
else newLogoActivityAlias
// Enable New Icon
context.packageManager.setComponentEnabledSetting(
ComponentName(context.packageName, "com.github.libretube.$newLogoActivityAlias"),
ComponentName(context.packageName, newLogoActivityClass),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP
)

View File

@ -608,7 +608,7 @@
<item>@string/birdIcon</item>
</string-array>
<string-array name="iconsValue">
<item>activities.MainActivity</item>
<item>MainActivity</item>
<item>IconLegacy</item>
<item>IconGradient</item>
<item>IconFire</item>