diff --git a/android/app/src/main/java/com/audiobookshelf/app/data/DataClasses.kt b/android/app/src/main/java/com/audiobookshelf/app/data/DataClasses.kt index b87fa0dd..65be49a0 100644 --- a/android/app/src/main/java/com/audiobookshelf/app/data/DataClasses.kt +++ b/android/app/src/main/java/com/audiobookshelf/app/data/DataClasses.kt @@ -25,7 +25,8 @@ data class LibraryItem( var isInvalid:Boolean, var mediaType:String, var media:MediaType, - var libraryFiles:MutableList? + var libraryFiles:MutableList?, + var userMediaProgress:MediaProgress? // Only included when requesting library item with progress (for downloads) ) : LibraryItemWrapper() { @get:JsonIgnore val title get() = media.metadata.title @@ -131,7 +132,7 @@ class Podcast( } } @JsonIgnore - fun addEpisode(audioTrack:AudioTrack, episode:PodcastEpisode) { + fun addEpisode(audioTrack:AudioTrack, episode:PodcastEpisode):PodcastEpisode { val newEpisode = PodcastEpisode("local_" + episode.id,episodes?.size ?: 0 + 1,episode.episode,episode.episodeType,episode.title,episode.subtitle,episode.description,null,audioTrack,audioTrack.duration,0, episode.id) episodes?.add(newEpisode) @@ -140,6 +141,7 @@ class Podcast( it.index = index index++ } + return newEpisode } // Used for FolderScanner local podcast item to get copy of Podcast excluding episodes @@ -355,3 +357,17 @@ data class BookChapter( var end:Double, var title:String? ) + +@JsonIgnoreProperties(ignoreUnknown = true) +data class MediaProgress( + var id:String, + var libraryItemId:String, + var episodeId:String?, + var duration:Double, // seconds + var progress:Double, // 0 to 1 + var currentTime:Double, + var isFinished:Boolean, + var lastUpdate:Long, + var startedAt:Long, + var finishedAt:Long? +) diff --git a/android/app/src/main/java/com/audiobookshelf/app/data/LocalLibraryItem.kt b/android/app/src/main/java/com/audiobookshelf/app/data/LocalLibraryItem.kt index df6c2f94..04624a06 100644 --- a/android/app/src/main/java/com/audiobookshelf/app/data/LocalLibraryItem.kt +++ b/android/app/src/main/java/com/audiobookshelf/app/data/LocalLibraryItem.kt @@ -66,24 +66,25 @@ data class LocalLibraryItem( @JsonIgnore fun getPlaybackSession(episode:PodcastEpisode?):PlaybackSession { - var localEpisodeId = episode?.id - var sessionId = "play_local_${UUID.randomUUID()}" + val localEpisodeId = episode?.id + val sessionId = "play_local_${UUID.randomUUID()}" + // Get current progress for local media val mediaProgressId = if (localEpisodeId.isNullOrEmpty()) id else "$id-$localEpisodeId" - var mediaProgress = DeviceManager.dbManager.getLocalMediaProgress(mediaProgressId) - var currentTime = mediaProgress?.currentTime ?: 0.0 + val mediaProgress = DeviceManager.dbManager.getLocalMediaProgress(mediaProgressId) + val currentTime = mediaProgress?.currentTime ?: 0.0 // TODO: Clean up add mediaType methods for displayTitle and displayAuthor - var mediaMetadata = media.metadata - var chapters = if (mediaType == "book") (media as Book).chapters else mutableListOf() + val mediaMetadata = media.metadata + val chapters = if (mediaType == "book") (media as Book).chapters else mutableListOf() var audioTracks = media.getAudioTracks() as MutableList - var authorName = mediaMetadata.getAuthorDisplayName() + val authorName = mediaMetadata.getAuthorDisplayName() if (episode != null) { // Get podcast episode audio track episode.audioTrack?.let { at -> mutableListOf(at) }?.let { tracks -> audioTracks = tracks } Log.d("LocalLibraryItem", "getPlaybackSession: Got podcast episode audio track ${audioTracks.size}") } - var dateNow = System.currentTimeMillis() + val dateNow = System.currentTimeMillis() return PlaybackSession(sessionId,serverUserId,libraryItemId,episode?.serverEpisodeId, mediaType, mediaMetadata, chapters ?: mutableListOf(), mediaMetadata.title, authorName,null,getDuration(),PLAYMETHOD_LOCAL,dateNow,0L,0L, audioTracks,currentTime,null,this,localEpisodeId,serverConnectionConfigId, serverAddress, "exo-player") } diff --git a/android/app/src/main/java/com/audiobookshelf/app/device/FolderScanner.kt b/android/app/src/main/java/com/audiobookshelf/app/device/FolderScanner.kt index 0d454a27..6142b625 100644 --- a/android/app/src/main/java/com/audiobookshelf/app/device/FolderScanner.kt +++ b/android/app/src/main/java/com/audiobookshelf/app/device/FolderScanner.kt @@ -19,6 +19,7 @@ class FolderScanner(var ctx: Context) { private val tag = "FolderScanner" var jacksonMapper = jacksonObjectMapper().enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature()) + data class DownloadItemScanResult(val localLibraryItem:LocalLibraryItem, var localMediaProgress:LocalMediaProgress?) private fun getLocalLibraryItemId(mediaItemId:String):String { return "local_" + DeviceManager.getBase64Id(mediaItemId) @@ -217,9 +218,9 @@ class FolderScanner(var ctx: Context) { } // Scan item after download and create local library item - fun scanDownloadItem(downloadItem: AbsDownloader.DownloadItem):LocalLibraryItem? { - var folderDf = DocumentFileCompat.fromUri(ctx, Uri.parse(downloadItem.localFolder.contentUrl)) - var foldersFound = folderDf?.search(false, DocumentFileType.FOLDER) ?: mutableListOf() + fun scanDownloadItem(downloadItem: AbsDownloader.DownloadItem):DownloadItemScanResult? { + val folderDf = DocumentFileCompat.fromUri(ctx, Uri.parse(downloadItem.localFolder.contentUrl)) + val foldersFound = folderDf?.search(false, DocumentFileType.FOLDER) ?: mutableListOf() var itemFolderId = "" var itemFolderUrl = "" @@ -238,20 +239,21 @@ class FolderScanner(var ctx: Context) { Log.d(tag, "scanDownloadItem failed to find media folder") return null } - var df: DocumentFile? = DocumentFileCompat.fromUri(ctx, Uri.parse(itemFolderUrl)) + val df: DocumentFile? = DocumentFileCompat.fromUri(ctx, Uri.parse(itemFolderUrl)) if (df == null) { Log.e(tag, "Folder Doc File Invalid ${downloadItem.itemFolderPath}") return null } - var localLibraryItemId = getLocalLibraryItemId(itemFolderId) + val localLibraryItemId = getLocalLibraryItemId(itemFolderId) Log.d(tag, "scanDownloadItem starting for ${downloadItem.itemFolderPath} | ${df.uri} | Item Folder Id:$itemFolderId | LLI Id:$localLibraryItemId") // Search for files in media item folder - var filesFound = df.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4")) + val filesFound = df.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4")) Log.d(tag, "scanDownloadItem ${filesFound.size} files found in ${downloadItem.itemFolderPath}") + var localEpisodeId:String? = null var localLibraryItem:LocalLibraryItem? = null if (downloadItem.mediaType == "book") { localLibraryItem = LocalLibraryItem(localLibraryItemId, downloadItem.localFolder.id, itemFolderBasePath, itemFolderAbsolutePath, itemFolderUrl, false, downloadItem.mediaType, downloadItem.media.getLocalCopy(), mutableListOf(), null, null, true, downloadItem.serverConnectionConfigId, downloadItem.serverAddress, downloadItem.serverUserId, downloadItem.libraryItemId) @@ -264,10 +266,10 @@ class FolderScanner(var ctx: Context) { } } - var audioTracks:MutableList = mutableListOf() + val audioTracks:MutableList = mutableListOf() filesFound.forEach { docFile -> - var itemPart = downloadItem.downloadItemParts.find { itemPart -> + val itemPart = downloadItem.downloadItemParts.find { itemPart -> itemPart.filename == docFile.name } if (itemPart == null) { @@ -275,31 +277,32 @@ class FolderScanner(var ctx: Context) { Log.e(tag, "scanDownloadItem: Item part not found for doc file ${docFile.name} | ${docFile.getAbsolutePath(ctx)} | ${docFile.uri}") } } else if (itemPart.audioTrack != null) { // Is audio track - var audioTrackFromServer = itemPart.audioTrack + val audioTrackFromServer = itemPart.audioTrack Log.d(tag, "scanDownloadItem: Audio Track from Server index = ${audioTrackFromServer?.index}") - var localFileId = DeviceManager.getBase64Id(docFile.id) - var localFile = LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx),docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length()) + val localFileId = DeviceManager.getBase64Id(docFile.id) + val localFile = LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx),docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length()) localLibraryItem.localFiles.add(localFile) // TODO: Make asynchronous - var audioProbeResult = probeAudioFile(localFile.absolutePath) + val audioProbeResult = probeAudioFile(localFile.absolutePath) // Create new audio track - var track = AudioTrack(audioTrackFromServer?.index ?: -1, audioTrackFromServer?.startOffset ?: 0.0, audioProbeResult.duration, localFile.filename ?: "", localFile.contentUrl, localFile.mimeType ?: "", null, true, localFileId, audioProbeResult, audioTrackFromServer?.index ?: -1) + val track = AudioTrack(audioTrackFromServer?.index ?: -1, audioTrackFromServer?.startOffset ?: 0.0, audioProbeResult.duration, localFile.filename ?: "", localFile.contentUrl, localFile.mimeType ?: "", null, true, localFileId, audioProbeResult, audioTrackFromServer?.index ?: -1) audioTracks.add(track) Log.d(tag, "scanDownloadItem: Created Audio Track with index ${track.index} from local file ${localFile.absolutePath}") // Add podcast episodes to library itemPart.episode?.let { podcastEpisode -> - var podcast = localLibraryItem.media as Podcast - podcast.addEpisode(track, podcastEpisode) + val podcast = localLibraryItem.media as Podcast + var newEpisode = podcast.addEpisode(track, podcastEpisode) + localEpisodeId = newEpisode.id Log.d(tag, "scanDownloadItem: Added episode to podcast ${podcastEpisode.title} ${track.title} | Track index: ${podcastEpisode.audioTrack?.index}") } } else { // Cover image - var localFileId = DeviceManager.getBase64Id(docFile.id) - var localFile = LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx),docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length()) + val localFileId = DeviceManager.getBase64Id(docFile.id) + val localFile = LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx),docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length()) localLibraryItem.coverAbsolutePath = localFile.absolutePath localLibraryItem.coverContentUrl = localFile.contentUrl @@ -330,9 +333,36 @@ class FolderScanner(var ctx: Context) { localLibraryItem.media.setAudioTracks(audioTracks) } + val downloadItemScanResult = DownloadItemScanResult(localLibraryItem,null) + + // If library item had media progress then make local media progress and save + downloadItem.userMediaProgress?.let { mediaProgress -> + val localMediaProgressId = if (downloadItem.episodeId.isNullOrEmpty()) localLibraryItemId else "$localLibraryItemId-$localEpisodeId" + val newLocalMediaProgress = LocalMediaProgress( + id = localMediaProgressId, + localLibraryItemId = localLibraryItemId, + localEpisodeId = localEpisodeId, + duration = mediaProgress.duration, + progress = mediaProgress.progress, + currentTime = mediaProgress.currentTime, + isFinished = false, + lastUpdate = mediaProgress.lastUpdate, + startedAt = mediaProgress.startedAt, + finishedAt = mediaProgress.finishedAt, + serverConnectionConfigId = downloadItem.serverConnectionConfigId, + serverAddress = downloadItem.serverAddress, + serverUserId = downloadItem.serverUserId, + libraryItemId = downloadItem.libraryItemId, + episodeId = downloadItem.episodeId) + Log.d(tag, "scanLibraryItemFolder: Saving local media progress ${newLocalMediaProgress.id} at progress ${newLocalMediaProgress.progress}") + DeviceManager.dbManager.saveLocalMediaProgress(newLocalMediaProgress) + + downloadItemScanResult.localMediaProgress = newLocalMediaProgress + } + DeviceManager.dbManager.saveLocalLibraryItem(localLibraryItem) - return localLibraryItem + return downloadItemScanResult } fun scanLocalLibraryItem(localLibraryItem:LocalLibraryItem, forceAudioProbe:Boolean):LocalLibraryItemScanResult? { diff --git a/android/app/src/main/java/com/audiobookshelf/app/plugins/AbsDownloader.kt b/android/app/src/main/java/com/audiobookshelf/app/plugins/AbsDownloader.kt index bd161d3c..75c56a96 100644 --- a/android/app/src/main/java/com/audiobookshelf/app/plugins/AbsDownloader.kt +++ b/android/app/src/main/java/com/audiobookshelf/app/plugins/AbsDownloader.kt @@ -105,6 +105,7 @@ class AbsDownloader : Plugin() { val id: String, val libraryItemId:String, val episodeId:String?, + val userMediaProgress:MediaProgress?, val serverConnectionConfigId:String, val serverAddress:String, val serverUserId:String, @@ -141,7 +142,7 @@ class AbsDownloader : Plugin() { return call.resolve(JSObject("{\"error\":\"Download already started for this media entity\"}")) } - apiHandler.getLibraryItem(libraryItemId) { libraryItem -> + apiHandler.getLibraryItemWithProgress(libraryItemId, episodeId) { libraryItem -> Log.d(tag, "Got library item from server ${libraryItem.id}") val localFolder = DeviceManager.dbManager.getLocalFolder(localFolderId) @@ -191,7 +192,7 @@ class AbsDownloader : Plugin() { val tracks = libraryItem.media.getAudioTracks() Log.d(tag, "Starting library item download with ${tracks.size} tracks") val itemFolderPath = localFolder.absolutePath + "/" + bookTitle - val downloadItem = DownloadItem(libraryItem.id, libraryItem.id, null,DeviceManager.serverConnectionConfig?.id ?: "", DeviceManager.serverAddress, DeviceManager.serverUserId, libraryItem.mediaType, itemFolderPath, localFolder, bookTitle, libraryItem.media, mutableListOf()) + val downloadItem = DownloadItem(libraryItem.id, libraryItem.id, null, libraryItem.userMediaProgress,DeviceManager.serverConnectionConfig?.id ?: "", DeviceManager.serverAddress, DeviceManager.serverUserId, libraryItem.mediaType, itemFolderPath, localFolder, bookTitle, libraryItem.media, mutableListOf()) // Create download item part for each audio track tracks.forEach { audioTrack -> @@ -248,7 +249,7 @@ class AbsDownloader : Plugin() { Log.d(tag, "Starting podcast episode download") val itemFolderPath = localFolder.absolutePath + "/" + podcastTitle val downloadItemId = "${libraryItem.id}-${episode?.id}" - val downloadItem = DownloadItem(downloadItemId, libraryItem.id, episode?.id, DeviceManager.serverConnectionConfig?.id ?: "", DeviceManager.serverAddress, DeviceManager.serverUserId, libraryItem.mediaType, itemFolderPath, localFolder, podcastTitle, libraryItem.media, mutableListOf()) + val downloadItem = DownloadItem(downloadItemId, libraryItem.id, episode?.id, libraryItem.userMediaProgress, DeviceManager.serverConnectionConfig?.id ?: "", DeviceManager.serverAddress, DeviceManager.serverUserId, libraryItem.mediaType, itemFolderPath, localFolder, podcastTitle, libraryItem.media, mutableListOf()) var serverPath = "/s/item/${libraryItem.id}/${cleanRelPath(audioTrack?.relPath ?: "")}" var destinationFilename = getFilenameFromRelPath(audioTrack?.relPath ?: "") @@ -309,18 +310,22 @@ class AbsDownloader : Plugin() { delay(500) } - val localLibraryItem = folderScanner.scanDownloadItem(downloadItem) + val downloadItemScanResult = folderScanner.scanDownloadItem(downloadItem) DeviceManager.dbManager.removeDownloadItem(downloadItem.id) downloadQueue.remove(downloadItem) - Log.d(tag, "Item download complete ${downloadItem.itemTitle} | local library item id: ${localLibraryItem?.id} | Items remaining in Queue ${downloadQueue.size}") + Log.d(tag, "Item download complete ${downloadItem.itemTitle} | local library item id: ${downloadItemScanResult?.localLibraryItem?.id} | Items remaining in Queue ${downloadQueue.size}") val jsobj = JSObject() jsobj.put("libraryItemId", downloadItem.id) jsobj.put("localFolderId", downloadItem.localFolder.id) - if (localLibraryItem != null) { + + downloadItemScanResult?.localLibraryItem?.let { localLibraryItem -> jsobj.put("localLibraryItem", JSObject(jacksonMapper.writeValueAsString(localLibraryItem))) } + downloadItemScanResult?.localMediaProgress?.let { localMediaProgress -> + jsobj.put("localMediaProgress", JSObject(jacksonMapper.writeValueAsString(localMediaProgress))) + } notifyListeners("onItemDownloadComplete", jsobj) } } diff --git a/android/app/src/main/java/com/audiobookshelf/app/server/ApiHandler.kt b/android/app/src/main/java/com/audiobookshelf/app/server/ApiHandler.kt index 7c69d89a..674e6c39 100644 --- a/android/app/src/main/java/com/audiobookshelf/app/server/ApiHandler.kt +++ b/android/app/src/main/java/com/audiobookshelf/app/server/ApiHandler.kt @@ -88,13 +88,13 @@ class ApiHandler(var ctx:Context) { response.use { if (!it.isSuccessful) throw IOException("Unexpected code $response") - var bodyString = it.body!!.string() + val bodyString = it.body!!.string() if (bodyString == "OK") { cb(JSObject()) } else { var jsonObj = JSObject() if (bodyString.startsWith("[")) { - var array = JSArray(bodyString) + val array = JSArray(bodyString) jsonObj.put("value", array) } else { jsonObj = JSObject(bodyString) @@ -111,7 +111,7 @@ class ApiHandler(var ctx:Context) { getRequest("/api/libraries") { val libraries = mutableListOf() if (it.has("value")) { - var array = it.getJSONArray("value") + val array = it.getJSONArray("value") for (i in 0 until array.length()) { val library = mapper.readValue(array.get(i).toString()) libraries.add(library) @@ -128,11 +128,20 @@ class ApiHandler(var ctx:Context) { } } + fun getLibraryItemWithProgress(libraryItemId:String, episodeId:String?, cb: (LibraryItem) -> Unit) { + var requestUrl = "/api/items/$libraryItemId?expanded=1&include=progress" + if (!episodeId.isNullOrEmpty()) requestUrl += "&episode=$episodeId" + getRequest(requestUrl) { + val libraryItem = jacksonMapper.readValue(it.toString()) + cb(libraryItem) + } + } + fun getLibraryItems(libraryId:String, cb: (List) -> Unit) { getRequest("/api/libraries/$libraryId/items?limit=100&minified=1") { val items = mutableListOf() if (it.has("results")) { - var array = it.getJSONArray("results") + val array = it.getJSONArray("results") for (i in 0 until array.length()) { val item = jacksonMapper.readValue(array.get(i).toString()) items.add(item) @@ -146,11 +155,11 @@ class ApiHandler(var ctx:Context) { getRequest("/api/libraries/$libraryId/personalized") { val items = mutableListOf() if (it.has("value")) { - var array = it.getJSONArray("value") + val array = it.getJSONArray("value") for (i in 0 until array.length()) { - var jsobj = array.get(i) as JSONObject + val jsobj = array.get(i) as JSONObject - var type = jsobj.get("type").toString() + val type = jsobj.get("type").toString() // Only support for podcast and book in android auto if (type == "podcast" || type == "book") { jsobj.put("isLocal", false) @@ -164,7 +173,7 @@ class ApiHandler(var ctx:Context) { } fun playLibraryItem(libraryItemId:String, episodeId:String?, forceTranscode:Boolean, mediaPlayer:String, cb: (PlaybackSession) -> Unit) { - var payload = JSObject() + val payload = JSObject() payload.put("mediaPlayer", mediaPlayer) // Only if direct play fails do we force transcode @@ -181,7 +190,7 @@ class ApiHandler(var ctx:Context) { } fun sendProgressSync(sessionId:String, syncData: MediaProgressSyncData, cb: () -> Unit) { - var payload = JSObject(jacksonMapper.writeValueAsString(syncData)) + val payload = JSObject(jacksonMapper.writeValueAsString(syncData)) postRequest("/api/session/$sessionId/sync", payload) { cb() @@ -189,7 +198,7 @@ class ApiHandler(var ctx:Context) { } fun sendLocalProgressSync(playbackSession:PlaybackSession, cb: () -> Unit) { - var payload = JSObject(jacksonMapper.writeValueAsString(playbackSession)) + val payload = JSObject(jacksonMapper.writeValueAsString(playbackSession)) postRequest("/api/session/local", payload) { cb() @@ -204,15 +213,15 @@ class ApiHandler(var ctx:Context) { } // Get all local media progress connected to items on the current connected server - var localMediaProgress = DeviceManager.dbManager.getAllLocalMediaProgress().filter { + val localMediaProgress = DeviceManager.dbManager.getAllLocalMediaProgress().filter { it.serverConnectionConfigId == DeviceManager.serverConnectionConfig?.id } - var localSyncResultsPayload = LocalMediaProgressSyncResultsPayload(localMediaProgress.size,0, 0) + val localSyncResultsPayload = LocalMediaProgressSyncResultsPayload(localMediaProgress.size,0, 0) if (localMediaProgress.isNotEmpty()) { Log.d(tag, "Sending sync local progress request with ${localMediaProgress.size} progress items") - var payload = JSObject(jacksonMapper.writeValueAsString(LocalMediaProgressSyncPayload(localMediaProgress))) + val payload = JSObject(jacksonMapper.writeValueAsString(LocalMediaProgressSyncPayload(localMediaProgress))) postRequest("/api/me/sync-local-progress", payload) { Log.d(tag, "Media Progress Sync payload $payload - response ${it.toString()}") @@ -242,7 +251,7 @@ class ApiHandler(var ctx:Context) { fun updateMediaProgress(libraryItemId:String,episodeId:String?,updatePayload:JSObject, cb: () -> Unit) { Log.d(tag, "updateMediaProgress $libraryItemId $episodeId $updatePayload") - var endpoint = if(episodeId.isNullOrEmpty()) "/api/me/progress/$libraryItemId" else "/api/me/progress/$libraryItemId/$episodeId" + val endpoint = if(episodeId.isNullOrEmpty()) "/api/me/progress/$libraryItemId" else "/api/me/progress/$libraryItemId/$episodeId" patchRequest(endpoint,updatePayload) { Log.d(tag, "updateMediaProgress patched progress") cb() diff --git a/components/widgets/DownloadProgressIndicator.vue b/components/widgets/DownloadProgressIndicator.vue index 9d4ddb08..43bc6d54 100644 --- a/components/widgets/DownloadProgressIndicator.vue +++ b/components/widgets/DownloadProgressIndicator.vue @@ -97,6 +97,11 @@ export default { this.$eventBus.$emit('new-local-library-item', data.localLibraryItem) } + if (data.localMediaProgress) { + console.log('onItemDownloadComplete updating local media progress', data.localMediaProgress.id) + this.$store.commit('globals/updateLocalMediaProgress', data.localMediaProgress) + } + this.$store.commit('globals/removeItemDownload', data.libraryItemId) } },