Commit 99d64ab9 authored by Geoffrey Métais's avatar Geoffrey Métais

Code cleaning

parent adcef71c
package org.videolan.tools
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.IO
open class IOScopedObject : CoroutineScope {
override val coroutineContext = Dispatchers.IO
}
\ No newline at end of file
......@@ -5,7 +5,7 @@
android:installLocation="auto">
<uses-sdk
tools:overrideLibrary="android.support.v17.leanback, android.support.v17.preference, android.support.media.tv" />
tools:overrideLibrary="android.support.media.tv" />
<uses-permission android:name="android.permission.READ_LOGS"
android:maxSdkVersion="18" /> <!-- android:maxSdkVersion="15" -->
......
......@@ -24,7 +24,7 @@ class FileProvider : ContentProvider() {
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0
override fun getType(uri: Uri) = "image/${uri.path.substringAfterLast('.')}"
override fun getType(uri: Uri) = "image/${uri.path?.substringAfterLast('.')}"
override fun openFile(uri: Uri, mode: String?): ParcelFileDescriptor {
val file = File(uri.path)
......
......@@ -7,7 +7,7 @@ import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.view.KeyEvent
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.*
import org.videolan.medialibrary.Tools
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.medialibrary.media.MediaWrapper
......@@ -71,7 +71,7 @@ internal class MediaSessionCallback(private val playbackService: PlaybackService
return
}
playbackService.mediaSession.setPlaybackState(PlaybackStateCompat.Builder().setState(PlaybackStateCompat.STATE_CONNECTING, playbackService.time, 1.0f).build())
launch {
GlobalScope.launch(Dispatchers.IO) {
val vsp = VoiceSearchParams(query, extras)
var items: Array<out MediaLibraryItem>? = null
var tracks: Array<MediaWrapper>? = null
......
......@@ -43,12 +43,10 @@ import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.actor
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.withContext
import org.videolan.libvlc.IVLCVout
import org.videolan.libvlc.Media
import org.videolan.libvlc.MediaPlayer
......@@ -72,7 +70,8 @@ import java.util.*
private const val TAG = "VLC/PlaybackService"
class PlaybackService : MediaBrowserServiceCompat() {
class PlaybackService : MediaBrowserServiceCompat(), CoroutineScope {
override val coroutineContext = Dispatchers.Main.immediate
lateinit var playlistManager: PlaylistManager
private set
......@@ -167,7 +166,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
publishState()
audioFocusHelper.changeAudioFocus(true)
if (!wakeLock.isHeld) wakeLock.acquire()
if (!keyguardManager.inKeyguardRestrictedInputMode()
if (!keyguardManager.isKeyguardLocked
&& !playlistManager.videoBackground
&& !hasRenderer()
&& playlistManager.switchToVideo()) {
......@@ -639,7 +638,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
val sessionToken = mediaSession.sessionToken
val ctx = this
val metaData = mediaSession.controller.metadata
launch {
launch(Dispatchers.Default) {
if (isPlayingPopup) return@launch
try {
val title = if (metaData == null) mw.title else metaData.getString(MediaMetadataCompat.METADATA_KEY_TITLE)
......@@ -1002,7 +1001,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
* @param flags LibVLC.MEDIA_* flags
*/
@JvmOverloads
fun playIndex(index: Int, flags: Int = 0) = launch(UI.immediate) { playlistManager.playIndex(index, flags) }
fun playIndex(index: Int, flags: Int = 0) = launch { playlistManager.playIndex(index, flags) }
@MainThread
fun flush() {
......@@ -1280,7 +1279,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
}
private fun sendResults(result: MediaBrowserServiceCompat.Result<List<MediaBrowserCompat.MediaItem>>, parentId: String) {
launch {
launch(Dispatchers.IO) {
try {
result.sendResult(BrowserProvider.browse(applicationContext, parentId))
} catch (ignored: RuntimeException) {} //bitmap parcelization can fail
......@@ -1289,7 +1288,7 @@ class PlaybackService : MediaBrowserServiceCompat() {
private val cbActor by lazy {
actor<CbAction>(UI, capacity = Channel.UNLIMITED) {
actor<CbAction>(capacity = Channel.UNLIMITED) {
for (update in channel) when (update) {
CbUpdate -> for (callback in callbacks) callback.update()
is CbMediaEvent -> for (callback in callbacks) callback.onMediaEvent(update.event)
......
......@@ -10,8 +10,9 @@ import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.Surface
import kotlinx.coroutines.experimental.CoroutineStart
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.launch
import org.videolan.libvlc.Media
import org.videolan.libvlc.MediaPlayer
......@@ -25,7 +26,8 @@ import java.io.IOException
private const val TAG = "PreviewInputService"
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class PreviewVideoInputService : TvInputService() {
class PreviewVideoInputService : TvInputService(), CoroutineScope {
override val coroutineContext = Dispatchers.Main.immediate
override fun onCreateSession(inputId: String): TvInputService.Session? {
return PreviewSession(this)
......@@ -42,8 +44,8 @@ class PreviewVideoInputService : TvInputService() {
override fun onTune(uri: Uri): Boolean {
notifyVideoUnavailable(VIDEO_UNAVAILABLE_REASON_TUNING)
val id = uri.lastPathSegment.toLong()
launch(UI, CoroutineStart.UNDISPATCHED) {
val id = uri.lastPathSegment?.toLong() ?: return false
launch {
val mw = this@PreviewVideoInputService.getFromMl { getMedia(id) }
if (mw == null) {
Log.w(TAG, "Could not find video $id")
......
......@@ -29,8 +29,10 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.support.v4.app.NotificationManagerCompat
import android.support.v4.content.ContextCompat
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.Main
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.vlc.gui.helpers.BitmapUtil
import org.videolan.vlc.gui.video.VideoPlayerActivity
......@@ -40,7 +42,8 @@ private const val TAG = "VLC/RecommendationsService"
private const val MAX_RECOMMENDATIONS = 3
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class RecommendationsService : IntentService("RecommendationService") {
class RecommendationsService : IntentService("RecommendationService"), CoroutineScope {
override val coroutineContext = Dispatchers.Main.immediate
private lateinit var mNotificationManager: NotificationManager
......@@ -83,12 +86,12 @@ class RecommendationsService : IntentService("RecommendationService") {
return PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun doRecommendations() = launch (start = CoroutineStart.UNDISPATCHED) {
private fun doRecommendations() = launch {
mNotificationManager.cancelAll()
val videoList = withContext(Dispatchers.IO) { VLCApplication.getMLInstance().recentVideos }
if (Util.isArrayEmpty(videoList)) return@launch
for ((id, mediaWrapper) in videoList.withIndex()) {
buildRecommendation(mediaWrapper, id, Notification.PRIORITY_DEFAULT)
buildRecommendation(mediaWrapper, id, NotificationManagerCompat.IMPORTANCE_DEFAULT)
if (id == MAX_RECOMMENDATIONS) break
}
}
......
......@@ -22,6 +22,7 @@ package org.videolan.vlc
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.android.UI
import org.videolan.libvlc.RendererDiscoverer
import org.videolan.libvlc.RendererItem
......@@ -40,7 +41,7 @@ object RendererDelegate : RendererDiscoverer.EventListener {
val selectedRenderer: LiveData<RendererItem> = MutableLiveData()
init {
ExternalMonitor.connected.observeForever { launch(UI.immediate) { if (it == true) start() else stop() } }
ExternalMonitor.connected.observeForever { GlobalScope.launch(Dispatchers.Main.immediate) { if (it == true) start() else stop() } }
}
suspend fun start() {
......
......@@ -187,12 +187,11 @@ val migration_27_28 = object:Migration(27, 28) {
override fun migrate(database: SupportSQLiteDatabase) {
val preferences = Settings.getInstance(VLCApplication.getAppContext())
val customPaths = preferences.getString("custom_paths", "")
var oldPaths = listOf<String>()
if (customPaths.isNotEmpty())
oldPaths = customPaths.split(":")
var oldPaths : List<String>? = null
if (customPaths.isNotEmpty()) oldPaths = customPaths?.split(":")
database.execSQL("CREATE TABLE IF NOT EXISTS $CUSTOM_DIRECTORY_TABLE_NAME(path TEXT PRIMARY KEY NOT NULL);")
oldPaths.forEach {
oldPaths?.forEach {
database.execSQL("INSERT INTO $CUSTOM_DIRECTORY_TABLE_NAME(path) VALUES (\"$it\")")
}
}
......
......@@ -117,7 +117,7 @@ class AudioPlayer : Fragment(), PlaylistAdapter.IPlayer, TextWatcher, PlaybackSe
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = AudioPlayerBinding.inflate(inflater)!!
binding = AudioPlayerBinding.inflate(inflater)
return binding.root
}
......
......@@ -48,6 +48,7 @@ import org.videolan.medialibrary.interfaces.EntryPointsEventsCb
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.medialibrary.media.Storage
import org.videolan.tools.coroutineScope
import org.videolan.vlc.R
import org.videolan.vlc.VLCApplication
import org.videolan.vlc.databinding.BrowserItemBinding
......@@ -146,7 +147,7 @@ class StorageBrowserFragment : FileBrowserFragment(), EntryPointsEventsCb {
override fun onCtxClick(v: View, position: Int, item: MediaLibraryItem) {
if (isRootDirectory) {
val storage = adapter.getItem(position) as Storage
launch(UI.immediate) {
coroutineScope.launch {
val isCustom = viewModel.customDirectoryExists(storage.uri.path)
if (isCustom) showContext(requireActivity(), this@StorageBrowserFragment, position, item.title, CTX_CUSTOM_REMOVE)
}
......@@ -215,7 +216,7 @@ class StorageBrowserFragment : FileBrowserFragment(), EntryPointsEventsCb {
builder.setTitle(R.string.add_custom_path)
builder.setMessage(R.string.add_custom_path_description)
builder.setView(input)
builder.setNegativeButton(R.string.cancel) { dialogInterface, which -> }
builder.setNegativeButton(R.string.cancel) { _, _ -> }
builder.setPositiveButton(R.string.ok, DialogInterface.OnClickListener { dialog, which ->
val path = input.text.toString().trim { it <= ' ' }
val f = File(path)
......@@ -224,7 +225,7 @@ class StorageBrowserFragment : FileBrowserFragment(), EntryPointsEventsCb {
return@OnClickListener
}
launch(UI.immediate + CoroutineExceptionHandler{ _, _ ->}) {
coroutineScope.launch(CoroutineExceptionHandler{ _, _ ->}) {
viewModel.addCustomDirectory(f.canonicalPath).join()
viewModel.browserRoot()
}
......
......@@ -29,8 +29,8 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import org.videolan.tools.coroutineScope
import org.videolan.vlc.R
import org.videolan.vlc.databinding.ContextItemBinding
import org.videolan.vlc.util.*
......@@ -75,7 +75,7 @@ class ContextSheet : BottomSheetDialogFragment() {
list.adapter = ContextAdapter()
val flags = arguments?.getInt(CTX_FLAGS_KEY) ?: 0
options = populateOptions(flags)
if (!AndroidDevices.isPhone) launch(UI) { dialog.window.setLayout(resources.getDimensionPixelSize(R.dimen.default_context_width), ViewGroup.LayoutParams.MATCH_PARENT) }
if (!AndroidDevices.isPhone) coroutineScope.launch { dialog.window.setLayout(resources.getDimensionPixelSize(R.dimen.default_context_width), ViewGroup.LayoutParams.MATCH_PARENT) }
}
private fun populateOptions(flags: Int) = mutableListOf<CtxOption>().apply {
......
......@@ -40,11 +40,9 @@ import org.videolan.vlc.gui.PlaybackServiceActivity
import org.videolan.vlc.gui.helpers.SelectorViewHolder
import org.videolan.vlc.gui.helpers.UiTools
class RenderersDialog : DialogFragment(), PlaybackService.Client.Callback {
const private val TAG = "VLC/RenderersDialog"
companion object {
private val TAG = "VLC/RenderersDialog"
}
class RenderersDialog : DialogFragment(), PlaybackService.Client.Callback {
private var renderers = RendererDelegate.renderers.value
private lateinit var mBinding: DialogRenderersBinding
private val mAdapter = RendererAdapter()
......
......@@ -27,6 +27,9 @@ import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.SendChannel
......@@ -63,7 +66,7 @@ open class BaseHeadlessFragment : Fragment() {
companion object {
internal fun waitForIt(channel: Channel<Unit>, cb: Runnable) {
launch(UI.immediate) {
GlobalScope.launch(Dispatchers.Main.immediate) {
channel.receive()
channel.close()
cb.run()
......
......@@ -37,9 +37,9 @@ import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.actor
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.tools.coroutineScope
import org.videolan.vlc.R
import org.videolan.vlc.databinding.MrlPanelBinding
import org.videolan.vlc.gui.DialogActivity
......@@ -60,7 +60,7 @@ class MRLPanelFragment : DialogFragment(), View.OnKeyListener, TextView.OnEditor
private lateinit var editText: TextInputLayout
private lateinit var viewModel: StreamsModel
private val listEventActor = actor<MrlAction>(UI) {
private val listEventActor = coroutineScope.actor<MrlAction> {
for (event in channel) when(event) {
is Playmedia -> playMedia(event.media)
is ShowContext -> showContext(event.position)
......
......@@ -2,7 +2,6 @@ package org.videolan.vlc.gui.tv
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.widget.TextView
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.UiTools
......
......@@ -34,13 +34,13 @@ import android.support.v17.leanback.app.BrowseSupportFragment
import android.support.v17.leanback.widget.*
import android.support.v4.content.ContextCompat
import android.view.View
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.Medialibrary
import org.videolan.medialibrary.media.DummyItem
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.tools.coroutineScope
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.ExternalMonitor
import org.videolan.vlc.R
......@@ -87,7 +87,7 @@ class MainTvFragment : BrowseSupportFragment(), OnItemViewSelectedListener, OnIt
private lateinit var browserFavRepository: BrowserFavRepository
var updatedFavoritList: List<MediaWrapper> = listOf()
private var updatedFavoritList: List<MediaWrapper> = listOf()
private lateinit var favorites: LiveData<List<MediaWrapper>>
override fun onCreate(savedInstanceState: Bundle?) {
......@@ -206,7 +206,7 @@ class MainTvFragment : BrowseSupportFragment(), OnItemViewSelectedListener, OnIt
return true
}
fun updateBrowsers() = launch(UI.immediate) {
fun updateBrowsers() = coroutineScope.launch {
val list = mutableListOf<MediaLibraryItem>()
val directories = DirectoryRepository.getInstance(requireContext()).getMediaDirectoriesList(requireContext().applicationContext).toMutableList()
if (!AndroidDevices.showInternalStorage && !directories.isEmpty()) directories.removeAt(0)
......
......@@ -29,10 +29,10 @@ import android.os.Bundle
import android.support.v17.leanback.app.SearchSupportFragment
import android.support.v17.leanback.widget.*
import android.text.TextUtils
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import org.videolan.medialibrary.Tools
import org.videolan.medialibrary.media.*
import org.videolan.tools.coroutineScope
import org.videolan.vlc.R
import org.videolan.vlc.util.getFromMl
import java.util.*
......@@ -75,7 +75,7 @@ class SearchFragment : SearchSupportFragment(), SearchSupportFragment.SearchResu
return true
}
private fun loadRows(query: String?) = launch(UI.immediate) {
private fun loadRows(query: String?) = coroutineScope.launch {
val searchAggregate = context?.getFromMl { search(query) } ?: return@launch
val empty = searchAggregate.isEmpty
val mediaEmpty = empty || (Tools.isArrayEmpty(searchAggregate.tracks) && Tools.isArrayEmpty(searchAggregate.videos))
......
......@@ -152,7 +152,7 @@ class DisplayManager(private val activity: Activity, cloneMode: Boolean, benchma
lateinit var surfaceFrame: FrameLayout
companion object {
val TAG = "VLC/SecondaryDisplay"
const val TAG = "VLC/SecondaryDisplay"
}
override fun onCreate(savedInstanceState: Bundle?) {
......
......@@ -163,7 +163,7 @@ object MediaUtils : CoroutineScope {
val count = withContext(Dispatchers.IO) { model.getTotalCount() }
when (count) {
0 -> null
in 1..PAGE_SIZE -> withContext(Dispatchers.IO) { model.getAll()?.toList() }
in 1..PAGE_SIZE -> withContext(Dispatchers.IO) { model.getAll().toList() }
else -> withContext(Dispatchers.IO) {
mutableListOf<MediaWrapper>().apply {
var index = 0
......
......@@ -197,11 +197,9 @@ class PlayerController(val context: Context) : IVLCVout.Callback, MediaPlayer.Ev
slaves?.let { it.forEach { slave -> media.addSlave(slave) } }
media.release()
slaves?.let {
val jobs = slaveRepository.saveSlaves(mw)
jobs?.forEach { it.join() }
slaveRepository.saveSlaves(mw)?.forEach { it.join() }
}
val list = slaveRepository.getSlaves(mw.location)
list?.forEach { slave ->
slaveRepository.getSlaves(mw.location).forEach { slave ->
mediaplayer.addSlave(slave.type, Uri.parse(slave.uri), false)
}
}
......
......@@ -130,13 +130,13 @@ class PlaylistManager(val service: PlaybackService) : MediaWrapperList.EventList
if (loadingLastPlaylist) return true
loadingLastPlaylist = true
val audio = type == PLAYLIST_TYPE_AUDIO
val currentMedia = settings.getString(if (audio) "current_song" else "current_media", "")
val currentMedia = settings.getString(if (audio) "current_song" else "current_media", "")!!
if (currentMedia.isEmpty()) {
loadingLastPlaylist = false
return false
}
val locations = settings.getString(if (audio) "audio_list" else "media_list", "").split(" ".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
if (Util.isArrayEmpty(locations)) {
val locations = settings.getString(if (audio) "audio_list" else "media_list", null)?.split(" ".toRegex())?.dropLastWhile({ it.isEmpty() })?.toTypedArray()
if (locations?.isNotEmpty() != false) {
loadingLastPlaylist = false
return false
}
......@@ -694,7 +694,7 @@ class PlaylistManager(val service: PlaybackService) : MediaWrapperList.EventList
MediaPlayer.Event.Playing -> {
medialibrary.pauseBackgroundOperations()
videoBackground = false
val mw = withContext(IO) {
val mw = withContext(Dispatchers.IO) {
val current = getCurrentMedia()
medialibrary.findMedia(current).apply { if (type == -1) type = current?.type ?: -1 }
}
......
......@@ -198,7 +198,7 @@ abstract class BrowserProvider(val context: Context, val dataset: LiveDataset<Me
val mw = MediaWrapper(media)
val uri = mw.uri
if ((mw.type == MediaWrapper.TYPE_AUDIO || mw.type == MediaWrapper.TYPE_VIDEO)
&& "file" == uri.scheme) return withContext(IO) { medialibrary.getMedia(uri) ?: mw }
&& "file" == uri.scheme) return withContext(Dispatchers.IO) { medialibrary.getMedia(uri) ?: mw }
return mw
}
......
......@@ -24,10 +24,11 @@ import android.arch.lifecycle.MediatorLiveData
import android.content.Context
import android.net.Uri
import android.support.annotation.WorkerThread
import kotlinx.coroutines.experimental.IO
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.launch
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.tools.IOScopedObject
import org.videolan.tools.SingletonHolder
import org.videolan.vlc.ExternalMonitor
import org.videolan.vlc.database.BrowserFavDao
......@@ -39,7 +40,7 @@ import org.videolan.vlc.util.convertFavorites
import java.util.*
class BrowserFavRepository(private val browserFavDao: BrowserFavDao) {
class BrowserFavRepository(private val browserFavDao: BrowserFavDao) : IOScopedObject() {
private val networkFavs by lazy { browserFavDao.getAllNetwrokFavs() }
......@@ -47,11 +48,11 @@ class BrowserFavRepository(private val browserFavDao: BrowserFavDao) {
val localFavorites by lazy { browserFavDao.getAllLocalFavs() }
fun addNetworkFavItem(uri: Uri, title: String, iconUrl: String?) = launch(IO) {
fun addNetworkFavItem(uri: Uri, title: String, iconUrl: String?) = launch {
browserFavDao.insert(BrowserFav(uri, TYPE_NETWORK_FAV, title, iconUrl))
}
fun addLocalFavItem(uri: Uri, title: String, iconUrl: String? = null) = launch(IO) {
fun addLocalFavItem(uri: Uri, title: String, iconUrl: String? = null) = launch {
browserFavDao.insert(BrowserFav(uri, TYPE_LOCAL_FAV, title, iconUrl))
}
......@@ -59,7 +60,7 @@ class BrowserFavRepository(private val browserFavDao: BrowserFavDao) {
MediatorLiveData<List<MediaWrapper>>().apply {
addSource(networkFavs) { value = convertFavorites(it).filterNetworkFavs() }
addSource(ExternalMonitor.connected) {
launch(UI.immediate) {
launch(Dispatchers.Main.immediate) {
val favList = convertFavorites(networkFavs.value)
if (favList.isNotEmpty()) value = if (it == true) favList.filterNetworkFavs() else emptyList()
}
......@@ -70,7 +71,7 @@ class BrowserFavRepository(private val browserFavDao: BrowserFavDao) {
@WorkerThread
fun browserFavExists(uri: Uri): Boolean = browserFavDao.get(uri).isNotEmpty()
fun deleteBrowserFav(uri: Uri) = launch(IO) { browserFavDao.delete(uri) }
fun deleteBrowserFav(uri: Uri) = launch { browserFavDao.delete(uri) }
private fun List<MediaWrapper>.filterNetworkFavs() : List<MediaWrapper> {
return when {
......
......@@ -2,12 +2,12 @@ package org.videolan.vlc.repository
import android.content.Context
import android.text.TextUtils
import kotlinx.coroutines.experimental.IO
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.withContext
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.tools.IOScopedObject
import org.videolan.tools.SingletonHolder
import org.videolan.vlc.R
import org.videolan.vlc.database.CustomDirectoryDao
......@@ -19,17 +19,17 @@ import org.videolan.vlc.util.AndroidDevices.getExternalStorageDirectories
import org.videolan.vlc.util.FileUtils
import java.io.File
class DirectoryRepository (private val customDirectoryDao: CustomDirectoryDao) {
class DirectoryRepository (private val customDirectoryDao: CustomDirectoryDao) : IOScopedObject() {
fun addCustomDirectory(path: String): Job = launch(IO) {
fun addCustomDirectory(path: String): Job = launch {
customDirectoryDao.insert(CustomDirectory(path))
}
suspend fun getCustomDirectories() = withContext(IO) { customDirectoryDao.getAll() }
suspend fun getCustomDirectories() = withContext(coroutineContext) { customDirectoryDao.getAll() }
fun deleteCustomDirectory(path: String) = launch(IO) { customDirectoryDao.delete(CustomDirectory(path)) }
fun deleteCustomDirectory(path: String) = launch { customDirectoryDao.delete(CustomDirectory(path)) }
suspend fun customDirectoryExists(path: String) = withContext(IO) { customDirectoryDao.get(path).isNotEmpty() }
suspend fun customDirectoryExists(path: String) = withContext(coroutineContext) { customDirectoryDao.get(path).isNotEmpty() }
suspend fun getMediaDirectoriesList(context: Context): List<MediaWrapper> {
val storages = getMediaDirectories()
......
......@@ -22,36 +22,32 @@ package org.videolan.vlc.repository
import android.content.Context
import android.net.Uri
import kotlinx.coroutines.experimental.IO
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.withContext
import kotlinx.coroutines.experimental.*
import org.videolan.libvlc.Media
import org.videolan.medialibrary.media.MediaWrapper
import org.videolan.tools.IOScopedObject
import org.videolan.tools.SingletonHolder
import org.videolan.vlc.database.MediaDatabase
import org.videolan.vlc.database.SlaveDao
import org.videolan.vlc.database.models.Slave
class SlaveRepository(private val slaveDao:SlaveDao){
class SlaveRepository(private val slaveDao:SlaveDao) : IOScopedObject() {
fun saveSlave(mediaPath: String, type: Int, priority: Int, uriString: String): Job {
return launch(IO) {
return launch {
slaveDao.insert(Slave(mediaPath, type, priority, uriString))
}
}
fun saveSlaves(mw: MediaWrapper): List<Job>? {
return mw.slaves?.let{
it.map {
saveSlave(mw.location, it.type, it.priority, it.uri)
}
it.map { saveSlave(mw.location, it.type, it.priority, it.uri) }
}
}
suspend fun getSlaves(mrl: String): List<Media.Slave> {
return withContext(IO) {
return withContext(Dispatchers.IO) {
val slaves = slaveDao.get(mrl)
val mediaSlaves = slaves.map {
var uri = it.uri
......
......@@ -73,9 +73,9 @@ const val ACTION_RESUME_SCAN = "action_resume_scan"
const val ACTION_PAUSE_SCAN = "action_pause_scan"
// VideoPlayerActivity
@JvmField val PLAY_FROM_VIDEOGRID = Strings.buildPkgString("gui.video.PLAY_FROM_VIDEOGRID")!!
@JvmField val PLAY_FROM_SERVICE = Strings.buildPkgString("gui.video.PLAY_FROM_SERVICE")!!
@JvmField val EXIT_PLAYER = Strings.buildPkgString("gui.video.EXIT_PLAYER")!!
@JvmField val PLAY_FROM_VIDEOGRID = Strings.buildPkgString("gui.video.PLAY_FROM_VIDEOGRID")
@JvmField val PLAY_FROM_SERVICE = Strings.buildPkgString("gui.video.PLAY_FROM_SERVICE")
@JvmField val EXIT_PLAYER = Strings.buildPkgString("gui.video.EXIT_PLAYER")
const val PLAY_EXTRA_ITEM_LOCATION = "item_location"
const val PLAY_EXTRA_SUBTITLES_LOCATION = "subtitles_location"
const val PLAY_EXTRA_ITEM_TITLE = "title"
......
......@@ -23,7 +23,8 @@ package org.videolan.vlc.util
import org.videolan.vlc.BuildConfig
import java.text.DecimalFormat
private val TAG = "VLC/UiTools/Strings"
private const val TAG = "VLC/UiTools/Strings"
object Strings {
fun stripTrailingSlash(s: String): String {
......
......@@ -113,7 +113,7 @@ open class VideosModel(context: Context, private val group: String?, private val
class Factory(private val context: Context, val group: String?, private val minGroupLen : Int, private val sort : Int, private val desc : Boolean?): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
val length = if (minGroupLen == 0) Integer.valueOf(Settings.getInstance(context).getString("video_min_group_length", "6")) else minGroupLen
val length = if (minGroupLen == 0) Integer.valueOf(Settings.getInstance(context).getString("video_min_group_length", "6")!!) else minGroupLen
@Suppress("UNCHECKED_CAST")
return VideosModel(context.applicationContext, group, length, sort, desc) as T
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment