Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Track and show results from Indexing #15

Draft
wants to merge 2 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import zechs.zplex.data.model.drive.DriveFile
import zechs.zplex.data.model.entities.Movie
import zechs.zplex.data.model.entities.Show
import zechs.zplex.data.remote.RemoteLibrary
import zechs.zplex.service.IndexingResult
import zechs.zplex.service.IndexingStateFlow
import zechs.zplex.utils.SessionManager
import zechs.zplex.utils.state.Resource
import zechs.zplex.utils.util.DriveApiQueryBuilder
Expand All @@ -18,7 +20,8 @@ import javax.inject.Inject
class RemoteLibraryRepository @Inject constructor(
private val driveRepository: DriveRepository,
private val tmdbRepository: TmdbRepository,
private val sessionManager: SessionManager
private val sessionManager: SessionManager,
private val indexingStateFlow: IndexingStateFlow
) : RemoteLibrary {

companion object {
Expand All @@ -32,12 +35,16 @@ class RemoteLibraryRepository @Inject constructor(
val fileId: String
)

private val moviesResult = IndexingResult()
private val showsResult = IndexingResult()

override suspend fun indexMovies() {
Log.d(TAG, "Beginning indexing movies...")


if (!doesMoviesFolderExist()) {
Log.d(TAG, "Movies folder does not exist, skipping show processing.")
Log.d(TAG, "Movies folder does not exist, skipping movies processing.")
indexingStateFlow.emitErrorIndexingMovies("Movies folder does not exist, skipping movies processing.")
return
}

Expand All @@ -58,9 +65,12 @@ class RemoteLibraryRepository @Inject constructor(

processMovies(driveFiles)
} else {
indexingStateFlow.emitErrorIndexingMovies(driveFilesResult.message ?: "Unknown error")
Log.d(TAG, "Error getting files: ${driveFilesResult.message ?: "Unknown error"}")
}

Log.d(TAG, "Movies indexing result: $moviesResult")
indexingStateFlow.emitIndexingResultMovies(moviesResult)
Log.d(TAG, "Ended indexing movies")
}

Expand All @@ -81,7 +91,13 @@ class RemoteLibraryRepository @Inject constructor(
private suspend fun processMovies(driveFiles: List<DriveFile>) {
coroutineScope {
driveFiles
.mapNotNull { parseFileName(it) }
.mapNotNull {
val parse = parseFileName(it)
if (parse == null) {
moviesResult.indexingErrors++
}
parse
}
.map { videoInfo -> async(Dispatchers.IO) { processSingleMovie(videoInfo) } }
.awaitAll()
synchronizeLocalMoviesWithRemote(driveFiles)
Expand All @@ -107,10 +123,12 @@ class RemoteLibraryRepository @Inject constructor(
Log.d(TAG, "Movie already exists: ${videoFile.name}, updating videoId.")
tmdbRepository.upsertMovie(existingMovie.copy(fileId = videoFile.fileId))
}
moviesResult.existingItemsSkipped++
}

private suspend fun insertNewMovie(videoFile: Info) {
Log.d(TAG, "New movie: ${videoFile.name}, inserting into the database.")
moviesResult.newItemsIndexed++

val movieResponse = tmdbRepository.getMovie(videoFile.tmdbId, appendToQuery = null)

Expand All @@ -132,6 +150,7 @@ class RemoteLibraryRepository @Inject constructor(
if (driveFiles.none { driveFile -> driveFile.id == savedMovie.fileId }) {
Log.d(TAG, "Deleting movie: ${savedMovie.title} from the database.")
tmdbRepository.deleteMovie(savedMovie.id)
moviesResult.deleted++
}
}
}
Expand All @@ -141,6 +160,7 @@ class RemoteLibraryRepository @Inject constructor(
Log.d(TAG, "Beginning indexing shows...")

if (!doesShowsFolderExist()) {
indexingStateFlow.emitErrorIndexingShows("Shows folder does not exist, skipping show processing.")
Log.d(TAG, "Shows folder does not exist, skipping show processing.")
return
}
Expand All @@ -162,9 +182,12 @@ class RemoteLibraryRepository @Inject constructor(

processShows(driveFiles)
} else {
indexingStateFlow.emitErrorIndexingShows(driveFilesResult.message ?: "Unknown error")
Log.d(TAG, "Error getting files: ${driveFilesResult.message ?: "Unknown error"}")
}

Log.d(TAG, "Shows indexing result: $showsResult")
indexingStateFlow.emitIndexingResultShows(showsResult)
Log.d(TAG, "Ended indexing shows")
}

Expand All @@ -184,7 +207,11 @@ class RemoteLibraryRepository @Inject constructor(
private suspend fun processShows(shows: List<DriveFile>) {
coroutineScope {
shows
.mapNotNull { parseFileName(it, extension = false) }
.mapNotNull {
val parse = parseFileName(it, extension = false)
if (parse == null) { showsResult.indexingErrors++ }
parse
}
.map { videoInfo -> async(Dispatchers.IO) { processSingleShow(videoInfo) } }
.awaitAll()

Expand Down Expand Up @@ -212,11 +239,13 @@ class RemoteLibraryRepository @Inject constructor(
Log.d(TAG, "Show already exists: ${videoInfo.name}, updating videoId.")
tmdbRepository.upsertShow(existingShow.copy(fileId = videoInfo.fileId))
}
showsResult.existingItemsSkipped++
}


private suspend fun insertNewShow(videoInfo: Info) {
Log.d(TAG, "New show: ${videoInfo.name}, inserting into the database.")
showsResult.newItemsIndexed++

val showResponse = tmdbRepository.getShow(videoInfo.tmdbId, appendToQuery = null)

Expand All @@ -238,6 +267,7 @@ class RemoteLibraryRepository @Inject constructor(
tmdbRepository.getSavedShows().value?.forEach { savedShow ->
if (shows.none { show -> show.id == savedShow.fileId }) {
tmdbRepository.deleteShow(savedShow.id)
showsResult.deleted++
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/zechs/zplex/di/ServiceModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ object ServiceModule {
fun provideRemoteLibrary(
driveRepository: DriveRepository,
tmdbRepository: TmdbRepository,
sessionManager: SessionManager
sessionManager: SessionManager,
indexingStateFlow: IndexingStateFlow
): RemoteLibrary {
return RemoteLibraryRepository(driveRepository, tmdbRepository, sessionManager,)
return RemoteLibraryRepository(driveRepository, tmdbRepository, sessionManager, indexingStateFlow)
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,37 @@ class IndexingStateFlow {
}
}

private val _indexingMoviesState = MutableStateFlow<IndexingState>(IndexingState.Checking)
val indexingMoviesState = _indexingMoviesState.asStateFlow()

fun emitErrorIndexingMovies(message: String) {
coroutineScope.launch {
_indexingMoviesState.value = IndexingState.Error(message)
}
}

fun emitIndexingResultMovies(result: IndexingResult) {
coroutineScope.launch {
_indexingMoviesState.value = IndexingState.Completed(result)
}
}

private val _indexingShowsState = MutableStateFlow<IndexingState>(IndexingState.Checking)
val indexingShowsState = _indexingShowsState.asStateFlow()


fun emitIndexingResultShows(result: IndexingResult) {
coroutineScope.launch {
_indexingShowsState.value = IndexingState.Completed(result)
}
}

fun emitErrorIndexingShows(message: String) {
coroutineScope.launch {
_indexingShowsState.value = IndexingState.Error(message)
}
}

}

sealed interface ServiceState {
Expand All @@ -38,6 +69,13 @@ sealed interface ServiceState {
data class Stopped(val lastRun: String = getTimestamp()) : ServiceState
}


sealed interface IndexingState {
data object Checking : IndexingState
data class Error(val message: String) : IndexingState
data class Completed(val stats: IndexingResult) : IndexingState
}

private fun getTimestamp() = formatDate(Calendar.getInstance().timeInMillis)

private fun formatDate(timeInMillis: Long): String {
Expand All @@ -47,3 +85,10 @@ private fun formatDate(timeInMillis: Long): String {
val dateFormat = SimpleDateFormat("hh:mm a d MMM, yyyy", Locale.ENGLISH)
return dateFormat.format(calendar.time)
}

data class IndexingResult(
var newItemsIndexed: Int = 0,
var existingItemsSkipped: Int = 0,
var indexingErrors: Int = 0,
var deleted: Int = 0,
)
22 changes: 22 additions & 0 deletions app/src/main/java/zechs/zplex/ui/settings/SettingsFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import zechs.zplex.databinding.FragmentSettingsBinding
import zechs.zplex.service.RemoteLibraryIndexingService
import zechs.zplex.service.ServiceState
import zechs.zplex.ui.settings.dialog.LoadingDialog
import zechs.zplex.ui.settings.dialog.StatsDialog
import zechs.zplex.utils.FolderPickerResultContract
import zechs.zplex.utils.FolderType
import zechs.zplex.utils.SelectedFolder
Expand All @@ -50,6 +51,7 @@ class SettingsFragment : Fragment() {
private val viewModel by activityViewModels<SettingsViewModel>()

private var loadingDialog: LoadingDialog? = null
private val statsDialog by lazy { StatsDialog(requireContext()) }

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand Down Expand Up @@ -125,6 +127,7 @@ class SettingsFragment : Fragment() {
loadingObserver()
loginStatusObserver()
indexingServiceObserver()
setupIndexingResultObserver()
}

private fun showFolderPickerDialog(
Expand Down Expand Up @@ -312,6 +315,7 @@ class SettingsFragment : Fragment() {
Intent(requireContext(), RemoteLibraryIndexingService::class.java)
)
}
btnShowDetails.setOnClickListener { statsDialog.show() }
}
}

Expand All @@ -334,7 +338,25 @@ class SettingsFragment : Fragment() {
Snackbar.LENGTH_SHORT
).show()
}
btnShowDetails.setOnClickListener {
Snackbar.make(
binding.root,
getString(R.string.scanning_in_progress),
Snackbar.LENGTH_SHORT
).show()
}
}
}

private fun setupIndexingResultObserver() {
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.combinedIndexingResult.collect { (movies, shows) ->
statsDialog.updateStats(movies, shows)
}
}
}

}

override fun onDestroy() {
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/java/zechs/zplex/ui/settings/SettingsViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,15 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import zechs.zplex.data.repository.TmdbRepository
import zechs.zplex.service.IndexingState
import zechs.zplex.service.IndexingStateFlow
import zechs.zplex.utils.SessionManager
import javax.inject.Inject
Expand Down Expand Up @@ -64,4 +69,13 @@ class SettingsViewModel @Inject constructor(
val isLoggedIn = sessionManager.isLoggedIn()
val indexingServiceStatus = indexingStateFlow.serviceState

val combinedIndexingResult: Flow<Pair<IndexingState, IndexingState>> =
indexingStateFlow.indexingMoviesState
.combine(indexingStateFlow.indexingShowsState) { movies, shows -> Pair(movies, shows) }
.stateIn(
viewModelScope,
SharingStarted.Eagerly,
Pair(IndexingState.Checking, IndexingState.Checking)
)

}
26 changes: 26 additions & 0 deletions app/src/main/java/zechs/zplex/ui/settings/dialog/StatsDialog.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package zechs.zplex.ui.settings.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import zechs.zplex.R
import zechs.zplex.service.IndexingState

class StatsDialog(context: Context) : Dialog(context) {

companion object {
const val TAG = "StatsDialog"
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitle("Media library stats")
setContentView(R.layout.dialog_loading)
}

fun updateStats(movies: IndexingState, shows: IndexingState) {
Log.d(TAG, "updateStats: $movies, $shows")
}

}
48 changes: 48 additions & 0 deletions app/src/main/res/layout/dialog_stats.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:elevation="16sp"
app:cardCornerRadius="48dp">

<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/view_loading"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp">

<ProgressBar
android:id="@+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/textView6"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:text="@string/please_wait"
android:textAlignment="viewStart"
android:textColor="@color/textColor"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="@+id/progressBar2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/progressBar2"
app:layout_constraintTop_toTopOf="@+id/progressBar2" />
</androidx.constraintlayout.widget.ConstraintLayout>

</com.google.android.material.card.MaterialCardView>
Loading