Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48313b60c1 | ||
|
|
3be13025a8 | ||
|
|
505717e580 | ||
|
|
b4bb6bf81b | ||
|
|
6a8d901ce1 | ||
|
|
68f3f0e276 | ||
|
|
ddf8e66a08 | ||
|
|
5b7a492a48 | ||
|
|
9be1ee1843 | ||
|
|
b5c6acc2bc | ||
|
|
39b137c7f1 | ||
|
|
b16a7342aa | ||
|
|
3056c55d2f | ||
|
|
6b416e6fc1 | ||
|
|
e4c6093a82 | ||
|
|
3c1120ea48 | ||
|
|
a41e26e4c6 | ||
|
|
317dc366e3 | ||
|
|
cd4c280950 | ||
|
|
0ca8de5916 | ||
|
|
3840f2f344 | ||
|
|
f353a44fac | ||
|
|
a06796d9ca | ||
|
|
a69054fefa | ||
|
|
6805d7eb96 | ||
|
|
c77d0f1944 | ||
|
|
c457c8eaf7 | ||
|
|
a391db5dc2 | ||
|
|
2180e2f649 | ||
|
|
fc6d16bdd9 | ||
|
|
815529129a | ||
|
|
bad8d10a18 | ||
|
|
a4412da3ed | ||
|
|
870774b408 | ||
|
|
d7dcaa22a6 | ||
|
|
cc0b2943dd | ||
|
|
50ee0b2265 | ||
|
|
910b3a2a17 | ||
|
|
916da91ccb | ||
|
|
d70a99254a | ||
|
|
dcf5bb61a2 | ||
|
|
aa65bb10c1 | ||
|
|
158448f8a2 | ||
|
|
f4be9b3e26 | ||
|
|
15d68ca285 | ||
|
|
ad12e6a19d | ||
|
|
1f1b2fe85a | ||
|
|
480df58ce4 | ||
|
|
2decf532b2 | ||
|
|
3ba87419ae | ||
|
|
1c78af37fa | ||
|
|
2b5373aedd | ||
|
|
99bf960b8a | ||
|
|
c4aca22c28 | ||
|
|
58bd0e0cee | ||
|
|
c1c56f8f52 | ||
|
|
f930ba1941 | ||
|
|
251116a5ce | ||
|
|
06739c0401 | ||
|
|
92f069d1e6 | ||
|
|
62c5042ecc | ||
|
|
604b086c0b | ||
|
|
0e0b356f6b | ||
|
|
573768e2b2 | ||
|
|
236fd09c94 | ||
|
|
cb6cb5f637 | ||
|
|
eb916a3ab0 | ||
|
|
61b8ca1510 | ||
|
|
5d2da97dc5 | ||
|
|
d626686614 | ||
|
|
60ee33cb72 | ||
|
|
8d2498e96d | ||
|
|
1794484bed | ||
|
|
f2b6331843 | ||
|
|
8d5f33245f | ||
|
|
1ee544b842 | ||
|
|
0fd9463c7c | ||
|
|
ad5edf3aee | ||
|
|
d5fafd8cab | ||
|
|
92256f2fed | ||
|
|
5fa8d4c989 | ||
|
|
6b75f79f00 | ||
|
|
b0c9f29d90 | ||
|
|
7721afc116 | ||
|
|
bc85e9bbfa | ||
|
|
e8b6602fe5 |
@@ -29,8 +29,8 @@ android {
|
||||
applicationId "com.audiobookshelf.app"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 73
|
||||
versionName "0.9.44-beta"
|
||||
versionCode 82
|
||||
versionName "0.9.51-beta"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -15,7 +15,6 @@ dependencies {
|
||||
implementation project(':capacitor-network')
|
||||
implementation project(':capacitor-status-bar')
|
||||
implementation project(':capacitor-storage')
|
||||
implementation project(':robingenz-capacitor-app-update')
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:dist="http://schemas.android.com/apk/distribution"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:installLocation="preferExternal"
|
||||
package="com.audiobookshelf.app">
|
||||
|
||||
<!-- Permissions -->
|
||||
|
||||
@@ -22,9 +22,5 @@
|
||||
{
|
||||
"pkg": "@capacitor/storage",
|
||||
"classpath": "com.capacitorjs.plugins.storage.StoragePlugin"
|
||||
},
|
||||
{
|
||||
"pkg": "@robingenz/capacitor-app-update",
|
||||
"classpath": "dev.robingenz.capacitor.appupdate.AppUpdatePlugin"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
package com.audiobookshelf.app
|
||||
|
||||
import android.Manifest
|
||||
import android.app.DownloadManager
|
||||
import android.content.*
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.ServiceConnection
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.*
|
||||
import android.os.Bundle
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
import androidx.core.app.ActivityCompat
|
||||
import com.anggrayudi.storage.SimpleStorage
|
||||
import com.anggrayudi.storage.SimpleStorageHelper
|
||||
import com.audiobookshelf.app.data.AbsDatabase
|
||||
import com.audiobookshelf.app.data.DbManager
|
||||
import com.audiobookshelf.app.player.PlayerNotificationService
|
||||
import com.audiobookshelf.app.plugins.AbsAudioPlayer
|
||||
import com.audiobookshelf.app.plugins.AbsDownloader
|
||||
@@ -50,14 +54,15 @@ class MainActivity : BridgeActivity() {
|
||||
// .build())
|
||||
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
Log.d(tag, "onCreate")
|
||||
|
||||
DbManager.initialize(applicationContext)
|
||||
|
||||
// Grant full storage access for testing
|
||||
// var ss = SimpleStorage(this)
|
||||
// ss.requestFullStorageAccess()
|
||||
|
||||
var permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
val permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
if (permission != PackageManager.PERMISSION_GRANTED) {
|
||||
ActivityCompat.requestPermissions(this,
|
||||
PERMISSIONS_ALL,
|
||||
@@ -68,8 +73,6 @@ class MainActivity : BridgeActivity() {
|
||||
registerPlugin(AbsDownloader::class.java)
|
||||
registerPlugin(AbsFileSystem::class.java)
|
||||
registerPlugin(AbsDatabase::class.java)
|
||||
|
||||
Paper.init(applicationContext)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
@@ -140,9 +143,4 @@ class MainActivity : BridgeActivity() {
|
||||
// Mandatory for Activity, but not for Fragment & ComponentActivity
|
||||
storageHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
}
|
||||
|
||||
// override fun onUserInteraction() {
|
||||
// super.onUserInteraction()
|
||||
// Log.d(tag, "USER INTERACTION")
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -42,6 +42,15 @@ data class LibraryItem(
|
||||
return Uri.parse("${DeviceManager.serverAddress}/api/items/$id/cover?token=${DeviceManager.token}")
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun checkHasTracks():Boolean {
|
||||
return if (mediaType == "podcast") {
|
||||
((media as Podcast).numEpisodes ?: 0) > 0
|
||||
} else {
|
||||
((media as Book).numTracks ?: 0) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun getMediaMetadata(): MediaMetadataCompat {
|
||||
return MediaMetadataCompat.Builder().apply {
|
||||
@@ -74,6 +83,7 @@ open class MediaType(var metadata:MediaTypeMetadata, var coverPath:String?) {
|
||||
open fun removeAudioTrack(localFileId:String) { }
|
||||
@JsonIgnore
|
||||
open fun getLocalCopy():MediaType { return MediaType(MediaTypeMetadata(""),null) }
|
||||
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -82,7 +92,8 @@ class Podcast(
|
||||
coverPath:String?,
|
||||
var tags:MutableList<String>,
|
||||
var episodes:MutableList<PodcastEpisode>?,
|
||||
var autoDownloadEpisodes:Boolean
|
||||
var autoDownloadEpisodes:Boolean,
|
||||
var numEpisodes:Int?
|
||||
) : MediaType(metadata, coverPath) {
|
||||
@JsonIgnore
|
||||
override fun getAudioTracks():List<AudioTrack> {
|
||||
@@ -99,7 +110,7 @@ class Podcast(
|
||||
// Add new episodes
|
||||
audioTracks.forEach { at ->
|
||||
if (episodes?.find{ it.audioTrack?.localFileId == at.localFileId } == null) {
|
||||
val newEpisode = PodcastEpisode("local_" + at.localFileId,episodes?.size ?: 0 + 1,null,null,at.title,null,null,null,at,at.duration,0, null)
|
||||
val newEpisode = PodcastEpisode("local_ep_" + at.localFileId,episodes?.size ?: 0 + 1,null,null,at.title,null,null,null,at,at.duration,0, null)
|
||||
episodes?.add(newEpisode)
|
||||
}
|
||||
}
|
||||
@@ -147,7 +158,7 @@ class Podcast(
|
||||
// Used for FolderScanner local podcast item to get copy of Podcast excluding episodes
|
||||
@JsonIgnore
|
||||
override fun getLocalCopy(): Podcast {
|
||||
return Podcast(metadata as PodcastMetadata,coverPath,tags, mutableListOf(),autoDownloadEpisodes)
|
||||
return Podcast(metadata as PodcastMetadata,coverPath,tags, mutableListOf(),autoDownloadEpisodes, 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +171,8 @@ class Book(
|
||||
var chapters:List<BookChapter>?,
|
||||
var tracks:MutableList<AudioTrack>?,
|
||||
var size:Long?,
|
||||
var duration:Double?
|
||||
var duration:Double?,
|
||||
var numTracks:Int?
|
||||
) : MediaType(metadata, coverPath) {
|
||||
@JsonIgnore
|
||||
override fun getAudioTracks():List<AudioTrack> {
|
||||
@@ -209,7 +221,7 @@ class Book(
|
||||
|
||||
@JsonIgnore
|
||||
override fun getLocalCopy(): Book {
|
||||
return Book(metadata as BookMetadata,coverPath,tags, mutableListOf(),chapters,mutableListOf(),null,null)
|
||||
return Book(metadata as BookMetadata,coverPath,tags, mutableListOf(),chapters,mutableListOf(),null,null, 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +293,29 @@ data class PodcastEpisode(
|
||||
var duration:Double?,
|
||||
var size:Long?,
|
||||
var serverEpisodeId:String? // For local podcasts to match with server podcasts
|
||||
)
|
||||
) {
|
||||
@JsonIgnore
|
||||
fun getMediaMetadata(libraryItem:LibraryItemWrapper): MediaMetadataCompat {
|
||||
var coverUri:Uri = Uri.EMPTY
|
||||
val podcast = if(libraryItem is LocalLibraryItem) {
|
||||
coverUri = libraryItem.getCoverUri()
|
||||
libraryItem.media as Podcast
|
||||
} else {
|
||||
coverUri = (libraryItem as LibraryItem).getCoverUri()
|
||||
(libraryItem as LibraryItem).media as Podcast
|
||||
}
|
||||
|
||||
return MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, podcast.metadata.getAuthorDisplayName())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_AUTHOR, podcast.metadata.getAuthorDisplayName())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, coverUri.toString())
|
||||
|
||||
}.build()
|
||||
}
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
data class LibraryFile(
|
||||
@@ -312,7 +346,16 @@ data class Library(
|
||||
var folders:MutableList<Folder>,
|
||||
var icon:String,
|
||||
var mediaType:String
|
||||
)
|
||||
) {
|
||||
@JsonIgnore
|
||||
fun getMediaMetadata(): MediaMetadataCompat {
|
||||
return MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, name)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, name)
|
||||
}.build()
|
||||
}
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
data class Folder(
|
||||
@@ -356,7 +399,12 @@ data class BookChapter(
|
||||
var start:Double,
|
||||
var end:Double,
|
||||
var title:String?
|
||||
)
|
||||
) {
|
||||
@get:JsonIgnore
|
||||
val startMs get() = (start * 1000L).toLong()
|
||||
@get:JsonIgnore
|
||||
val endMs get() = (end * 1000L).toLong()
|
||||
}
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
data class MediaProgress(
|
||||
@@ -371,3 +419,9 @@ data class MediaProgress(
|
||||
var startedAt:Long,
|
||||
var finishedAt:Long?
|
||||
)
|
||||
|
||||
// Helper class
|
||||
data class LibraryItemWithEpisode(
|
||||
var libraryItemWrapper:LibraryItemWrapper,
|
||||
var episode:PodcastEpisode
|
||||
)
|
||||
|
||||
@@ -1,16 +1,27 @@
|
||||
package com.audiobookshelf.app.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.audiobookshelf.app.plugins.AbsDownloader
|
||||
import io.paperdb.Paper
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
class DbManager {
|
||||
val tag = "DbManager"
|
||||
|
||||
companion object {
|
||||
var isDbInitialized = false
|
||||
|
||||
fun initialize(ctx: Context) {
|
||||
if (isDbInitialized) return
|
||||
Paper.init(ctx)
|
||||
isDbInitialized = true
|
||||
Log.i("DbManager", "Initialized Paper db")
|
||||
}
|
||||
}
|
||||
|
||||
fun getDeviceData(): DeviceData {
|
||||
return Paper.book("device").read("data") ?: DeviceData(mutableListOf(), null, null)
|
||||
return Paper.book("device").read("data") ?: DeviceData(mutableListOf(), null, null, DeviceSettings.default())
|
||||
}
|
||||
fun saveDeviceData(deviceData:DeviceData) {
|
||||
Paper.book("device").write("data", deviceData)
|
||||
@@ -42,6 +53,20 @@ class DbManager {
|
||||
return Paper.book("localLibraryItems").read(localLibraryItemId)
|
||||
}
|
||||
|
||||
fun getLocalLibraryItemWithEpisode(podcastEpisodeId:String):LibraryItemWithEpisode? {
|
||||
var podcastEpisode:PodcastEpisode? = null
|
||||
val localLibraryItem = getLocalLibraryItems("podcast").find { localLibraryItem ->
|
||||
val podcast = localLibraryItem.media as Podcast
|
||||
podcastEpisode = podcast.episodes?.find { it.id == podcastEpisodeId }
|
||||
podcastEpisode != null
|
||||
}
|
||||
return if (localLibraryItem != null) {
|
||||
LibraryItemWithEpisode(localLibraryItem, podcastEpisode!!)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun removeLocalLibraryItem(localLibraryItemId:String) {
|
||||
Paper.book("localLibraryItems").delete(localLibraryItemId)
|
||||
}
|
||||
@@ -133,6 +158,7 @@ class DbManager {
|
||||
|
||||
// Check local files
|
||||
lli.localFiles = lli.localFiles.filter { localFile ->
|
||||
|
||||
val file = File(localFile.absolutePath)
|
||||
if (!file.exists()) {
|
||||
Log.d(tag, "cleanLocalLibraryItems: Local file ${localFile.absolutePath} was removed from library item ${lli.media.metadata.title}")
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo
|
||||
import java.util.*
|
||||
|
||||
data class ServerConnectionConfig(
|
||||
var id:String,
|
||||
@@ -13,13 +12,33 @@ data class ServerConnectionConfig(
|
||||
var address:String,
|
||||
var userId:String,
|
||||
var username:String,
|
||||
var token:String
|
||||
var token:String,
|
||||
var customHeaders:Map<String, String>?
|
||||
)
|
||||
|
||||
data class DeviceSettings(
|
||||
var disableAutoRewind:Boolean,
|
||||
var jumpBackwardsTime:Int,
|
||||
var jumpForwardTime:Int
|
||||
) {
|
||||
companion object {
|
||||
// Static method to get default device settings
|
||||
fun default():DeviceSettings {
|
||||
return DeviceSettings(false, 10, 10)
|
||||
}
|
||||
}
|
||||
|
||||
@get:JsonIgnore
|
||||
val jumpBackwardsTimeMs get() = jumpBackwardsTime * 1000L
|
||||
@get:JsonIgnore
|
||||
val jumpForwardTimeMs get() = jumpForwardTime * 1000L
|
||||
}
|
||||
|
||||
data class DeviceData(
|
||||
var serverConnectionConfigs:MutableList<ServerConnectionConfig>,
|
||||
var lastServerConnectionConfigId:String?,
|
||||
var currentLocalPlaybackSession:PlaybackSession? // Stored to open up where left off for local media
|
||||
var currentLocalPlaybackSession:PlaybackSession?, // Stored to open up where left off for local media
|
||||
var deviceSettings:DeviceSettings?
|
||||
) {
|
||||
@JsonIgnore
|
||||
fun getLastServerConnectionConfig():ServerConnectionConfig? {
|
||||
@@ -42,6 +61,8 @@ data class LocalFile(
|
||||
) {
|
||||
@JsonIgnore
|
||||
fun isAudioFile():Boolean {
|
||||
if (mimeType == "application/octet-stream") return true
|
||||
if (mimeType == "video/mp4") return true
|
||||
return mimeType?.startsWith("audio") == true
|
||||
}
|
||||
}
|
||||
@@ -64,3 +85,20 @@ data class LocalFolder(
|
||||
JsonSubTypes.Type(LocalLibraryItem::class)
|
||||
)
|
||||
open class LibraryItemWrapper()
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
data class DeviceInfo(
|
||||
var manufacturer:String,
|
||||
var model:String,
|
||||
var brand:String,
|
||||
var sdkVersion:Int,
|
||||
var clientVersion: String
|
||||
)
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
data class PlayItemRequestPayload(
|
||||
var mediaPlayer:String,
|
||||
var forceDirectPlay:Boolean,
|
||||
var forceTranscode:Boolean,
|
||||
var deviceInfo:DeviceInfo
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.audiobookshelf.app.data
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.support.v4.media.MediaMetadataCompat
|
||||
import android.util.Log
|
||||
@@ -44,7 +45,7 @@ data class LocalLibraryItem(
|
||||
@JsonIgnore
|
||||
fun getDuration():Double {
|
||||
var total = 0.0
|
||||
var audioTracks = media.getAudioTracks()
|
||||
val audioTracks = media.getAudioTracks()
|
||||
audioTracks.forEach{ total += it.duration }
|
||||
return total
|
||||
}
|
||||
@@ -94,15 +95,17 @@ data class LocalLibraryItem(
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun getMediaMetadata(): MediaMetadataCompat {
|
||||
fun getMediaMetadata(ctx: Context): MediaMetadataCompat {
|
||||
val coverUri = getCoverUri()
|
||||
|
||||
return MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, authorName)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, getCoverUri().toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, getCoverUri().toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ART_URI, getCoverUri().toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON_URI, coverUri.toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, coverUri.toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ART_URI, coverUri.toString())
|
||||
putString(MediaMetadataCompat.METADATA_KEY_AUTHOR, authorName)
|
||||
}.build()
|
||||
}
|
||||
|
||||
@@ -58,13 +58,13 @@ data class LocalMediaItem(
|
||||
|
||||
@JsonIgnore
|
||||
fun getLocalLibraryItem():LocalLibraryItem {
|
||||
var mediaMetadata = getMediaMetadata()
|
||||
val mediaMetadata = getMediaMetadata()
|
||||
if (mediaType == "book") {
|
||||
var chapters = getAudiobookChapters()
|
||||
var book = Book(mediaMetadata as BookMetadata, coverAbsolutePath, mutableListOf(), mutableListOf(), chapters,audioTracks,getTotalSize(),getDuration())
|
||||
val chapters = getAudiobookChapters()
|
||||
val book = Book(mediaMetadata as BookMetadata, coverAbsolutePath, mutableListOf(), mutableListOf(), chapters,audioTracks,getTotalSize(),getDuration(),audioTracks.size)
|
||||
return LocalLibraryItem(id, folderId, basePath,absolutePath, contentUrl, false,mediaType, book, localFiles, coverContentUrl, coverAbsolutePath,true,null,null,null,null)
|
||||
} else {
|
||||
var podcast = Podcast(mediaMetadata as PodcastMetadata, coverAbsolutePath, mutableListOf(), mutableListOf(), false)
|
||||
val podcast = Podcast(mediaMetadata as PodcastMetadata, coverAbsolutePath, mutableListOf(), mutableListOf(), false, 0)
|
||||
podcast.setAudioTracks(audioTracks) // Builds episodes from audio tracks
|
||||
return LocalLibraryItem(id, folderId, basePath,absolutePath, contentUrl, false, mediaType, podcast,localFiles,coverContentUrl, coverAbsolutePath, true, null,null,null,null)
|
||||
}
|
||||
|
||||
@@ -42,4 +42,15 @@ data class LocalMediaProgress(
|
||||
isFinished = playbackSession.progress >= 0.99
|
||||
finishedAt = if (isFinished) lastUpdate else null
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun updateFromServerMediaProgress(serverMediaProgress:MediaProgress) {
|
||||
isFinished = serverMediaProgress.isFinished
|
||||
progress = serverMediaProgress.progress
|
||||
currentTime = serverMediaProgress.currentTime
|
||||
duration = serverMediaProgress.duration
|
||||
lastUpdate = serverMediaProgress.lastUpdate
|
||||
finishedAt = serverMediaProgress.finishedAt
|
||||
startedAt = serverMediaProgress.startedAt
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,11 @@ package com.audiobookshelf.app.data
|
||||
|
||||
import android.net.Uri
|
||||
import android.support.v4.media.MediaMetadataCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.audiobookshelf.app.R
|
||||
import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.audiobookshelf.app.player.MediaProgressSyncData
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
|
||||
import com.google.android.exoplayer2.C
|
||||
import com.google.android.exoplayer2.MediaItem
|
||||
import com.google.android.exoplayer2.MediaMetadata
|
||||
import com.google.android.gms.cast.MediaInfo
|
||||
@@ -64,28 +62,36 @@ class PlaybackSession(
|
||||
val localMediaProgressId get() = if (episodeId.isNullOrEmpty()) localLibraryItemId else "$localLibraryItemId-$localEpisodeId"
|
||||
@get:JsonIgnore
|
||||
val progress get() = currentTime / getTotalDuration()
|
||||
@get:JsonIgnore
|
||||
val isLocalLibraryItemOnly get() = localLibraryItemId != "" && libraryItemId == null
|
||||
|
||||
@JsonIgnore
|
||||
fun getCurrentTrackIndex():Int {
|
||||
for (i in 0..(audioTracks.size - 1)) {
|
||||
var track = audioTracks[i]
|
||||
if (currentTimeMs >= track.startOffsetMs && (track.endOffsetMs) > currentTimeMs) {
|
||||
for (i in 0 until audioTracks.size) {
|
||||
val track = audioTracks[i]
|
||||
if (currentTimeMs >= track.startOffsetMs && (track.endOffsetMs > currentTimeMs)) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return audioTracks.size - 1
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun getChapterForTime(time:Long):BookChapter? {
|
||||
if (chapters.isEmpty()) return null
|
||||
return chapters.find { time >= it.startMs && it.endMs > time}
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun getCurrentTrackTimeMs():Long {
|
||||
var currentTrack = audioTracks[this.getCurrentTrackIndex()]
|
||||
var time = currentTime - currentTrack.startOffset
|
||||
val currentTrack = audioTracks[this.getCurrentTrackIndex()]
|
||||
val time = currentTime - currentTrack.startOffset
|
||||
return (time * 1000L).toLong()
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
fun getTrackStartOffsetMs(index:Int):Long {
|
||||
var currentTrack = audioTracks[index]
|
||||
val currentTrack = audioTracks[index]
|
||||
return (currentTrack.startOffset * 1000L).toLong()
|
||||
}
|
||||
|
||||
@@ -112,7 +118,7 @@ class PlaybackSession(
|
||||
|
||||
@JsonIgnore
|
||||
fun getMediaMetadataCompat(): MediaMetadataCompat {
|
||||
var metadataBuilder = MediaMetadataCompat.Builder()
|
||||
val metadataBuilder = MediaMetadataCompat.Builder()
|
||||
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, displayTitle)
|
||||
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, displayTitle)
|
||||
.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, displayAuthor)
|
||||
@@ -125,14 +131,14 @@ class PlaybackSession(
|
||||
|
||||
@JsonIgnore
|
||||
fun getExoMediaMetadata(audioTrack:AudioTrack): MediaMetadata {
|
||||
var metadataBuilder = MediaMetadata.Builder()
|
||||
val metadataBuilder = MediaMetadata.Builder()
|
||||
.setTitle(displayTitle)
|
||||
.setDisplayTitle(displayTitle)
|
||||
.setArtist(displayAuthor)
|
||||
.setAlbumArtist(displayAuthor)
|
||||
.setSubtitle(displayAuthor)
|
||||
|
||||
var contentUri = this.getContentUri(audioTrack)
|
||||
val contentUri = this.getContentUri(audioTrack)
|
||||
metadataBuilder.setMediaUri(contentUri)
|
||||
|
||||
return metadataBuilder.build()
|
||||
@@ -140,15 +146,15 @@ class PlaybackSession(
|
||||
|
||||
@JsonIgnore
|
||||
fun getMediaItems():List<MediaItem> {
|
||||
var mediaItems:MutableList<MediaItem> = mutableListOf()
|
||||
val mediaItems:MutableList<MediaItem> = mutableListOf()
|
||||
|
||||
for (audioTrack in audioTracks) {
|
||||
var mediaMetadata = this.getExoMediaMetadata(audioTrack)
|
||||
var mediaUri = this.getContentUri(audioTrack)
|
||||
var mimeType = audioTrack.mimeType
|
||||
val mediaMetadata = this.getExoMediaMetadata(audioTrack)
|
||||
val mediaUri = this.getContentUri(audioTrack)
|
||||
val mimeType = audioTrack.mimeType
|
||||
|
||||
var queueItem = getQueueItem(audioTrack) // Queue item used in exo player CastManager
|
||||
var mediaItem = MediaItem.Builder().setUri(mediaUri).setTag(queueItem).setMediaMetadata(mediaMetadata).setMimeType(mimeType).build()
|
||||
val queueItem = getQueueItem(audioTrack) // Queue item used in exo player CastManager
|
||||
val mediaItem = MediaItem.Builder().setUri(mediaUri).setTag(queueItem).setMediaMetadata(mediaMetadata).setMimeType(mimeType).build()
|
||||
mediaItems.add(mediaItem)
|
||||
}
|
||||
return mediaItems
|
||||
@@ -156,7 +162,7 @@ class PlaybackSession(
|
||||
|
||||
@JsonIgnore
|
||||
fun getCastMediaMetadata(audioTrack:AudioTrack):com.google.android.gms.cast.MediaMetadata {
|
||||
var castMetadata = com.google.android.gms.cast.MediaMetadata(com.google.android.gms.cast.MediaMetadata.MEDIA_TYPE_AUDIOBOOK_CHAPTER)
|
||||
val castMetadata = com.google.android.gms.cast.MediaMetadata(com.google.android.gms.cast.MediaMetadata.MEDIA_TYPE_AUDIOBOOK_CHAPTER)
|
||||
|
||||
coverPath?.let {
|
||||
castMetadata.addImage(WebImage(Uri.parse("$serverAddress/api/items/$libraryItemId/cover?token=${DeviceManager.token}")))
|
||||
@@ -171,11 +177,11 @@ class PlaybackSession(
|
||||
|
||||
@JsonIgnore
|
||||
fun getQueueItem(audioTrack:AudioTrack):MediaQueueItem {
|
||||
var castMetadata = getCastMediaMetadata(audioTrack)
|
||||
val castMetadata = getCastMediaMetadata(audioTrack)
|
||||
|
||||
var mediaUri = getContentUri(audioTrack)
|
||||
val mediaUri = getContentUri(audioTrack)
|
||||
|
||||
var mediaInfo = MediaInfo.Builder(mediaUri.toString()).apply {
|
||||
val mediaInfo = MediaInfo.Builder(mediaUri.toString()).apply {
|
||||
setContentUrl(mediaUri.toString())
|
||||
setContentType(audioTrack.mimeType)
|
||||
setMetadata(castMetadata)
|
||||
|
||||
@@ -24,6 +24,11 @@ object DeviceManager {
|
||||
}
|
||||
|
||||
fun getBase64Id(id:String):String {
|
||||
return android.util.Base64.encodeToString(id.toByteArray(), android.util.Base64.NO_WRAP)
|
||||
return android.util.Base64.encodeToString(id.toByteArray(), android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
fun getServerConnectionConfig(id:String?):ServerConnectionConfig? {
|
||||
if (id == null) return null
|
||||
return deviceData.serverConnectionConfigs.find { it.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +105,7 @@ class FolderScanner(var ctx: Context) {
|
||||
var coverContentUrl:String? = null
|
||||
var coverAbsolutePath:String? = null
|
||||
|
||||
val filesInFolder = itemFolder.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4"))
|
||||
val filesInFolder = itemFolder.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4", "application/octet-stream"))
|
||||
|
||||
val existingLocalFilesRemoved = existingLocalFiles.filter { elf ->
|
||||
filesInFolder.find { fif -> DeviceManager.getBase64Id(fif.id) == elf.id } == null // File was not found in media item folder
|
||||
@@ -157,11 +157,11 @@ class FolderScanner(var ctx: Context) {
|
||||
audioTrackToAdd = existingAudioTrack
|
||||
} else {
|
||||
// Create new audio track
|
||||
var track = AudioTrack(index, startOffset, audioProbeResult.duration, filename, localFile.contentUrl, mimeType, null, true, localFileId, audioProbeResult, null)
|
||||
val track = AudioTrack(index, startOffset, audioProbeResult?.duration ?: 0.0, filename, localFile.contentUrl, mimeType, null, true, localFileId, audioProbeResult, null)
|
||||
audioTrackToAdd = track
|
||||
}
|
||||
|
||||
startOffset += audioProbeResult.duration
|
||||
startOffset += audioProbeResult?.duration ?: 0.0
|
||||
isNewOrUpdated = true
|
||||
} else {
|
||||
audioTrackToAdd = existingAudioTrack
|
||||
@@ -250,7 +250,8 @@ class FolderScanner(var ctx: Context) {
|
||||
Log.d(tag, "scanDownloadItem starting for ${downloadItem.itemFolderPath} | ${df.uri} | Item Folder Id:$itemFolderId | LLI Id:$localLibraryItemId")
|
||||
|
||||
// Search for files in media item folder
|
||||
val filesFound = df.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4"))
|
||||
// m4b files showing as mimeType application/octet-stream on Android 10 and earlier see #154
|
||||
val filesFound = df.search(false, DocumentFileType.FILE, arrayOf("audio/*", "image/*", "video/mp4", "application/octet-stream"))
|
||||
Log.d(tag, "scanDownloadItem ${filesFound.size} files found in ${downloadItem.itemFolderPath}")
|
||||
|
||||
var localEpisodeId:String? = null
|
||||
@@ -288,7 +289,7 @@ class FolderScanner(var ctx: Context) {
|
||||
val audioProbeResult = probeAudioFile(localFile.absolutePath)
|
||||
|
||||
// Create new audio track
|
||||
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)
|
||||
val track = AudioTrack(audioTrackFromServer.index, audioTrackFromServer.startOffset, audioProbeResult?.duration ?: 0.0, localFile.filename ?: "", localFile.contentUrl, localFile.mimeType ?: "", null, true, localFileId, audioProbeResult, audioTrackFromServer.index)
|
||||
audioTracks.add(track)
|
||||
|
||||
Log.d(tag, "scanDownloadItem: Created Audio Track with index ${track.index} from local file ${localFile.absolutePath}")
|
||||
@@ -296,7 +297,7 @@ class FolderScanner(var ctx: Context) {
|
||||
// Add podcast episodes to library
|
||||
itemPart.episode?.let { podcastEpisode ->
|
||||
val podcast = localLibraryItem.media as Podcast
|
||||
var newEpisode = podcast.addEpisode(track, podcastEpisode)
|
||||
val 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}")
|
||||
}
|
||||
@@ -366,7 +367,7 @@ class FolderScanner(var ctx: Context) {
|
||||
}
|
||||
|
||||
fun scanLocalLibraryItem(localLibraryItem:LocalLibraryItem, forceAudioProbe:Boolean):LocalLibraryItemScanResult? {
|
||||
var df: DocumentFile? = DocumentFileCompat.fromUri(ctx, Uri.parse(localLibraryItem.contentUrl))
|
||||
val df: DocumentFile? = DocumentFileCompat.fromUri(ctx, Uri.parse(localLibraryItem.contentUrl))
|
||||
|
||||
if (df == null) {
|
||||
Log.e(tag, "Item Folder Doc File Invalid ${localLibraryItem.absolutePath}")
|
||||
@@ -377,7 +378,7 @@ class FolderScanner(var ctx: Context) {
|
||||
var wasUpdated = false
|
||||
|
||||
// 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", "application/octet-stream"))
|
||||
Log.d(tag, "scanLocalLibraryItem ${filesFound.size} files found in ${localLibraryItem.absolutePath}")
|
||||
|
||||
filesFound.forEach {
|
||||
@@ -388,10 +389,10 @@ class FolderScanner(var ctx: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
var existingAudioTracks = localLibraryItem.media.getAudioTracks()
|
||||
val existingAudioTracks = localLibraryItem.media.getAudioTracks()
|
||||
|
||||
// Remove any files no longer found in library item folder
|
||||
var existingLocalFileIds = localLibraryItem.localFiles.map { it.id }
|
||||
val existingLocalFileIds = localLibraryItem.localFiles.map { it.id }
|
||||
existingLocalFileIds.forEach { localFileId ->
|
||||
Log.d(tag, "Checking local file id is there $localFileId")
|
||||
if (filesFound.find { DeviceManager.getBase64Id(it.id) == localFileId } == null) {
|
||||
@@ -407,12 +408,12 @@ class FolderScanner(var ctx: Context) {
|
||||
}
|
||||
|
||||
filesFound.forEach { docFile ->
|
||||
var localFileId = DeviceManager.getBase64Id(docFile.id)
|
||||
var existingLocalFile = localLibraryItem.localFiles.find { it.id == localFileId }
|
||||
val localFileId = DeviceManager.getBase64Id(docFile.id)
|
||||
val existingLocalFile = localLibraryItem.localFiles.find { it.id == localFileId }
|
||||
|
||||
if (existingLocalFile == null || (existingLocalFile.isAudioFile() && forceAudioProbe)) {
|
||||
|
||||
var localFile = existingLocalFile ?: LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx), docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length())
|
||||
val localFile = existingLocalFile ?: LocalFile(localFileId,docFile.name,docFile.uri.toString(),docFile.getBasePath(ctx), docFile.getAbsolutePath(ctx),docFile.getSimplePath(ctx),docFile.mimeType,docFile.length())
|
||||
if (existingLocalFile == null) {
|
||||
localLibraryItem.localFiles.add(localFile)
|
||||
Log.d(tag, "scanLocalLibraryItem new file found ${localFile.filename}")
|
||||
@@ -420,22 +421,26 @@ class FolderScanner(var ctx: Context) {
|
||||
|
||||
if (localFile.isAudioFile()) {
|
||||
// TODO: Make asynchronous
|
||||
var audioProbeResult = probeAudioFile(localFile.absolutePath)
|
||||
val audioProbeResult = probeAudioFile(localFile.absolutePath)
|
||||
|
||||
var existingTrack = existingAudioTracks.find { audioTrack ->
|
||||
val existingTrack = existingAudioTracks.find { audioTrack ->
|
||||
audioTrack.localFileId == localFile.id
|
||||
}
|
||||
|
||||
if (existingTrack == null) {
|
||||
// Create new audio track
|
||||
var lastTrack = existingAudioTracks.lastOrNull()
|
||||
var startOffset = (lastTrack?.startOffset ?: 0.0) + (lastTrack?.duration ?: 0.0)
|
||||
var track = AudioTrack(existingAudioTracks.size, startOffset, audioProbeResult.duration, localFile.filename ?: "", localFile.contentUrl, localFile.mimeType ?: "", null, true, localFileId, audioProbeResult, null)
|
||||
val lastTrack = existingAudioTracks.lastOrNull()
|
||||
val startOffset = (lastTrack?.startOffset ?: 0.0) + (lastTrack?.duration ?: 0.0)
|
||||
val track = AudioTrack(existingAudioTracks.size, startOffset, audioProbeResult?.duration ?: 0.0, localFile.filename ?: "", localFile.contentUrl, localFile.mimeType ?: "", null, true, localFileId, audioProbeResult, null)
|
||||
localLibraryItem.media.addAudioTrack(track)
|
||||
Log.d(tag, "Added New Audio Track ${track.title}")
|
||||
wasUpdated = true
|
||||
} else {
|
||||
existingTrack.audioProbeResult = audioProbeResult
|
||||
// TODO: Update data found from probe
|
||||
|
||||
Log.d(tag, "Updated Audio Track Probe Data ${existingTrack.title}")
|
||||
|
||||
wasUpdated = true
|
||||
}
|
||||
} else { // Check if cover is empty
|
||||
@@ -458,12 +463,18 @@ class FolderScanner(var ctx: Context) {
|
||||
return LocalLibraryItemScanResult(wasUpdated, localLibraryItem)
|
||||
}
|
||||
|
||||
fun probeAudioFile(absolutePath:String):AudioProbeResult {
|
||||
var session = FFprobeKit.execute("-i \"${absolutePath}\" -print_format json -show_format -show_streams -select_streams a -show_chapters -loglevel quiet")
|
||||
fun probeAudioFile(absolutePath:String):AudioProbeResult? {
|
||||
val session = FFprobeKit.execute("-i \"${absolutePath}\" -print_format json -show_format -show_streams -select_streams a -show_chapters -loglevel quiet")
|
||||
Log.d(tag, "FFprobe output ${JSObject(session.output)}")
|
||||
|
||||
val audioProbeResult = jacksonMapper.readValue<AudioProbeResult>(session.output)
|
||||
Log.d(tag, "Probe Result DATA ${audioProbeResult.duration} | ${audioProbeResult.size} | ${audioProbeResult.title} | ${audioProbeResult.artist}")
|
||||
return audioProbeResult
|
||||
val probeObject = JSObject(session.output)
|
||||
if (!probeObject.has("streams")) { // Check if output is empty
|
||||
Log.d(tag, "probeAudioFile Probe audio file $absolutePath is empty")
|
||||
return null
|
||||
} else {
|
||||
val audioProbeResult = jacksonMapper.readValue<AudioProbeResult>(session.output)
|
||||
Log.d(tag, "Probe Result DATA ${audioProbeResult.duration} | ${audioProbeResult.size} | ${audioProbeResult.title} | ${audioProbeResult.artist}")
|
||||
return audioProbeResult
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,47 @@
|
||||
package com.audiobookshelf.app.media
|
||||
|
||||
import android.bluetooth.BluetoothClass
|
||||
import android.content.Context
|
||||
import android.support.v4.media.MediaBrowserCompat
|
||||
import android.util.Log
|
||||
import com.audiobookshelf.app.data.*
|
||||
import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.audiobookshelf.app.player.PlayerNotificationService
|
||||
import com.audiobookshelf.app.server.ApiHandler
|
||||
import java.util.*
|
||||
import io.paperdb.Paper
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
val tag = "MediaManager"
|
||||
|
||||
var serverLibraryItems = listOf<LibraryItem>()
|
||||
var selectedLibraryId = ""
|
||||
|
||||
var selectedLibraryItemWrapper:LibraryItemWrapper? = null
|
||||
var selectedPodcast:Podcast? = null
|
||||
var selectedLibraryItemId:String? = null
|
||||
var serverPodcastEpisodes = listOf<PodcastEpisode>()
|
||||
var serverLibraryCategories = listOf<LibraryCategory>()
|
||||
var serverLibraries = listOf<Library>()
|
||||
var serverConfigIdUsed:String? = null
|
||||
|
||||
fun initializeAndroidAuto() {
|
||||
Log.d(tag, "Android Auto started when MainActivity was never started - initializing Paper")
|
||||
Paper.init(ctx)
|
||||
fun getIsLibrary(id:String) : Boolean {
|
||||
return serverLibraries.find { it.id == id } != null
|
||||
}
|
||||
|
||||
fun checkResetServerItems() {
|
||||
// When opening android auto need to check if still connected to server
|
||||
// and reset any server data already set
|
||||
val serverConnConfig = if (DeviceManager.isConnectedToServer) DeviceManager.serverConnectionConfig else DeviceManager.deviceData.getLastServerConnectionConfig()
|
||||
|
||||
if (!DeviceManager.isConnectedToServer || !apiHandler.isOnline() || serverConnConfig == null || serverConnConfig.id !== serverConfigIdUsed) {
|
||||
serverPodcastEpisodes = listOf()
|
||||
serverLibraryCategories = listOf()
|
||||
serverLibraries = listOf()
|
||||
serverLibraryItems = listOf()
|
||||
selectedLibraryId = ""
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibraryCategories(libraryId:String, cb: (List<LibraryCategory>) -> Unit) {
|
||||
@@ -33,17 +55,75 @@ class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibraryItems(libraryId:String, cb: (List<LibraryItem>) -> Unit) {
|
||||
if (serverLibraryItems.isNotEmpty()) {
|
||||
fun loadLibraryItemsWithAudio(libraryId:String, cb: (List<LibraryItem>) -> Unit) {
|
||||
if (serverLibraryItems.isNotEmpty() && selectedLibraryId == libraryId) {
|
||||
cb(serverLibraryItems)
|
||||
} else {
|
||||
apiHandler.getLibraryItems(libraryId) { libraryItems ->
|
||||
serverLibraryItems = libraryItems
|
||||
cb(libraryItems)
|
||||
val libraryItemsWithAudio = libraryItems.filter { li -> li.checkHasTracks() }
|
||||
if (libraryItemsWithAudio.isNotEmpty()) selectedLibraryId = libraryId
|
||||
|
||||
serverLibraryItems = libraryItemsWithAudio
|
||||
cb(libraryItemsWithAudio)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibraryItem(libraryItemId:String, cb: (LibraryItemWrapper?) -> Unit) {
|
||||
if (libraryItemId.startsWith("local")) {
|
||||
cb(DeviceManager.dbManager.getLocalLibraryItem(libraryItemId))
|
||||
} else {
|
||||
Log.d(tag, "loadLibraryItem: $libraryItemId")
|
||||
apiHandler.getLibraryItem(libraryItemId) { libraryItem ->
|
||||
Log.d(tag, "loadLibraryItem: Got library item $libraryItem")
|
||||
cb(libraryItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadPodcastEpisodeMediaBrowserItems(libraryItemId:String, cb: (MutableList<MediaBrowserCompat.MediaItem>) -> Unit) {
|
||||
loadLibraryItem(libraryItemId) { libraryItemWrapper ->
|
||||
Log.d(tag, "Loaded Podcast library item $libraryItemWrapper")
|
||||
|
||||
selectedLibraryItemWrapper = libraryItemWrapper
|
||||
|
||||
libraryItemWrapper?.let {
|
||||
if (libraryItemWrapper is LocalLibraryItem) { // Local podcast episodes
|
||||
if (libraryItemWrapper.mediaType != "podcast" || libraryItemWrapper.media.getAudioTracks().isEmpty()) {
|
||||
serverPodcastEpisodes = listOf()
|
||||
cb(mutableListOf())
|
||||
} else {
|
||||
val podcast = libraryItemWrapper.media as Podcast
|
||||
serverPodcastEpisodes = podcast.episodes ?: listOf()
|
||||
selectedLibraryItemId = libraryItemWrapper.id
|
||||
selectedPodcast = podcast
|
||||
|
||||
val children = podcast.episodes?.map { podcastEpisode ->
|
||||
Log.d(tag, "Local Podcast Episode ${podcastEpisode.title} | ${podcastEpisode.id}")
|
||||
MediaBrowserCompat.MediaItem(podcastEpisode.getMediaMetadata(libraryItemWrapper).description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
|
||||
}
|
||||
children?.let { cb(children as MutableList) } ?: cb(mutableListOf())
|
||||
}
|
||||
} else if (libraryItemWrapper is LibraryItem) { // Server podcast episodes
|
||||
if (libraryItemWrapper.mediaType != "podcast" || libraryItemWrapper.media.getAudioTracks().isEmpty()) {
|
||||
serverPodcastEpisodes = listOf()
|
||||
cb(mutableListOf())
|
||||
} else {
|
||||
val podcast = libraryItemWrapper.media as Podcast
|
||||
serverPodcastEpisodes = podcast.episodes ?: listOf()
|
||||
selectedLibraryItemId = libraryItemWrapper.id
|
||||
selectedPodcast = podcast
|
||||
|
||||
val children = podcast.episodes?.map { podcastEpisode ->
|
||||
MediaBrowserCompat.MediaItem(podcastEpisode.getMediaMetadata(libraryItemWrapper).description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
|
||||
}
|
||||
children?.let { cb(children as MutableList) } ?: cb(mutableListOf())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadLibraries(cb: (List<Library>) -> Unit) {
|
||||
if (serverLibraries.isNotEmpty()) {
|
||||
cb(serverLibraries)
|
||||
@@ -55,11 +135,53 @@ class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun checkServerConnection(config:ServerConnectionConfig) : Boolean {
|
||||
var successfulPing = false
|
||||
suspendCoroutine<Boolean> { cont ->
|
||||
apiHandler.pingServer(config) {
|
||||
Log.d(tag, "checkServerConnection: Checked server conn for ${config.address} result = $it")
|
||||
successfulPing = it
|
||||
cont.resume(it)
|
||||
}
|
||||
}
|
||||
return successfulPing
|
||||
}
|
||||
|
||||
fun checkSetValidServerConnectionConfig(cb: (Boolean) -> Unit) = runBlocking {
|
||||
if (!apiHandler.isOnline()) cb(false)
|
||||
else {
|
||||
coroutineScope {
|
||||
var hasValidConn = false
|
||||
|
||||
// First check if the current selected config is pingable
|
||||
DeviceManager.serverConnectionConfig?.let {
|
||||
hasValidConn = checkServerConnection(it)
|
||||
Log.d(tag, "checkSetValidServerConnectionConfig: Current config ${DeviceManager.serverAddress} is pingable? $hasValidConn")
|
||||
}
|
||||
|
||||
if (!hasValidConn) {
|
||||
// Loop through available configs and check if can connect
|
||||
for (config: ServerConnectionConfig in DeviceManager.deviceData.serverConnectionConfigs) {
|
||||
val result = checkServerConnection(config)
|
||||
|
||||
if (result) {
|
||||
hasValidConn = true
|
||||
DeviceManager.serverConnectionConfig = config
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cb(hasValidConn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Load currently listening category for local items
|
||||
fun loadLocalCategory():List<LibraryCategory> {
|
||||
var localBooks = DeviceManager.dbManager.getLocalLibraryItems("book")
|
||||
var localPodcasts = DeviceManager.dbManager.getLocalLibraryItems("podcast")
|
||||
var cats = mutableListOf<LibraryCategory>()
|
||||
val localBooks = DeviceManager.dbManager.getLocalLibraryItems("book")
|
||||
val localPodcasts = DeviceManager.dbManager.getLocalLibraryItems("podcast")
|
||||
val cats = mutableListOf<LibraryCategory>()
|
||||
if (localBooks.isNotEmpty()) {
|
||||
cats.add(LibraryCategory("local-books", "Local Books", "book", localBooks, true))
|
||||
}
|
||||
@@ -69,45 +191,39 @@ class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
return cats
|
||||
}
|
||||
|
||||
fun loadAndroidAutoItems(libraryId:String, cb: (List<LibraryCategory>) -> Unit) {
|
||||
Log.d(tag, "Load android auto items for library id $libraryId")
|
||||
var cats = mutableListOf<LibraryCategory>()
|
||||
fun loadAndroidAutoItems(cb: (List<LibraryCategory>) -> Unit) {
|
||||
Log.d(tag, "Load android auto items")
|
||||
val cats = mutableListOf<LibraryCategory>()
|
||||
|
||||
var localCategories = loadLocalCategory()
|
||||
val localCategories = loadLocalCategory()
|
||||
cats.addAll(localCategories)
|
||||
|
||||
// Connected to server and has internet - load other cats
|
||||
if (apiHandler.isOnline() && (DeviceManager.isConnectedToServer || DeviceManager.hasLastServerConnectionConfig)) {
|
||||
if (!DeviceManager.isConnectedToServer) {
|
||||
DeviceManager.serverConnectionConfig = DeviceManager.deviceData.getLastServerConnectionConfig()
|
||||
Log.d(tag, "Not connected to server, set last server \"${DeviceManager.serverAddress}\"")
|
||||
}
|
||||
// Check if any valid server connection if not use locally downloaded books
|
||||
checkSetValidServerConnectionConfig { isConnected ->
|
||||
if (isConnected) {
|
||||
serverConfigIdUsed = DeviceManager.serverConnectionConfigId
|
||||
|
||||
loadLibraries { libraries ->
|
||||
var library = libraries.find { it.id == libraryId } ?: libraries[0]
|
||||
Log.d(tag, "Loading categories for library ${library.name} - ${library.id} - ${library.mediaType}")
|
||||
loadLibraries { libraries ->
|
||||
val library = libraries[0]
|
||||
Log.d(tag, "Loading categories for library ${library.name} - ${library.id} - ${library.mediaType}")
|
||||
|
||||
loadLibraryCategories(libraryId) { libraryCategories ->
|
||||
loadLibraryCategories(library.id) { libraryCategories ->
|
||||
|
||||
// Only using book or podcast library categories for now
|
||||
libraryCategories.forEach {
|
||||
Log.d(tag, "Found library category ${it.label} with type ${it.type}")
|
||||
if (it.type == library.mediaType) {
|
||||
Log.d(tag, "Using library category ${it.id}")
|
||||
cats.add(it)
|
||||
// Only using book or podcast library categories for now
|
||||
libraryCategories.forEach {
|
||||
// Log.d(tag, "Found library category ${it.label} with type ${it.type}")
|
||||
if (it.type == library.mediaType) {
|
||||
// Log.d(tag, "Using library category ${it.id}")
|
||||
cats.add(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadLibraryItems(libraryId) { libraryItems ->
|
||||
var mainCat = LibraryCategory("library", "Library", library.mediaType, libraryItems, false)
|
||||
cats.add(mainCat)
|
||||
|
||||
cb(cats)
|
||||
}
|
||||
}
|
||||
} else { // Not connected/no internet sent downloaded cats only
|
||||
cb(cats)
|
||||
}
|
||||
} else { // Not connected/no internet sent downloaded cats only
|
||||
cb(cats)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,11 +231,24 @@ class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
if (serverLibraryItems.isNotEmpty()) {
|
||||
return serverLibraryItems[0]
|
||||
} else {
|
||||
var localBooks = DeviceManager.dbManager.getLocalLibraryItems("book")
|
||||
val localBooks = DeviceManager.dbManager.getLocalLibraryItems("book")
|
||||
return if (localBooks.isNotEmpty()) return localBooks[0] else null
|
||||
}
|
||||
}
|
||||
|
||||
fun getPodcastWithEpisodeByEpisodeId(id:String) : LibraryItemWithEpisode? {
|
||||
if (id.startsWith("local")) {
|
||||
return DeviceManager.dbManager.getLocalLibraryItemWithEpisode(id)
|
||||
} else {
|
||||
val podcastEpisode = serverPodcastEpisodes.find { it.id == id }
|
||||
return if (podcastEpisode != null && selectedLibraryItemWrapper != null) {
|
||||
LibraryItemWithEpisode(selectedLibraryItemWrapper!!, podcastEpisode)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getById(id:String) : LibraryItemWrapper? {
|
||||
if (id.startsWith("local")) {
|
||||
return DeviceManager.dbManager.getLocalLibraryItem(id)
|
||||
@@ -135,14 +264,18 @@ class MediaManager(var apiHandler: ApiHandler, var ctx: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun play(libraryItemWrapper:LibraryItemWrapper, mediaPlayer:String, cb: (PlaybackSession) -> Unit) {
|
||||
fun play(libraryItemWrapper:LibraryItemWrapper, episode:PodcastEpisode?, playItemRequestPayload:PlayItemRequestPayload, cb: (PlaybackSession?) -> Unit) {
|
||||
if (libraryItemWrapper is LocalLibraryItem) {
|
||||
var localLibraryItem = libraryItemWrapper as LocalLibraryItem
|
||||
cb(localLibraryItem.getPlaybackSession(null))
|
||||
val localLibraryItem = libraryItemWrapper as LocalLibraryItem
|
||||
cb(localLibraryItem.getPlaybackSession(episode))
|
||||
} else {
|
||||
var libraryItem = libraryItemWrapper as LibraryItem
|
||||
apiHandler.playLibraryItem(libraryItem.id,"",false, mediaPlayer) {
|
||||
cb(it)
|
||||
val libraryItem = libraryItemWrapper as LibraryItem
|
||||
apiHandler.playLibraryItem(libraryItem.id,episode?.id ?: "",playItemRequestPayload) {
|
||||
if (it == null) {
|
||||
cb(null)
|
||||
} else {
|
||||
cb(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,6 @@ import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.support.v4.media.session.MediaControllerCompat
|
||||
import android.util.Log
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anggrayudi.storage.file.getAbsolutePath
|
||||
import com.anggrayudi.storage.file.toRawFile
|
||||
import com.audiobookshelf.app.R
|
||||
import com.bumptech.glide.Glide
|
||||
import com.bumptech.glide.load.engine.DiskCacheStrategy
|
||||
@@ -24,9 +21,6 @@ class AbMediaDescriptionAdapter constructor(private val controller: MediaControl
|
||||
var currentIconUri: Uri? = null
|
||||
var currentBitmap: Bitmap? = null
|
||||
|
||||
private val glideOptions = RequestOptions()
|
||||
.fallback(R.drawable.icon)
|
||||
.diskCacheStrategy(DiskCacheStrategy.DATA)
|
||||
private val serviceJob = SupervisorJob()
|
||||
private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)
|
||||
|
||||
@@ -62,26 +56,10 @@ class AbMediaDescriptionAdapter constructor(private val controller: MediaControl
|
||||
|
||||
private suspend fun resolveUriAsBitmap(uri: Uri): Bitmap? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
// Block on downloading artwork.
|
||||
val context = playerNotificationService.getContext()
|
||||
|
||||
// Fix attempt for #35 local cover crashing
|
||||
// Convert content uri to a file and pass to Glide
|
||||
var urival:Any = uri
|
||||
if (uri.toString().startsWith("content:")) {
|
||||
val imageDocFile = DocumentFile.fromSingleUri(context, uri)
|
||||
Log.d(tag, "Converting local content url $uri to file with path ${imageDocFile?.getAbsolutePath(context)}")
|
||||
val file = imageDocFile?.toRawFile(context)
|
||||
file?.let {
|
||||
Log.d(tag, "Using local file image instead of content uri ${it.absolutePath}")
|
||||
urival = it
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Glide.with(context).applyDefaultRequestOptions(glideOptions)
|
||||
Glide.with(playerNotificationService)
|
||||
.asBitmap()
|
||||
.load(urival)
|
||||
.load(uri)
|
||||
.placeholder(R.drawable.icon)
|
||||
.error(R.drawable.icon)
|
||||
.submit(NOTIFICATION_LARGE_ICON_SIZE, NOTIFICATION_LARGE_ICON_SIZE)
|
||||
@@ -89,7 +67,7 @@ class AbMediaDescriptionAdapter constructor(private val controller: MediaControl
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
|
||||
Glide.with(context).applyDefaultRequestOptions(glideOptions)
|
||||
Glide.with(playerNotificationService)
|
||||
.asBitmap()
|
||||
.load(Uri.parse("android.resource://com.audiobookshelf.app/" + R.drawable.icon))
|
||||
.submit(NOTIFICATION_LARGE_ICON_SIZE, NOTIFICATION_LARGE_ICON_SIZE)
|
||||
|
||||
@@ -7,14 +7,15 @@ import android.support.v4.media.MediaMetadataCompat
|
||||
import android.util.Log
|
||||
import androidx.annotation.AnyRes
|
||||
import com.audiobookshelf.app.R
|
||||
import com.audiobookshelf.app.data.Library
|
||||
import com.audiobookshelf.app.data.LibraryCategory
|
||||
import com.audiobookshelf.app.data.LibraryItem
|
||||
import com.audiobookshelf.app.data.LocalLibraryItem
|
||||
|
||||
|
||||
class BrowseTree(
|
||||
val context: Context,
|
||||
libraryCategories: List<LibraryCategory>
|
||||
libraryCategories: List<LibraryCategory>,
|
||||
libraries: List<Library>
|
||||
) {
|
||||
private val mediaIdToChildren = mutableMapOf<String, MutableList<MediaMetadataCompat>>()
|
||||
|
||||
@@ -41,22 +42,22 @@ class BrowseTree(
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, getUriToDrawable(context, R.drawable.exo_icon_localaudio).toString())
|
||||
}.build()
|
||||
|
||||
val allMetadata = MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, ALL_ROOT)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Library Items")
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, getUriToDrawable(context, R.drawable.exo_icon_books).toString())
|
||||
}.build()
|
||||
|
||||
val downloadsMetadata = MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, DOWNLOADS_ROOT)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Downloads")
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, getUriToDrawable(context, R.drawable.exo_icon_downloaddone).toString())
|
||||
}.build()
|
||||
|
||||
val librariesMetadata = MediaMetadataCompat.Builder().apply {
|
||||
putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, LIBRARIES_ROOT)
|
||||
putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Libraries")
|
||||
putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, getUriToDrawable(context, R.drawable.icon_library_folder).toString())
|
||||
}.build()
|
||||
|
||||
// Server continue Listening cat
|
||||
libraryCategories.find { it.id == "continue-listening" }?.let { continueListeningCategory ->
|
||||
var continueListeningMediaMetadata = continueListeningCategory.entities.map { liw ->
|
||||
var libraryItem = liw as LibraryItem
|
||||
val continueListeningMediaMetadata = continueListeningCategory.entities.map { liw ->
|
||||
val libraryItem = liw as LibraryItem
|
||||
libraryItem.getMediaMetadata()
|
||||
}
|
||||
if (continueListeningMediaMetadata.isNotEmpty()) {
|
||||
@@ -69,30 +70,32 @@ class BrowseTree(
|
||||
}
|
||||
}
|
||||
|
||||
rootList += allMetadata
|
||||
rootList += downloadsMetadata
|
||||
if (libraries.isNotEmpty()) {
|
||||
rootList += librariesMetadata
|
||||
|
||||
// Server library cat
|
||||
libraryCategories.find { it.id == "library" }?.let { libraryCategory ->
|
||||
var libraryMediaMetadata = libraryCategory.entities.map { libc ->
|
||||
var libraryItem = libc as LibraryItem
|
||||
libraryItem.getMediaMetadata()
|
||||
}
|
||||
libraryMediaMetadata.forEach {
|
||||
val children = mediaIdToChildren[ALL_ROOT] ?: mutableListOf()
|
||||
children += it
|
||||
mediaIdToChildren[ALL_ROOT] = children
|
||||
libraries.forEach { library ->
|
||||
val libraryMediaMetadata = library.getMediaMetadata()
|
||||
val children = mediaIdToChildren[LIBRARIES_ROOT] ?: mutableListOf()
|
||||
children += libraryMediaMetadata
|
||||
mediaIdToChildren[LIBRARIES_ROOT] = children
|
||||
}
|
||||
}
|
||||
|
||||
rootList += downloadsMetadata
|
||||
libraryCategories.find { it.id == "local-books" }?.let { localBooksCat ->
|
||||
var localMediaMetadata = localBooksCat.entities.map { libc ->
|
||||
var libraryItem = libc as LocalLibraryItem
|
||||
libraryItem.getMediaMetadata()
|
||||
localBooksCat.entities.forEach { libc ->
|
||||
val libraryItem = libc as LocalLibraryItem
|
||||
val children = mediaIdToChildren[DOWNLOADS_ROOT] ?: mutableListOf()
|
||||
children += libraryItem.getMediaMetadata(context)
|
||||
mediaIdToChildren[DOWNLOADS_ROOT] = children
|
||||
}
|
||||
localMediaMetadata.forEach {
|
||||
}
|
||||
|
||||
libraryCategories.find { it.id == "local-podcasts" }?.let { localPodcastsCat ->
|
||||
localPodcastsCat.entities.forEach { libc ->
|
||||
val libraryItem = libc as LocalLibraryItem
|
||||
val children = mediaIdToChildren[DOWNLOADS_ROOT] ?: mutableListOf()
|
||||
children += it
|
||||
children += libraryItem.getMediaMetadata(context)
|
||||
mediaIdToChildren[DOWNLOADS_ROOT] = children
|
||||
}
|
||||
}
|
||||
@@ -104,6 +107,6 @@ class BrowseTree(
|
||||
}
|
||||
|
||||
const val AUTO_BROWSE_ROOT = "/"
|
||||
const val ALL_ROOT = "__ALL__"
|
||||
const val CONTINUE_ROOT = "__CONTINUE__"
|
||||
const val DOWNLOADS_ROOT = "__DOWNLOADS__"
|
||||
const val LIBRARIES_ROOT = "__LIBRARIES__"
|
||||
|
||||
@@ -88,7 +88,7 @@ class CastPlayer(var castContext: CastContext) : BasePlayer() {
|
||||
private var currentMediaItemIndex = 0
|
||||
private var pendingMediaItemRemovalPosition:PositionInfo? = null
|
||||
private var pendingSeekCount = 0
|
||||
private var pendingSeekWindowIndex = 0
|
||||
private var pendingSeekWindowIndex = C.INDEX_UNSET
|
||||
private var pendingSeekPositionMs = 0L
|
||||
|
||||
init {
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import com.audiobookshelf.app.data.LocalMediaProgress
|
||||
import com.audiobookshelf.app.data.MediaProgress
|
||||
import com.audiobookshelf.app.data.PlaybackSession
|
||||
import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.audiobookshelf.app.server.ApiHandler
|
||||
@@ -17,15 +18,14 @@ data class MediaProgressSyncData(
|
||||
var currentTime:Double // seconds
|
||||
)
|
||||
|
||||
class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, apiHandler: ApiHandler) {
|
||||
class MediaProgressSyncer(val playerNotificationService:PlayerNotificationService, private val apiHandler: ApiHandler) {
|
||||
private val tag = "MediaProgressSync"
|
||||
private val playerNotificationService:PlayerNotificationService = playerNotificationService
|
||||
private val apiHandler = apiHandler
|
||||
|
||||
private var listeningTimerTask: TimerTask? = null
|
||||
var listeningTimerRunning:Boolean = false
|
||||
|
||||
private var lastSyncTime:Long = 0
|
||||
private var failedSyncs:Int = 0
|
||||
|
||||
var currentPlaybackSession: PlaybackSession? = null // copy of pb session currently syncing
|
||||
var currentLocalMediaProgress: LocalMediaProgress? = null
|
||||
@@ -43,6 +43,7 @@ class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, a
|
||||
currentLocalMediaProgress = null
|
||||
listeningTimerTask?.cancel()
|
||||
lastSyncTime = 0L
|
||||
failedSyncs = 0
|
||||
} else {
|
||||
return
|
||||
}
|
||||
@@ -54,7 +55,7 @@ class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, a
|
||||
listeningTimerTask = Timer("ListeningTimer", false).schedule(0L, 5000L) {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
if (playerNotificationService.currentPlayer.isPlaying) {
|
||||
var currentTime = playerNotificationService.getCurrentTimeSeconds()
|
||||
val currentTime = playerNotificationService.getCurrentTimeSeconds()
|
||||
sync(currentTime)
|
||||
}
|
||||
}
|
||||
@@ -65,20 +66,30 @@ class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, a
|
||||
if (!listeningTimerRunning) return
|
||||
Log.d(tag, "stop: Stopping listening for $currentDisplayTitle")
|
||||
|
||||
var currentTime = playerNotificationService.getCurrentTimeSeconds()
|
||||
val currentTime = playerNotificationService.getCurrentTimeSeconds()
|
||||
sync(currentTime)
|
||||
reset()
|
||||
}
|
||||
|
||||
fun syncFromServerProgress(mediaProgress: MediaProgress) {
|
||||
currentPlaybackSession?.let {
|
||||
it.updatedAt = mediaProgress.lastUpdate
|
||||
it.currentTime = mediaProgress.currentTime
|
||||
|
||||
DeviceManager.dbManager.saveLocalPlaybackSession(it)
|
||||
saveLocalProgress(it)
|
||||
}
|
||||
}
|
||||
|
||||
fun sync(currentTime:Double) {
|
||||
var diffSinceLastSync = System.currentTimeMillis() - lastSyncTime
|
||||
val diffSinceLastSync = System.currentTimeMillis() - lastSyncTime
|
||||
if (diffSinceLastSync < 1000L) {
|
||||
return
|
||||
}
|
||||
var listeningTimeToAdd = diffSinceLastSync / 1000L
|
||||
val listeningTimeToAdd = diffSinceLastSync / 1000L
|
||||
lastSyncTime = System.currentTimeMillis()
|
||||
|
||||
var syncData = MediaProgressSyncData(listeningTimeToAdd,currentPlaybackDuration,currentTime)
|
||||
val syncData = MediaProgressSyncData(listeningTimeToAdd,currentPlaybackDuration,currentTime)
|
||||
|
||||
currentPlaybackSession?.syncData(syncData)
|
||||
if (currentIsLocal) {
|
||||
@@ -87,23 +98,39 @@ class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, a
|
||||
DeviceManager.dbManager.saveLocalPlaybackSession(it)
|
||||
saveLocalProgress(it)
|
||||
|
||||
// Send sync to server also if connected to this server and local item belongs to this server
|
||||
if (it.serverConnectionConfigId != null && DeviceManager.serverConnectionConfig?.id == it.serverConnectionConfigId) {
|
||||
apiHandler.sendLocalProgressSync(it) {
|
||||
Log.d(tag, "Local progress sync data sent to server $currentDisplayTitle for time $currentTime")
|
||||
// Local library item is linked to a server library item
|
||||
if (!it.libraryItemId.isNullOrEmpty()) {
|
||||
// Send sync to server also if connected to this server and local item belongs to this server
|
||||
if (it.serverConnectionConfigId != null && DeviceManager.serverConnectionConfig?.id == it.serverConnectionConfigId) {
|
||||
apiHandler.sendLocalProgressSync(it) {
|
||||
Log.d(
|
||||
tag,
|
||||
"Local progress sync data sent to server $currentDisplayTitle for time $currentTime"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
apiHandler.sendProgressSync(currentSessionId, syncData) {
|
||||
Log.d(tag, "Progress sync data sent to server $currentDisplayTitle for time $currentTime")
|
||||
if (it) {
|
||||
Log.d(tag, "Progress sync data sent to server $currentDisplayTitle for time $currentTime")
|
||||
failedSyncs = 0
|
||||
} else {
|
||||
failedSyncs++
|
||||
if (failedSyncs == 2) {
|
||||
playerNotificationService.alertSyncFailing() // Show alert in client
|
||||
failedSyncs = 0
|
||||
}
|
||||
Log.d(tag, "Progress sync failed ($failedSyncs) to send to server $currentDisplayTitle for time $currentTime")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveLocalProgress(playbackSession:PlaybackSession) {
|
||||
if (currentLocalMediaProgress == null) {
|
||||
var mediaProgress = DeviceManager.dbManager.getLocalMediaProgress(playbackSession.localMediaProgressId)
|
||||
val mediaProgress = DeviceManager.dbManager.getLocalMediaProgress(playbackSession.localMediaProgressId)
|
||||
if (mediaProgress == null) {
|
||||
currentLocalMediaProgress = playbackSession.getNewLocalMediaProgress()
|
||||
} else {
|
||||
@@ -126,5 +153,6 @@ class MediaProgressSyncer(playerNotificationService:PlayerNotificationService, a
|
||||
currentPlaybackSession = null
|
||||
currentLocalMediaProgress = null
|
||||
lastSyncTime = 0L
|
||||
failedSyncs = 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,8 @@ import android.os.Message
|
||||
import android.support.v4.media.session.MediaSessionCompat
|
||||
import android.util.Log
|
||||
import android.view.KeyEvent
|
||||
import com.audiobookshelf.app.data.LibraryItem
|
||||
import com.audiobookshelf.app.data.LibraryItemWrapper
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.launch
|
||||
import com.audiobookshelf.app.data.PodcastEpisode
|
||||
import java.util.*
|
||||
import kotlin.concurrent.schedule
|
||||
|
||||
@@ -27,10 +24,13 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
override fun onPrepare() {
|
||||
Log.d(tag, "ON PREPARE MEDIA SESSION COMPAT")
|
||||
playerNotificationService.mediaManager.getFirstItem()?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Log.d(tag, "About to prepare player with ${it.displayTitle}")
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,true,null)
|
||||
playerNotificationService.mediaManager.play(li, null, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,true,null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,13 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
override fun onPlayFromSearch(query: String?, extras: Bundle?) {
|
||||
Log.d(tag, "ON PLAY FROM SEARCH $query")
|
||||
playerNotificationService.mediaManager.getFromSearch(query)?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Log.d(tag, "About to prepare player with ${it.displayTitle}")
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,true,null)
|
||||
playerNotificationService.mediaManager.play(li, null, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it, true, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,17 +93,30 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) {
|
||||
Log.d(tag, "ON PLAY FROM MEDIA ID $mediaId")
|
||||
var libraryItemWrapper: LibraryItemWrapper? = null
|
||||
var podcastEpisode: PodcastEpisode? = null
|
||||
|
||||
if (mediaId.isNullOrEmpty()) {
|
||||
libraryItemWrapper = playerNotificationService.mediaManager.getFirstItem()
|
||||
} else if (mediaId.startsWith("ep_") || mediaId.startsWith("local_ep_")) { // Playing podcast episode
|
||||
val libraryItemWithEpisode = playerNotificationService.mediaManager.getPodcastWithEpisodeByEpisodeId(mediaId)
|
||||
libraryItemWrapper = libraryItemWithEpisode?.libraryItemWrapper
|
||||
podcastEpisode = libraryItemWithEpisode?.episode
|
||||
} else {
|
||||
libraryItemWrapper = playerNotificationService.mediaManager.getById(mediaId)
|
||||
|
||||
if (libraryItemWrapper == null) {
|
||||
Log.e(tag, "onPlayFromMediaId: Media item not found $mediaId")
|
||||
}
|
||||
}
|
||||
|
||||
libraryItemWrapper?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Log.d(tag, "About to prepare player with ${it.displayTitle}")
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,true,null)
|
||||
playerNotificationService.mediaManager.play(li, podcastEpisode, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it, true, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,10 +128,13 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
|
||||
fun handleCallMediaButton(intent: Intent): Boolean {
|
||||
if(Intent.ACTION_MEDIA_BUTTON == intent.action) {
|
||||
var keyEvent = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
|
||||
if (keyEvent?.getAction() == KeyEvent.ACTION_UP) {
|
||||
when (keyEvent?.getKeyCode()) {
|
||||
val keyEvent = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
|
||||
|
||||
if (keyEvent?.action == KeyEvent.ACTION_UP) {
|
||||
Log.d(tag, "handleCallMediaButton: key action_up for ${keyEvent.keyCode}")
|
||||
when (keyEvent.keyCode) {
|
||||
KeyEvent.KEYCODE_HEADSETHOOK -> {
|
||||
Log.d(tag, "handleCallMediaButton: Headset Hook")
|
||||
if (0 == mediaButtonClickCount) {
|
||||
if (playerNotificationService.mPlayer.isPlaying)
|
||||
playerNotificationService.pause()
|
||||
@@ -125,6 +144,7 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
handleMediaButtonClickCount()
|
||||
}
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY -> {
|
||||
Log.d(tag, "handleCallMediaButton: Media Play")
|
||||
if (0 == mediaButtonClickCount) {
|
||||
playerNotificationService.play()
|
||||
playerNotificationService.sleepTimerManager.checkShouldExtendSleepTimer()
|
||||
@@ -132,6 +152,7 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
handleMediaButtonClickCount()
|
||||
}
|
||||
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
|
||||
Log.d(tag, "handleCallMediaButton: Media Pause")
|
||||
if (0 == mediaButtonClickCount) playerNotificationService.pause()
|
||||
handleMediaButtonClickCount()
|
||||
}
|
||||
@@ -145,6 +166,7 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
playerNotificationService.closePlayback()
|
||||
}
|
||||
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
|
||||
Log.d(tag, "handleCallMediaButton: Media Play/Pause")
|
||||
if (playerNotificationService.mPlayer.isPlaying) {
|
||||
if (0 == mediaButtonClickCount) playerNotificationService.pause()
|
||||
handleMediaButtonClickCount()
|
||||
@@ -157,7 +179,7 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
Log.d(tag, "KeyCode:${keyEvent.getKeyCode()}")
|
||||
Log.d(tag, "KeyCode:${keyEvent.keyCode}")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -166,7 +188,7 @@ class MediaSessionCallback(var playerNotificationService:PlayerNotificationServi
|
||||
return true
|
||||
}
|
||||
|
||||
fun handleMediaButtonClickCount() {
|
||||
private fun handleMediaButtonClickCount() {
|
||||
mediaButtonClickCount++
|
||||
if (1 == mediaButtonClickCount) {
|
||||
Timer().schedule(mediaButtonClickTimeout) {
|
||||
|
||||
@@ -7,8 +7,8 @@ import android.os.Looper
|
||||
import android.os.ResultReceiver
|
||||
import android.support.v4.media.session.PlaybackStateCompat
|
||||
import android.util.Log
|
||||
import com.audiobookshelf.app.data.LibraryItem
|
||||
import com.audiobookshelf.app.data.LibraryItemWrapper
|
||||
import com.audiobookshelf.app.data.PodcastEpisode
|
||||
import com.google.android.exoplayer2.Player
|
||||
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
|
||||
|
||||
@@ -30,9 +30,13 @@ class MediaSessionPlaybackPreparer(var playerNotificationService:PlayerNotificat
|
||||
override fun onPrepare(playWhenReady: Boolean) {
|
||||
Log.d(tag, "ON PREPARE $playWhenReady")
|
||||
playerNotificationService.mediaManager.getFirstItem()?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,playWhenReady,null)
|
||||
playerNotificationService.mediaManager.play(li, null, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it, playWhenReady, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,12 +45,25 @@ class MediaSessionPlaybackPreparer(var playerNotificationService:PlayerNotificat
|
||||
override fun onPrepareFromMediaId(mediaId: String, playWhenReady: Boolean, extras: Bundle?) {
|
||||
Log.d(tag, "ON PREPARE FROM MEDIA ID $mediaId $playWhenReady")
|
||||
|
||||
var libraryItemWrapper: LibraryItemWrapper? = playerNotificationService.mediaManager.getById(mediaId)
|
||||
var libraryItemWrapper: LibraryItemWrapper? = null
|
||||
var podcastEpisode: PodcastEpisode? = null
|
||||
|
||||
if (mediaId.startsWith("ep_") || mediaId.startsWith("local_ep_")) { // Playing podcast episode
|
||||
val libraryItemWithEpisode = playerNotificationService.mediaManager.getPodcastWithEpisodeByEpisodeId(mediaId)
|
||||
libraryItemWrapper = libraryItemWithEpisode?.libraryItemWrapper
|
||||
podcastEpisode = libraryItemWithEpisode?.episode
|
||||
} else {
|
||||
libraryItemWrapper = playerNotificationService.mediaManager.getById(mediaId)
|
||||
}
|
||||
|
||||
libraryItemWrapper?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Log.d(tag, "About to prepare player with ${it.displayTitle}")
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,playWhenReady,null)
|
||||
playerNotificationService.mediaManager.play(li, podcastEpisode, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it, playWhenReady, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,10 +72,13 @@ class MediaSessionPlaybackPreparer(var playerNotificationService:PlayerNotificat
|
||||
override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) {
|
||||
Log.d(tag, "ON PREPARE FROM SEARCH $query")
|
||||
playerNotificationService.mediaManager.getFromSearch(query)?.let { li ->
|
||||
playerNotificationService.mediaManager.play(li, playerNotificationService.getMediaPlayer()) {
|
||||
Log.d(tag, "About to prepare player with ${it.displayTitle}")
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it,playWhenReady,null)
|
||||
playerNotificationService.mediaManager.play(li, null, playerNotificationService.getPlayItemRequestPayload(false)) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to play library item")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
playerNotificationService.preparePlayer(it, playWhenReady, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@ package com.audiobookshelf.app.player
|
||||
|
||||
import android.util.Log
|
||||
import com.audiobookshelf.app.data.PlayerState
|
||||
import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.google.android.exoplayer2.PlaybackException
|
||||
import com.google.android.exoplayer2.Player
|
||||
|
||||
const val PAUSE_LEN_BEFORE_RECHECK = 30000 // 30 seconds
|
||||
|
||||
class PlayerListener(var playerNotificationService:PlayerNotificationService) : Player.Listener {
|
||||
var tag = "PlayerListener"
|
||||
|
||||
@@ -15,13 +18,13 @@ class PlayerListener(var playerNotificationService:PlayerNotificationService) :
|
||||
private var onSeekBack: Boolean = false
|
||||
|
||||
override fun onPlayerError(error: PlaybackException) {
|
||||
var errorMessage = error.message ?: "Unknown Error"
|
||||
val errorMessage = error.message ?: "Unknown Error"
|
||||
Log.e(tag, "onPlayerError $errorMessage")
|
||||
playerNotificationService.handlePlayerPlaybackError(errorMessage) // If was direct playing session, fallback to transcode
|
||||
}
|
||||
|
||||
override fun onEvents(player: Player, events: Player.Events) {
|
||||
Log.d(tag, "onEvents ${player.deviceInfo} | ${playerNotificationService.getMediaPlayer()} | ${events.size()}")
|
||||
Log.d(tag, "onEvents ${playerNotificationService.getMediaPlayer()} | ${events.size()}")
|
||||
|
||||
if (events.contains(Player.EVENT_POSITION_DISCONTINUITY)) {
|
||||
Log.d(tag, "EVENT_POSITION_DISCONTINUITY")
|
||||
@@ -67,20 +70,33 @@ class PlayerListener(var playerNotificationService:PlayerNotificationService) :
|
||||
|
||||
if (player.isPlaying) {
|
||||
Log.d(tag, "SeekBackTime: Player is playing")
|
||||
if (lastPauseTime > 0) {
|
||||
if (lastPauseTime > 0 && DeviceManager.deviceData.deviceSettings?.disableAutoRewind != true) {
|
||||
if (onSeekBack) onSeekBack = false
|
||||
else {
|
||||
Log.d(tag, "SeekBackTime: playing started now set seek back time $lastPauseTime")
|
||||
var backTime = calcPauseSeekBackTime()
|
||||
if (backTime > 0) {
|
||||
if (backTime >= playerNotificationService.getCurrentTime()) backTime = playerNotificationService.getCurrentTime() - 500
|
||||
// Current chapter is used so that seek back does not go back to the previous chapter
|
||||
val currentChapter = playerNotificationService.getCurrentBookChapter()
|
||||
val minSeekBackTime = currentChapter?.startMs ?: 0
|
||||
|
||||
val currentTime = playerNotificationService.getCurrentTime()
|
||||
val newTime = currentTime - backTime
|
||||
if (newTime < minSeekBackTime) {
|
||||
backTime = currentTime - minSeekBackTime
|
||||
}
|
||||
Log.d(tag, "SeekBackTime $backTime")
|
||||
onSeekBack = true
|
||||
playerNotificationService.seekBackward(backTime)
|
||||
} else {
|
||||
Log.d(tag, "SeekBackTime: back time is 0")
|
||||
}
|
||||
}
|
||||
|
||||
// Check if playback session still exists or sync media progress if updated
|
||||
val pauseLength: Long = System.currentTimeMillis() - lastPauseTime
|
||||
if (pauseLength > PAUSE_LEN_BEFORE_RECHECK) {
|
||||
val shouldCarryOn = playerNotificationService.checkCurrentSessionProgress()
|
||||
if (!shouldCarryOn) return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log.d(tag, "SeekBackTime: Player not playing set last pause time")
|
||||
@@ -90,6 +106,7 @@ class PlayerListener(var playerNotificationService:PlayerNotificationService) :
|
||||
// Start/stop progress sync interval
|
||||
Log.d(tag, "Playing ${playerNotificationService.getCurrentBookTitle()}")
|
||||
if (player.isPlaying) {
|
||||
player.volume = 1F // Volume on sleep timer might have decreased this
|
||||
playerNotificationService.mediaProgressSyncer.start()
|
||||
} else {
|
||||
playerNotificationService.mediaProgressSyncer.stop()
|
||||
@@ -101,10 +118,11 @@ class PlayerListener(var playerNotificationService:PlayerNotificationService) :
|
||||
|
||||
private fun calcPauseSeekBackTime() : Long {
|
||||
if (lastPauseTime <= 0) return 0
|
||||
var time: Long = System.currentTimeMillis() - lastPauseTime
|
||||
var seekback: Long
|
||||
if (time < 3000) seekback = 0
|
||||
else if (time < 300000) seekback = 10000 // 3s to 5m = jump back 10s
|
||||
val time: Long = System.currentTimeMillis() - lastPauseTime
|
||||
val seekback: Long
|
||||
if (time < 10000) seekback = 0 // 10s or less = no seekback
|
||||
else if (time < 60000) seekback = 3000 // 10s to 1m = jump back 3s
|
||||
else if (time < 300000) seekback = 10000 // 1m to 5m = jump back 10s
|
||||
else if (time < 1800000) seekback = 20000 // 5m to 30m = jump back 20s
|
||||
else seekback = 29500 // 30m and up = jump back 30s
|
||||
return seekback
|
||||
|
||||
@@ -14,6 +14,7 @@ class PlayerNotificationListener(var playerNotificationService:PlayerNotificatio
|
||||
|
||||
// Start foreground service
|
||||
Log.d(tag, "Notification Posted $notificationId - Start Foreground | $notification")
|
||||
PlayerNotificationService.isClosed = false
|
||||
playerNotificationService.startForeground(notificationId, notification)
|
||||
}
|
||||
|
||||
@@ -26,6 +27,12 @@ class PlayerNotificationListener(var playerNotificationService:PlayerNotificatio
|
||||
playerNotificationService.stopSelf()
|
||||
} else {
|
||||
Log.d(tag, "onNotificationCancelled not dismissed by user")
|
||||
|
||||
// When stop button is pressed on the notification I guess it isn't considered "dismissedByUser" so we need to close playback ourselves
|
||||
if (!PlayerNotificationService.isClosed) {
|
||||
Log.d(tag, "PNS is not closed - closing it now")
|
||||
playerNotificationService.closePlayback()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ import androidx.annotation.RequiresApi
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.media.MediaBrowserServiceCompat
|
||||
import androidx.media.utils.MediaConstants
|
||||
import com.audiobookshelf.app.BuildConfig
|
||||
import com.audiobookshelf.app.data.*
|
||||
import com.audiobookshelf.app.data.DeviceInfo
|
||||
import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.audiobookshelf.app.media.MediaManager
|
||||
import com.audiobookshelf.app.server.ApiHandler
|
||||
@@ -39,6 +41,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
|
||||
companion object {
|
||||
var isStarted = false
|
||||
var isClosed = false
|
||||
}
|
||||
|
||||
interface ClientEventEmitter {
|
||||
@@ -46,12 +49,12 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
fun onPlaybackClosed()
|
||||
fun onPlayingUpdate(isPlaying: Boolean)
|
||||
fun onMetadata(metadata: PlaybackMetadata)
|
||||
fun onPrepare(audiobookId: String, playWhenReady: Boolean)
|
||||
fun onSleepTimerEnded(currentPosition: Long)
|
||||
fun onSleepTimerSet(sleepTimeRemaining: Int)
|
||||
fun onLocalMediaProgressUpdate(localMediaProgress: LocalMediaProgress)
|
||||
fun onPlaybackFailed(errorMessage:String)
|
||||
fun onMediaPlayerChanged(mediaPlayer:String)
|
||||
fun onProgressSyncFailing()
|
||||
}
|
||||
|
||||
private val tag = "PlayerService"
|
||||
@@ -75,7 +78,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
lateinit var sleepTimerManager:SleepTimerManager
|
||||
lateinit var mediaProgressSyncer:MediaProgressSyncer
|
||||
|
||||
private var notificationId = 10;
|
||||
private var notificationId = 10
|
||||
private var channelId = "audiobookshelf_channel"
|
||||
private var channelName = "Audiobookshelf Channel"
|
||||
|
||||
@@ -100,7 +103,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
// Android Auto Media Browser Service
|
||||
if (SERVICE_INTERFACE == intent.action) {
|
||||
Log.d(tag, "Is Media Browser Service")
|
||||
return super.onBind(intent);
|
||||
return super.onBind(intent)
|
||||
}
|
||||
return binder
|
||||
}
|
||||
@@ -110,11 +113,6 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
fun getService(): PlayerNotificationService = this@PlayerNotificationService
|
||||
}
|
||||
|
||||
fun stopService(context: Context) {
|
||||
val stopIntent = Intent(context, PlayerNotificationService::class.java)
|
||||
context.stopService(stopIntent)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
isStarted = true
|
||||
Log.d(tag, "onStartCommand $startId")
|
||||
@@ -157,30 +155,12 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
|
||||
override fun onCreate() {
|
||||
Log.d(tag, "onCreate")
|
||||
super.onCreate()
|
||||
ctx = this
|
||||
|
||||
// Initialize player
|
||||
val customLoadControl:LoadControl = DefaultLoadControl.Builder().setBufferDurationsMs(
|
||||
1000 * 20, // 20s min buffer
|
||||
1000 * 45, // 45s max buffer
|
||||
1000 * 5, // 5s playback start
|
||||
1000 * 20 // 20s playback rebuffer
|
||||
).build()
|
||||
|
||||
mPlayer = ExoPlayer.Builder(this)
|
||||
.setLoadControl(customLoadControl)
|
||||
.setSeekBackIncrementMs(10000)
|
||||
.setSeekForwardIncrementMs(10000)
|
||||
.build()
|
||||
mPlayer.setHandleAudioBecomingNoisy(true)
|
||||
mPlayer.addListener(PlayerListener(this))
|
||||
val audioAttributes:AudioAttributes = AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.CONTENT_TYPE_SPEECH).build()
|
||||
mPlayer.setAudioAttributes(audioAttributes, true)
|
||||
|
||||
currentPlayer = mPlayer
|
||||
DbManager.initialize(ctx)
|
||||
|
||||
// Initialize API
|
||||
apiHandler = ApiHandler(ctx)
|
||||
@@ -232,6 +212,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
playerNotificationManager.setUseNextAction(false)
|
||||
playerNotificationManager.setUsePreviousAction(false)
|
||||
playerNotificationManager.setUseChronometer(false)
|
||||
playerNotificationManager.setUseStopAction(true)
|
||||
playerNotificationManager.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
playerNotificationManager.setPriority(NotificationCompat.PRIORITY_MAX)
|
||||
playerNotificationManager.setUseFastForwardActionInCompactView(true)
|
||||
@@ -245,11 +226,26 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
mediaSessionConnector = MediaSessionConnector(mediaSession)
|
||||
val queueNavigator: TimelineQueueNavigator = object : TimelineQueueNavigator(mediaSession) {
|
||||
override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat {
|
||||
if (currentPlaybackSession == null) {
|
||||
Log.e(tag,"Playback session is not set - returning blank MediaDescriptionCompat")
|
||||
return MediaDescriptionCompat.Builder().build()
|
||||
}
|
||||
|
||||
val coverUri = currentPlaybackSession!!.getCoverUri()
|
||||
|
||||
// Fix for local images crashing on Android 11 for specific devices
|
||||
// https://stackoverflow.com/questions/64186578/android-11-mediastyle-notification-crash/64232958#64232958
|
||||
ctx.grantUriPermission(
|
||||
"com.android.systemui",
|
||||
coverUri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION
|
||||
)
|
||||
|
||||
return MediaDescriptionCompat.Builder()
|
||||
.setMediaId(currentPlaybackSession!!.id)
|
||||
.setTitle(currentPlaybackSession!!.displayTitle)
|
||||
.setSubtitle(currentPlaybackSession!!.displayAuthor)
|
||||
.setIconUri(currentPlaybackSession!!.getCoverUri()).build()
|
||||
.setIconUri(coverUri).build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,17 +260,47 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
)
|
||||
mediaSessionConnector.setQueueNavigator(queueNavigator)
|
||||
mediaSessionConnector.setPlaybackPreparer(MediaSessionPlaybackPreparer(this))
|
||||
mediaSessionConnector.setPlayer(mPlayer)
|
||||
|
||||
mediaSession.setCallback(MediaSessionCallback(this))
|
||||
|
||||
initializeMPlayer()
|
||||
currentPlayer = mPlayer
|
||||
}
|
||||
|
||||
private fun initializeMPlayer() {
|
||||
val customLoadControl:LoadControl = DefaultLoadControl.Builder().setBufferDurationsMs(
|
||||
1000 * 20, // 20s min buffer
|
||||
1000 * 45, // 45s max buffer
|
||||
1000 * 5, // 5s playback start
|
||||
1000 * 20 // 20s playback rebuffer
|
||||
).build()
|
||||
|
||||
val seekBackTime = DeviceManager.deviceData.deviceSettings?.jumpBackwardsTimeMs ?: 10000
|
||||
val seekForwardTime = DeviceManager.deviceData.deviceSettings?.jumpForwardTimeMs ?: 10000
|
||||
Log.d(tag, "Seek Back Time $seekBackTime")
|
||||
Log.d(tag, "Seek Forward Time $seekForwardTime")
|
||||
|
||||
mPlayer = ExoPlayer.Builder(this)
|
||||
.setLoadControl(customLoadControl)
|
||||
.setSeekBackIncrementMs(seekBackTime)
|
||||
.setSeekForwardIncrementMs(seekForwardTime)
|
||||
.build()
|
||||
mPlayer.setHandleAudioBecomingNoisy(true)
|
||||
mPlayer.addListener(PlayerListener(this))
|
||||
val audioAttributes:AudioAttributes = AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.CONTENT_TYPE_SPEECH).build()
|
||||
mPlayer.setAudioAttributes(audioAttributes, true)
|
||||
|
||||
//attach player to playerNotificationManager
|
||||
playerNotificationManager.setPlayer(mPlayer)
|
||||
mediaSession.setCallback(MediaSessionCallback(this))
|
||||
|
||||
mediaSessionConnector.setPlayer(mPlayer)
|
||||
}
|
||||
|
||||
/*
|
||||
User callable methods
|
||||
*/
|
||||
fun preparePlayer(playbackSession: PlaybackSession, playWhenReady:Boolean, playbackRate:Float?) {
|
||||
isClosed = false
|
||||
val playbackRateToUse = playbackRate ?: initialPlaybackRate ?: 1f
|
||||
initialPlaybackRate = playbackRate
|
||||
|
||||
@@ -346,7 +372,9 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
Log.d(tag, "Prepare complete for session ${currentPlaybackSession?.displayTitle} | ${currentPlayer.mediaItemCount}")
|
||||
currentPlayer.playWhenReady = playWhenReady
|
||||
currentPlayer.setPlaybackSpeed(playbackRateToUse)
|
||||
|
||||
currentPlayer.prepare()
|
||||
|
||||
} else if (castPlayer != null) {
|
||||
val currentTrackIndex = playbackSession.getCurrentTrackIndex()
|
||||
val currentTrackTime = playbackSession.getCurrentTrackTimeMs()
|
||||
@@ -361,14 +389,19 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
// On error and was attempting to direct play - fallback to transcode
|
||||
currentPlaybackSession?.let { playbackSession ->
|
||||
if (playbackSession.isDirectPlay) {
|
||||
val mediaPlayer = getMediaPlayer()
|
||||
Log.d(tag, "Fallback to transcode $mediaPlayer")
|
||||
val playItemRequestPayload = getPlayItemRequestPayload(true)
|
||||
Log.d(tag, "Fallback to transcode $playItemRequestPayload.mediaPlayer")
|
||||
|
||||
val libraryItemId = playbackSession.libraryItemId ?: "" // Must be true since direct play
|
||||
val episodeId = playbackSession.episodeId
|
||||
apiHandler.playLibraryItem(libraryItemId, episodeId, true, mediaPlayer) {
|
||||
Handler(Looper.getMainLooper()).post() {
|
||||
preparePlayer(it, true, null)
|
||||
apiHandler.playLibraryItem(libraryItemId, episodeId, playItemRequestPayload) {
|
||||
if (it == null) { // Play request failed
|
||||
clientEventEmitter?.onPlaybackFailed(errorMessage)
|
||||
closePlayback()
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
preparePlayer(it, true, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -378,6 +411,25 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
}
|
||||
}
|
||||
|
||||
fun startNewPlaybackSession() {
|
||||
currentPlaybackSession?.let { playbackSession ->
|
||||
val forceTranscode = playbackSession.isHLS // If already HLS then force
|
||||
val playItemRequestPayload = getPlayItemRequestPayload(forceTranscode)
|
||||
|
||||
val libraryItemId = playbackSession.libraryItemId ?: "" // Must be true since direct play
|
||||
val episodeId = playbackSession.episodeId
|
||||
apiHandler.playLibraryItem(libraryItemId, episodeId, playItemRequestPayload) {
|
||||
if (it == null) {
|
||||
Log.e(tag, "Failed to start new playback session")
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
preparePlayer(it, true, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun switchToPlayer(useCastPlayer: Boolean) {
|
||||
val wasPlaying = currentPlayer.isPlaying
|
||||
if (useCastPlayer) {
|
||||
@@ -469,6 +521,80 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
return currentPlaybackSession?.id
|
||||
}
|
||||
|
||||
fun getCurrentBookChapter():BookChapter? {
|
||||
return currentPlaybackSession?.getChapterForTime(this.getCurrentTime())
|
||||
}
|
||||
|
||||
// Called from PlayerListener play event
|
||||
// check with server if progress has updated since last play and sync progress update
|
||||
fun checkCurrentSessionProgress():Boolean {
|
||||
if (currentPlaybackSession == null) return true
|
||||
|
||||
currentPlaybackSession?.let { playbackSession ->
|
||||
if (!apiHandler.isOnline() || playbackSession.isLocalLibraryItemOnly) {
|
||||
return true // carry on
|
||||
}
|
||||
|
||||
if (playbackSession.isLocal) {
|
||||
|
||||
// Make sure this connection config exists
|
||||
val serverConnectionConfig = DeviceManager.getServerConnectionConfig(playbackSession.serverConnectionConfigId)
|
||||
if (serverConnectionConfig == null) {
|
||||
Log.d(tag, "checkCurrentSessionProgress: Local library item server connection config is not saved ${playbackSession.serverConnectionConfigId}")
|
||||
return true // carry on
|
||||
}
|
||||
|
||||
// Local playback session check if server has updated media progress
|
||||
Log.d(tag, "checkCurrentSessionProgress: Checking if local media progress was updated on server")
|
||||
apiHandler.getMediaProgress(playbackSession.libraryItemId!!, playbackSession.episodeId, serverConnectionConfig) { mediaProgress ->
|
||||
|
||||
if (mediaProgress != null && mediaProgress.lastUpdate > playbackSession.updatedAt && mediaProgress.currentTime != playbackSession.currentTime) {
|
||||
Log.d(tag, "checkCurrentSessionProgress: Media progress was updated since last play time updating from ${playbackSession.currentTime} to ${mediaProgress.currentTime}")
|
||||
mediaProgressSyncer.syncFromServerProgress(mediaProgress)
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
seekPlayer(playbackSession.currentTimeMs)
|
||||
}
|
||||
}
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
// Should already be playing
|
||||
currentPlayer.volume = 1F // Volume on sleep timer might have decreased this
|
||||
mediaProgressSyncer.start()
|
||||
clientEventEmitter?.onPlayingUpdate(true)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Streaming from server so check if playback session still exists on server
|
||||
Log.d(
|
||||
tag,
|
||||
"checkCurrentSessionProgress: Checking if playback session for server stream is still available"
|
||||
)
|
||||
apiHandler.getPlaybackSession(playbackSession.id) {
|
||||
if (it == null) {
|
||||
Log.d(
|
||||
tag,
|
||||
"checkCurrentSessionProgress: Playback session does not exist on server - start new playback session"
|
||||
)
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
currentPlayer.pause()
|
||||
startNewPlaybackSession()
|
||||
}
|
||||
} else {
|
||||
Log.d(tag, "checkCurrentSessionProgress: Playback session still available on server")
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
currentPlayer.volume = 1F // Volume on sleep timer might have decreased this
|
||||
mediaProgressSyncer.start()
|
||||
clientEventEmitter?.onPlayingUpdate(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun play() {
|
||||
if (currentPlayer.isPlaying) {
|
||||
Log.d(tag, "Already playing")
|
||||
@@ -510,12 +636,10 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
|
||||
fun seekForward(amount: Long) {
|
||||
seekPlayer(getCurrentTime() + amount)
|
||||
// currentPlayer.seekTo(currentPlayer.currentPosition + amount)
|
||||
}
|
||||
|
||||
fun seekBackward(amount: Long) {
|
||||
seekPlayer(getCurrentTime() - amount)
|
||||
// currentPlayer.seekTo(currentPlayer.currentPosition - amount)
|
||||
}
|
||||
|
||||
fun setPlaybackSpeed(speed: Float) {
|
||||
@@ -523,11 +647,19 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
}
|
||||
|
||||
fun closePlayback() {
|
||||
currentPlayer.clearMediaItems()
|
||||
currentPlayer.stop()
|
||||
Log.d(tag, "closePlayback")
|
||||
try {
|
||||
currentPlayer.stop()
|
||||
currentPlayer.clearMediaItems()
|
||||
} catch(e:Exception) {
|
||||
Log.e(tag, "Exception clearing exoplayer $e")
|
||||
}
|
||||
|
||||
currentPlaybackSession = null
|
||||
clientEventEmitter?.onPlaybackClosed()
|
||||
PlayerListener.lastPauseTime = 0
|
||||
isClosed = true
|
||||
stopForeground(true)
|
||||
}
|
||||
|
||||
fun sendClientMetadata(playerState: PlayerState) {
|
||||
@@ -539,10 +671,29 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
return if(currentPlayer == castPlayer) "cast-player" else "exo-player"
|
||||
}
|
||||
|
||||
fun getDeviceInfo(): DeviceInfo {
|
||||
/* EXAMPLE
|
||||
manufacturer: Google
|
||||
model: Pixel 6
|
||||
brand: google
|
||||
sdkVersion: 32
|
||||
appVersion: 0.9.46-beta
|
||||
*/
|
||||
return DeviceInfo(Build.MANUFACTURER, Build.MODEL, Build.BRAND, Build.VERSION.SDK_INT, BuildConfig.VERSION_NAME)
|
||||
}
|
||||
|
||||
fun getPlayItemRequestPayload(forceTranscode:Boolean):PlayItemRequestPayload {
|
||||
return PlayItemRequestPayload(getMediaPlayer(), !forceTranscode, forceTranscode, getDeviceInfo())
|
||||
}
|
||||
|
||||
fun getContext():Context {
|
||||
return ctx
|
||||
}
|
||||
|
||||
fun alertSyncFailing() {
|
||||
clientEventEmitter?.onProgressSyncFailing()
|
||||
}
|
||||
|
||||
//
|
||||
// MEDIA BROWSER STUFF (ANDROID AUTO)
|
||||
//
|
||||
@@ -555,6 +706,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
|
||||
private val AUTO_MEDIA_ROOT = "/"
|
||||
private val ALL_ROOT = "__ALL__"
|
||||
private val LIBRARIES_ROOT = "__LIBRARIES__"
|
||||
private lateinit var browseTree:BrowseTree
|
||||
|
||||
|
||||
@@ -575,11 +727,8 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
// No further calls will be made to other media browsing methods.
|
||||
null
|
||||
} else {
|
||||
if (!isStarted) {
|
||||
Log.d(tag, "AA Not yet started")
|
||||
mediaManager.initializeAndroidAuto()
|
||||
isStarted = true
|
||||
}
|
||||
isStarted = true
|
||||
mediaManager.checkResetServerItems() // Reset any server items if no longer connected to server
|
||||
|
||||
isAndroidAuto = true
|
||||
|
||||
@@ -600,32 +749,66 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
|
||||
override fun onLoadChildren(parentMediaId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
|
||||
Log.d(tag, "ON LOAD CHILDREN $parentMediaId")
|
||||
|
||||
val flag = if (parentMediaId == AUTO_MEDIA_ROOT) MediaBrowserCompat.MediaItem.FLAG_BROWSABLE else MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
|
||||
var flag = if (parentMediaId == AUTO_MEDIA_ROOT || parentMediaId == LIBRARIES_ROOT) MediaBrowserCompat.MediaItem.FLAG_BROWSABLE else MediaBrowserCompat.MediaItem.FLAG_PLAYABLE
|
||||
|
||||
result.detach()
|
||||
|
||||
mediaManager.loadAndroidAutoItems("main") { libraryCategories ->
|
||||
browseTree = BrowseTree(this, libraryCategories)
|
||||
val children = browseTree[parentMediaId]?.map { item ->
|
||||
MediaBrowserCompat.MediaItem(item.description, flag)
|
||||
if (parentMediaId.startsWith("li_") || parentMediaId.startsWith("local_")) { // Show podcast episodes
|
||||
Log.d(tag, "Loading podcast episodes")
|
||||
mediaManager.loadPodcastEpisodeMediaBrowserItems(parentMediaId) {
|
||||
result.sendResult(it)
|
||||
}
|
||||
result.sendResult(children as MutableList<MediaBrowserCompat.MediaItem>?)
|
||||
}
|
||||
} else if (::browseTree.isInitialized && browseTree[parentMediaId] == null && mediaManager.getIsLibrary(parentMediaId)) { // Load library items for library
|
||||
|
||||
// TODO: For using sub menus. Check if this is the root menu:
|
||||
// if (AUTO_MEDIA_ROOT == parentMediaId) {
|
||||
// build the MediaItem objects for the top level,
|
||||
// and put them in the mediaItems list
|
||||
// } else {
|
||||
// examine the passed parentMediaId to see which submenu we're at,
|
||||
// and put the children of that menu in the mediaItems list
|
||||
// }
|
||||
mediaManager.loadLibraryItemsWithAudio(parentMediaId) { libraryItems ->
|
||||
val children = libraryItems.map { libraryItem ->
|
||||
val libraryItemMediaMetadata = libraryItem.getMediaMetadata()
|
||||
|
||||
if (libraryItem.mediaType == "podcast") { // Podcasts are browseable
|
||||
flag = MediaBrowserCompat.MediaItem.FLAG_BROWSABLE
|
||||
}
|
||||
|
||||
MediaBrowserCompat.MediaItem(libraryItemMediaMetadata.description, flag)
|
||||
}
|
||||
result.sendResult(children as MutableList<MediaBrowserCompat.MediaItem>?)
|
||||
}
|
||||
} else if (parentMediaId == "__DOWNLOADS__") { // Load downloads
|
||||
|
||||
val localBooks = DeviceManager.dbManager.getLocalLibraryItems("book")
|
||||
val localPodcasts = DeviceManager.dbManager.getLocalLibraryItems("podcast")
|
||||
val localBrowseItems:MutableList<MediaBrowserCompat.MediaItem> = mutableListOf()
|
||||
|
||||
localBooks.forEach { localLibraryItem ->
|
||||
val mediaMetadata = localLibraryItem.getMediaMetadata(ctx)
|
||||
localBrowseItems += MediaBrowserCompat.MediaItem(mediaMetadata.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
|
||||
}
|
||||
|
||||
localPodcasts.forEach { localLibraryItem ->
|
||||
val mediaMetadata = localLibraryItem.getMediaMetadata(ctx)
|
||||
localBrowseItems += MediaBrowserCompat.MediaItem(mediaMetadata.description, MediaBrowserCompat.MediaItem.FLAG_BROWSABLE)
|
||||
}
|
||||
|
||||
result.sendResult(localBrowseItems)
|
||||
|
||||
} else { // Load categories
|
||||
|
||||
mediaManager.loadAndroidAutoItems() { libraryCategories ->
|
||||
browseTree = BrowseTree(this, libraryCategories, mediaManager.serverLibraries)
|
||||
|
||||
val children = browseTree[parentMediaId]?.map { item ->
|
||||
Log.d(tag, "Loading Browser Media Item ${item.description.title} $flag")
|
||||
|
||||
MediaBrowserCompat.MediaItem(item.description, flag)
|
||||
}
|
||||
result.sendResult(children as MutableList<MediaBrowserCompat.MediaItem>?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSearch(query: String, extras: Bundle?, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
|
||||
result.detach()
|
||||
mediaManager.loadAndroidAutoItems("main") { libraryCategories ->
|
||||
browseTree = BrowseTree(this, libraryCategories)
|
||||
mediaManager.loadAndroidAutoItems() { libraryCategories ->
|
||||
browseTree = BrowseTree(this, libraryCategories, mediaManager.serverLibraries)
|
||||
val children = browseTree[ALL_ROOT]?.map { item ->
|
||||
MediaBrowserCompat.MediaItem(item.description, MediaBrowserCompat.MediaItem.FLAG_PLAYABLE)
|
||||
}
|
||||
|
||||
@@ -59,13 +59,6 @@ class AbsAudioPlayer : Plugin() {
|
||||
notifyListeners("onMetadata", JSObject(jacksonMapper.writeValueAsString(metadata)))
|
||||
}
|
||||
|
||||
override fun onPrepare(audiobookId: String, playWhenReady: Boolean) {
|
||||
val jsobj = JSObject()
|
||||
jsobj.put("audiobookId", audiobookId)
|
||||
jsobj.put("playWhenReady", playWhenReady)
|
||||
notifyListeners("onPrepareMedia", jsobj)
|
||||
}
|
||||
|
||||
override fun onSleepTimerEnded(currentPosition: Long) {
|
||||
emit("onSleepTimerEnded", currentPosition)
|
||||
}
|
||||
@@ -85,6 +78,10 @@ class AbsAudioPlayer : Plugin() {
|
||||
override fun onMediaPlayerChanged(mediaPlayer:String) {
|
||||
emit("onMediaPlayerChanged", mediaPlayer)
|
||||
}
|
||||
|
||||
override fun onProgressSyncFailing() {
|
||||
emit("onProgressSyncFailing", "")
|
||||
}
|
||||
})
|
||||
}
|
||||
mainActivity.pluginCallback = foregroundServiceReady
|
||||
@@ -168,7 +165,7 @@ class AbsAudioPlayer : Plugin() {
|
||||
|
||||
if (libraryItemId.isEmpty()) {
|
||||
Log.e(tag, "Invalid call to play library item no library item id")
|
||||
return call.resolve()
|
||||
return call.resolve(JSObject("{\"error\":\"Invalid request\"}"))
|
||||
}
|
||||
|
||||
if (libraryItemId.startsWith("local")) { // Play local media item
|
||||
@@ -179,7 +176,7 @@ class AbsAudioPlayer : Plugin() {
|
||||
episode = podcastMedia.episodes?.find { ep -> ep.id == episodeId }
|
||||
if (episode == null) {
|
||||
Log.e(tag, "prepareLibraryItem: Podcast episode not found $episodeId")
|
||||
return call.resolve(JSObject())
|
||||
return call.resolve(JSObject("{\"error\":\"Podcast episode not found\"}"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,16 +188,19 @@ class AbsAudioPlayer : Plugin() {
|
||||
return call.resolve(JSObject())
|
||||
}
|
||||
} else { // Play library item from server
|
||||
val mediaPlayer = playerNotificationService.getMediaPlayer()
|
||||
val playItemRequestPayload = playerNotificationService.getPlayItemRequestPayload(false)
|
||||
|
||||
apiHandler.playLibraryItem(libraryItemId, episodeId, false, mediaPlayer) {
|
||||
apiHandler.playLibraryItem(libraryItemId, episodeId, playItemRequestPayload) {
|
||||
if (it == null) {
|
||||
call.resolve(JSObject("{\"error\":\"Server play request failed\"}"))
|
||||
} else {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
Log.d(tag, "Preparing Player TEST ${jacksonMapper.writeValueAsString(it)}")
|
||||
playerNotificationService.preparePlayer(it, playWhenReady, playbackRate)
|
||||
}
|
||||
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
Log.d(tag, "Preparing Player TEST ${jacksonMapper.writeValueAsString(it)}")
|
||||
playerNotificationService.preparePlayer(it, playWhenReady, playbackRate)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(it)))
|
||||
}
|
||||
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(it)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.audiobookshelf.app.device.DeviceManager
|
||||
import com.audiobookshelf.app.server.ApiHandler
|
||||
import com.fasterxml.jackson.core.json.JsonReadFeature
|
||||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
|
||||
import com.fasterxml.jackson.module.kotlin.readValue
|
||||
import com.getcapacitor.*
|
||||
import com.getcapacitor.annotation.CapacitorPlugin
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -24,6 +25,7 @@ class AbsDatabase : Plugin() {
|
||||
data class LocalMediaProgressPayload(val value:List<LocalMediaProgress>)
|
||||
data class LocalLibraryItemsPayload(val value:List<LocalLibraryItem>)
|
||||
data class LocalFoldersPayload(val value:List<LocalFolder>)
|
||||
data class ServerConnConfigPayload(val id:String?, val index:Int, val name:String?, val userId:String, val username:String, val token:String, val address:String?, val customHeaders:Map<String,String>?)
|
||||
|
||||
override fun load() {
|
||||
mainActivity = (activity as MainActivity)
|
||||
@@ -36,7 +38,7 @@ class AbsDatabase : Plugin() {
|
||||
@PluginMethod
|
||||
fun getDeviceData(call:PluginCall) {
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var deviceData = DeviceManager.dbManager.getDeviceData()
|
||||
val deviceData = DeviceManager.dbManager.getDeviceData()
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(deviceData)))
|
||||
}
|
||||
}
|
||||
@@ -44,17 +46,17 @@ class AbsDatabase : Plugin() {
|
||||
@PluginMethod
|
||||
fun getLocalFolders(call:PluginCall) {
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var folders = DeviceManager.dbManager.getAllLocalFolders()
|
||||
val folders = DeviceManager.dbManager.getAllLocalFolders()
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(LocalFoldersPayload(folders))))
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun getLocalFolder(call:PluginCall) {
|
||||
var folderId = call.getString("folderId", "").toString()
|
||||
val folderId = call.getString("folderId", "").toString()
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
DeviceManager.dbManager.getLocalFolder(folderId)?.let {
|
||||
var folderObj = jacksonMapper.writeValueAsString(it)
|
||||
val folderObj = jacksonMapper.writeValueAsString(it)
|
||||
call.resolve(JSObject(folderObj))
|
||||
} ?: call.resolve()
|
||||
}
|
||||
@@ -62,10 +64,10 @@ class AbsDatabase : Plugin() {
|
||||
|
||||
@PluginMethod
|
||||
fun getLocalLibraryItem(call:PluginCall) {
|
||||
var id = call.getString("id", "").toString()
|
||||
val id = call.getString("id", "").toString()
|
||||
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var localLibraryItem = DeviceManager.dbManager.getLocalLibraryItem(id)
|
||||
val localLibraryItem = DeviceManager.dbManager.getLocalLibraryItem(id)
|
||||
if (localLibraryItem == null) {
|
||||
call.resolve()
|
||||
} else {
|
||||
@@ -76,9 +78,9 @@ class AbsDatabase : Plugin() {
|
||||
|
||||
@PluginMethod
|
||||
fun getLocalLibraryItemByLLId(call:PluginCall) {
|
||||
var libraryItemId = call.getString("libraryItemId", "").toString()
|
||||
val libraryItemId = call.getString("libraryItemId", "").toString()
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var localLibraryItem = DeviceManager.dbManager.getLocalLibraryItemByLLId(libraryItemId)
|
||||
val localLibraryItem = DeviceManager.dbManager.getLocalLibraryItemByLLId(libraryItemId)
|
||||
if (localLibraryItem == null) {
|
||||
call.resolve()
|
||||
} else {
|
||||
@@ -89,40 +91,41 @@ class AbsDatabase : Plugin() {
|
||||
|
||||
@PluginMethod
|
||||
fun getLocalLibraryItems(call:PluginCall) {
|
||||
var mediaType = call.getString("mediaType", "").toString()
|
||||
val mediaType = call.getString("mediaType", "").toString()
|
||||
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var localLibraryItems = DeviceManager.dbManager.getLocalLibraryItems(mediaType)
|
||||
val localLibraryItems = DeviceManager.dbManager.getLocalLibraryItems(mediaType)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(LocalLibraryItemsPayload(localLibraryItems))))
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun getLocalLibraryItemsInFolder(call:PluginCall) {
|
||||
var folderId = call.getString("folderId", "").toString()
|
||||
val folderId = call.getString("folderId", "").toString()
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var localLibraryItems = DeviceManager.dbManager.getLocalLibraryItemsInFolder(folderId)
|
||||
val localLibraryItems = DeviceManager.dbManager.getLocalLibraryItemsInFolder(folderId)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(LocalLibraryItemsPayload(localLibraryItems))))
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun setCurrentServerConnectionConfig(call:PluginCall) {
|
||||
var serverConnectionConfigId = call.getString("id", "").toString()
|
||||
var serverConnectionConfig = DeviceManager.deviceData.serverConnectionConfigs.find { it.id == serverConnectionConfigId }
|
||||
Log.d(tag, "setCurrentServerConnectionConfig ${call.data}")
|
||||
val serverConfigPayload = jacksonMapper.readValue<ServerConnConfigPayload>(call.data.toString())
|
||||
var serverConnectionConfig = DeviceManager.deviceData.serverConnectionConfigs.find { it.id == serverConfigPayload.id }
|
||||
|
||||
var userId = call.getString("userId", "").toString()
|
||||
var username = call.getString("username", "").toString()
|
||||
var token = call.getString("token", "").toString()
|
||||
val userId = serverConfigPayload.userId
|
||||
val username = serverConfigPayload.username
|
||||
val token = serverConfigPayload.token
|
||||
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
if (serverConnectionConfig == null) { // New Server Connection
|
||||
var serverAddress = call.getString("address", "").toString()
|
||||
val serverAddress = call.getString("address", "").toString()
|
||||
|
||||
// Create new server connection config
|
||||
var sscId = DeviceManager.getBase64Id("$serverAddress@$username")
|
||||
var sscIndex = DeviceManager.deviceData.serverConnectionConfigs.size
|
||||
serverConnectionConfig = ServerConnectionConfig(sscId, sscIndex, "$serverAddress ($username)", serverAddress, userId, username, token)
|
||||
val sscId = DeviceManager.getBase64Id("$serverAddress@$username")
|
||||
val sscIndex = DeviceManager.deviceData.serverConnectionConfigs.size
|
||||
serverConnectionConfig = ServerConnectionConfig(sscId, sscIndex, "$serverAddress ($username)", serverAddress, userId, username, token, serverConfigPayload.customHeaders)
|
||||
|
||||
// Add and save
|
||||
DeviceManager.deviceData.serverConnectionConfigs.add(serverConnectionConfig!!)
|
||||
@@ -139,8 +142,8 @@ class AbsDatabase : Plugin() {
|
||||
}
|
||||
|
||||
// Set last connection config
|
||||
if (DeviceManager.deviceData.lastServerConnectionConfigId != serverConnectionConfigId) {
|
||||
DeviceManager.deviceData.lastServerConnectionConfigId = serverConnectionConfigId
|
||||
if (DeviceManager.deviceData.lastServerConnectionConfigId != serverConfigPayload.id) {
|
||||
DeviceManager.deviceData.lastServerConnectionConfigId = serverConfigPayload.id
|
||||
shouldSave = true
|
||||
}
|
||||
|
||||
@@ -155,7 +158,7 @@ class AbsDatabase : Plugin() {
|
||||
@PluginMethod
|
||||
fun removeServerConnectionConfig(call:PluginCall) {
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var serverConnectionConfigId = call.getString("serverConnectionConfigId", "").toString()
|
||||
val serverConnectionConfigId = call.getString("serverConnectionConfigId", "").toString()
|
||||
DeviceManager.deviceData.serverConnectionConfigs = DeviceManager.deviceData.serverConnectionConfigs.filter { it.id != serverConnectionConfigId } as MutableList<ServerConnectionConfig>
|
||||
if (DeviceManager.deviceData.lastServerConnectionConfigId == serverConnectionConfigId) {
|
||||
DeviceManager.deviceData.lastServerConnectionConfigId = null
|
||||
@@ -181,14 +184,14 @@ class AbsDatabase : Plugin() {
|
||||
@PluginMethod
|
||||
fun getAllLocalMediaProgress(call:PluginCall) {
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
var localMediaProgress = DeviceManager.dbManager.getAllLocalMediaProgress()
|
||||
val localMediaProgress = DeviceManager.dbManager.getAllLocalMediaProgress()
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(LocalMediaProgressPayload(localMediaProgress))))
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun removeLocalMediaProgress(call:PluginCall) {
|
||||
var localMediaProgressId = call.getString("localMediaProgressId", "").toString()
|
||||
val localMediaProgressId = call.getString("localMediaProgressId", "").toString()
|
||||
DeviceManager.dbManager.removeLocalMediaProgress(localMediaProgressId)
|
||||
call.resolve()
|
||||
}
|
||||
@@ -204,6 +207,63 @@ class AbsDatabase : Plugin() {
|
||||
}
|
||||
}
|
||||
|
||||
// Updates received via web socket
|
||||
// This function doesn't need to sync with the server also because this data is coming from the server
|
||||
// If sending the localMediaProgressId then update existing media progress
|
||||
// If sending localLibraryItemId then save new local media progress
|
||||
@PluginMethod
|
||||
fun syncServerMediaProgressWithLocalMediaProgress(call:PluginCall) {
|
||||
val serverMediaProgress = call.getObject("mediaProgress").toString()
|
||||
val localLibraryItemId = call.getString("localLibraryItemId", "").toString()
|
||||
var localEpisodeId:String? = call.getString("localEpisodeId", "").toString()
|
||||
if (localEpisodeId.isNullOrEmpty()) localEpisodeId = null
|
||||
var localMediaProgressId = call.getString("localMediaProgressId") ?: ""
|
||||
|
||||
val mediaProgress = jacksonMapper.readValue<MediaProgress>(serverMediaProgress)
|
||||
|
||||
if (localMediaProgressId == "") {
|
||||
val localLibraryItem = DeviceManager.dbManager.getLocalLibraryItem(localLibraryItemId)
|
||||
if (localLibraryItem != null) {
|
||||
localMediaProgressId = if (localEpisodeId.isNullOrEmpty()) localLibraryItemId else "$localLibraryItemId-$localEpisodeId"
|
||||
|
||||
val localMediaProgress = LocalMediaProgress(
|
||||
id = localMediaProgressId,
|
||||
localLibraryItemId = localLibraryItemId,
|
||||
localEpisodeId = localEpisodeId,
|
||||
duration = mediaProgress.duration,
|
||||
progress = mediaProgress.progress,
|
||||
currentTime = mediaProgress.currentTime,
|
||||
isFinished = mediaProgress.isFinished,
|
||||
lastUpdate = mediaProgress.lastUpdate,
|
||||
startedAt = mediaProgress.startedAt,
|
||||
finishedAt = mediaProgress.finishedAt,
|
||||
serverConnectionConfigId = localLibraryItem.serverConnectionConfigId,
|
||||
serverAddress = localLibraryItem.serverAddress,
|
||||
serverUserId = localLibraryItem.serverUserId,
|
||||
libraryItemId = localLibraryItem.libraryItemId,
|
||||
episodeId = mediaProgress.episodeId)
|
||||
|
||||
Log.d(tag, "syncServerMediaProgressWithLocalMediaProgress: Saving new local media progress $localMediaProgress")
|
||||
DeviceManager.dbManager.saveLocalMediaProgress(localMediaProgress)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(localMediaProgress)))
|
||||
} else {
|
||||
Log.e(tag, "syncServerMediaProgressWithLocalMediaProgress: Local library item not found")
|
||||
}
|
||||
} else {
|
||||
Log.d(tag, "syncServerMediaProgressWithLocalMediaProgress $localMediaProgressId")
|
||||
val localMediaProgress = DeviceManager.dbManager.getLocalMediaProgress(localMediaProgressId)
|
||||
|
||||
if (localMediaProgress == null) {
|
||||
Log.w(tag, "syncServerMediaProgressWithLocalMediaProgress Local media progress not found $localMediaProgressId")
|
||||
call.resolve()
|
||||
} else {
|
||||
localMediaProgress.updateFromServerMediaProgress(mediaProgress)
|
||||
DeviceManager.dbManager.saveLocalMediaProgress(localMediaProgress)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(localMediaProgress)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun updateLocalMediaProgressFinished(call:PluginCall) {
|
||||
val localLibraryItemId = call.getString("localLibraryItemId", "").toString()
|
||||
@@ -273,13 +333,13 @@ class AbsDatabase : Plugin() {
|
||||
// Send update to server media progress is linked to a server and user is logged into that server
|
||||
localMediaProgress.serverConnectionConfigId?.let { configId ->
|
||||
if (DeviceManager.serverConnectionConfigId == configId) {
|
||||
var libraryItemId = localMediaProgress.libraryItemId ?: ""
|
||||
var episodeId = localMediaProgress.episodeId ?: ""
|
||||
var updatePayload = JSObject()
|
||||
val libraryItemId = localMediaProgress.libraryItemId ?: ""
|
||||
val episodeId = localMediaProgress.episodeId ?: ""
|
||||
val updatePayload = JSObject()
|
||||
updatePayload.put("isFinished", isFinished)
|
||||
apiHandler.updateMediaProgress(libraryItemId,episodeId,updatePayload) {
|
||||
Log.d(tag, "updateLocalMediaProgressFinished: Updated media progress isFinished on server")
|
||||
var jsobj = JSObject()
|
||||
val jsobj = JSObject()
|
||||
jsobj.put("local", true)
|
||||
jsobj.put("server", true)
|
||||
jsobj.put("localMediaProgress", JSObject(lmpstring))
|
||||
@@ -288,7 +348,7 @@ class AbsDatabase : Plugin() {
|
||||
}
|
||||
}
|
||||
if (localMediaProgress.serverConnectionConfigId == null || DeviceManager.serverConnectionConfigId != localMediaProgress.serverConnectionConfigId) {
|
||||
var jsobj = JSObject()
|
||||
val jsobj = JSObject()
|
||||
jsobj.put("local", true)
|
||||
jsobj.put("server", false)
|
||||
jsobj.put("localMediaProgress", JSObject(lmpstring))
|
||||
@@ -298,25 +358,25 @@ class AbsDatabase : Plugin() {
|
||||
|
||||
@PluginMethod
|
||||
fun updateLocalTrackOrder(call:PluginCall) {
|
||||
var localLibraryItemId = call.getString("localLibraryItemId", "") ?: ""
|
||||
var localLibraryItem = DeviceManager.dbManager.getLocalLibraryItem(localLibraryItemId)
|
||||
val localLibraryItemId = call.getString("localLibraryItemId", "") ?: ""
|
||||
val localLibraryItem = DeviceManager.dbManager.getLocalLibraryItem(localLibraryItemId)
|
||||
if (localLibraryItem == null) {
|
||||
call.resolve()
|
||||
return
|
||||
}
|
||||
|
||||
var audioTracks = localLibraryItem.media.getAudioTracks() as MutableList
|
||||
val audioTracks = localLibraryItem.media.getAudioTracks() as MutableList
|
||||
|
||||
var tracks:JSArray = call.getArray("tracks") ?: JSArray()
|
||||
val tracks:JSArray = call.getArray("tracks") ?: JSArray()
|
||||
Log.d(tag, "updateLocalTrackOrder $tracks")
|
||||
|
||||
var index = 1
|
||||
var hasUpdates = false
|
||||
for (i in 0 until tracks.length()) {
|
||||
var track = tracks.getJSONObject(i)
|
||||
var localFileId = track.getString("localFileId")
|
||||
val track = tracks.getJSONObject(i)
|
||||
val localFileId = track.getString("localFileId")
|
||||
|
||||
var existingTrack = audioTracks.find{ it.localFileId == localFileId }
|
||||
val existingTrack = audioTracks.find{ it.localFileId == localFileId }
|
||||
if (existingTrack != null) {
|
||||
Log.d(tag, "Found existing track ${existingTrack.localFileId} that has index ${existingTrack.index} should be index $index")
|
||||
if (existingTrack.index != index) hasUpdates = true
|
||||
@@ -336,4 +396,15 @@ class AbsDatabase : Plugin() {
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun updateDeviceSettings(call:PluginCall) { // Returns device data
|
||||
Log.d(tag, "updateDeviceSettings ${call.data}")
|
||||
val newDeviceSettings = jacksonMapper.readValue<DeviceSettings>(call.data.toString())
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
DeviceManager.deviceData.deviceSettings = newDeviceSettings
|
||||
DeviceManager.dbManager.saveDeviceData(DeviceManager.deviceData)
|
||||
call.resolve(JSObject(jacksonMapper.writeValueAsString(DeviceManager.deviceData)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,31 +143,35 @@ class AbsDownloader : Plugin() {
|
||||
}
|
||||
|
||||
apiHandler.getLibraryItemWithProgress(libraryItemId, episodeId) { libraryItem ->
|
||||
Log.d(tag, "Got library item from server ${libraryItem.id}")
|
||||
if (libraryItem == null) {
|
||||
call.resolve(JSObject("{\"error\":\"Server request failed\"}"))
|
||||
} else {
|
||||
Log.d(tag, "Got library item from server ${libraryItem.id}")
|
||||
|
||||
val localFolder = DeviceManager.dbManager.getLocalFolder(localFolderId)
|
||||
if (localFolder != null) {
|
||||
val localFolder = DeviceManager.dbManager.getLocalFolder(localFolderId)
|
||||
if (localFolder != null) {
|
||||
|
||||
if (episodeId.isNotEmpty() && libraryItem.mediaType != "podcast") {
|
||||
Log.e(tag, "Library item is not a podcast but episode was requested")
|
||||
call.resolve(JSObject("{\"error\":\"Invalid library item not a podcast\"}"))
|
||||
} else if (episodeId.isNotEmpty()) {
|
||||
val podcast = libraryItem.media as Podcast
|
||||
val episode = podcast.episodes?.find { podcastEpisode ->
|
||||
podcastEpisode.id == episodeId
|
||||
}
|
||||
if (episode == null) {
|
||||
call.resolve(JSObject("{\"error\":\"Invalid podcast episode not found\"}"))
|
||||
if (episodeId.isNotEmpty() && libraryItem.mediaType != "podcast") {
|
||||
Log.e(tag, "Library item is not a podcast but episode was requested")
|
||||
call.resolve(JSObject("{\"error\":\"Invalid library item not a podcast\"}"))
|
||||
} else if (episodeId.isNotEmpty()) {
|
||||
val podcast = libraryItem.media as Podcast
|
||||
val episode = podcast.episodes?.find { podcastEpisode ->
|
||||
podcastEpisode.id == episodeId
|
||||
}
|
||||
if (episode == null) {
|
||||
call.resolve(JSObject("{\"error\":\"Invalid podcast episode not found\"}"))
|
||||
} else {
|
||||
startLibraryItemDownload(libraryItem, localFolder, episode)
|
||||
call.resolve()
|
||||
}
|
||||
} else {
|
||||
startLibraryItemDownload(libraryItem, localFolder, episode)
|
||||
startLibraryItemDownload(libraryItem, localFolder, null)
|
||||
call.resolve()
|
||||
}
|
||||
} else {
|
||||
startLibraryItemDownload(libraryItem, localFolder, null)
|
||||
call.resolve()
|
||||
call.resolve(JSObject("{\"error\":\"Local Folder Not Found\"}"))
|
||||
}
|
||||
} else {
|
||||
call.resolve(JSObject("{\"error\":\"Local Folder Not Found\"}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -277,7 +281,7 @@ class AbsDownloader : Plugin() {
|
||||
finalDestinationFile.delete()
|
||||
}
|
||||
|
||||
var downloadItemPart = DownloadItemPart.make(destinationFilename,destinationFile,finalDestinationFile,podcastTitle,serverPath,localFolder,audioTrack,null)
|
||||
var downloadItemPart = DownloadItemPart.make(destinationFilename,destinationFile,finalDestinationFile,podcastTitle,serverPath,localFolder,audioTrack,episode)
|
||||
downloadItem.downloadItemParts.add(downloadItemPart)
|
||||
|
||||
var dlRequest = downloadItemPart.getDownloadRequest()
|
||||
@@ -294,7 +298,7 @@ class AbsDownloader : Plugin() {
|
||||
if (finalDestinationFile.exists()) {
|
||||
Log.d(tag, "Podcast cover already exists - not downloading cover again")
|
||||
} else {
|
||||
downloadItemPart = DownloadItemPart.make(destinationFilename,destinationFile,finalDestinationFile,podcastTitle,serverPath,localFolder,audioTrack,null)
|
||||
downloadItemPart = DownloadItemPart.make(destinationFilename,destinationFile,finalDestinationFile,podcastTitle,serverPath,localFolder,null,null)
|
||||
downloadItem.downloadItemParts.add(downloadItemPart)
|
||||
|
||||
dlRequest = downloadItemPart.getDownloadRequest()
|
||||
@@ -397,9 +401,13 @@ class AbsDownloader : Plugin() {
|
||||
|
||||
Log.d(tag, "DOWNLOAD: Move file to final destination path: ${downloadItemPart.finalDestinationPath}")
|
||||
val localFolderFile = DocumentFileCompat.fromUri(mainActivity,Uri.parse(downloadItemPart.localFolderUrl))
|
||||
val mimetype = if (downloadItemPart.audioTrack != null) MimeType.AUDIO else MimeType.IMAGE
|
||||
val fileDescription = FileDescription(downloadItemPart.filename, downloadItemPart.itemTitle, mimetype)
|
||||
file?.moveFileTo(mainActivity,localFolderFile!!,fileDescription,fcb)
|
||||
if (localFolderFile == null) {
|
||||
Log.e(tag, "Local Folder File from uri is null")
|
||||
} else {
|
||||
val mimetype = if (downloadItemPart.audioTrack != null) MimeType.AUDIO else MimeType.IMAGE
|
||||
val fileDescription = FileDescription(downloadItemPart.filename, downloadItemPart.itemTitle, mimetype)
|
||||
file?.moveFileTo(mainActivity,localFolderFile,fileDescription,fcb)
|
||||
}
|
||||
} else {
|
||||
// Why is kotlin requiring an else here..
|
||||
}
|
||||
|
||||
@@ -19,11 +19,13 @@ import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class ApiHandler(var ctx:Context) {
|
||||
val tag = "ApiHandler"
|
||||
|
||||
private var client = OkHttpClient()
|
||||
private var defaultClient = OkHttpClient()
|
||||
private var pingClient = OkHttpClient.Builder().callTimeout(3, TimeUnit.SECONDS).build()
|
||||
var jacksonMapper = jacksonObjectMapper().enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature())
|
||||
|
||||
var storageSharedPreferences: SharedPreferences? = null
|
||||
@@ -33,11 +35,14 @@ class ApiHandler(var ctx:Context) {
|
||||
data class MediaProgressSyncResponsePayload(val numServerProgressUpdates:Int, val localProgressUpdates:List<LocalMediaProgress>)
|
||||
data class LocalMediaProgressSyncResultsPayload(var numLocalMediaProgressForServer:Int, var numServerProgressUpdates:Int, var numLocalProgressUpdates:Int)
|
||||
|
||||
fun getRequest(endpoint:String, cb: (JSObject) -> Unit) {
|
||||
fun getRequest(endpoint:String, httpClient:OkHttpClient?, config:ServerConnectionConfig?, cb: (JSObject) -> Unit) {
|
||||
val address = config?.address ?: DeviceManager.serverAddress
|
||||
val token = config?.token ?: DeviceManager.token
|
||||
|
||||
val request = Request.Builder()
|
||||
.url("${DeviceManager.serverAddress}$endpoint").addHeader("Authorization", "Bearer ${DeviceManager.token}")
|
||||
.url("${address}$endpoint").addHeader("Authorization", "Bearer $token")
|
||||
.build()
|
||||
makeRequest(request, cb)
|
||||
makeRequest(request, httpClient, cb)
|
||||
}
|
||||
|
||||
fun postRequest(endpoint:String, payload: JSObject, cb: (JSObject) -> Unit) {
|
||||
@@ -46,7 +51,7 @@ class ApiHandler(var ctx:Context) {
|
||||
val request = Request.Builder().post(requestBody)
|
||||
.url("${DeviceManager.serverAddress}$endpoint").addHeader("Authorization", "Bearer ${DeviceManager.token}")
|
||||
.build()
|
||||
makeRequest(request, cb)
|
||||
makeRequest(request, null, cb)
|
||||
}
|
||||
|
||||
fun patchRequest(endpoint:String, payload: JSObject, cb: (JSObject) -> Unit) {
|
||||
@@ -55,7 +60,7 @@ class ApiHandler(var ctx:Context) {
|
||||
val request = Request.Builder().patch(requestBody)
|
||||
.url("${DeviceManager.serverAddress}$endpoint").addHeader("Authorization", "Bearer ${DeviceManager.token}")
|
||||
.build()
|
||||
makeRequest(request, cb)
|
||||
makeRequest(request, null, cb)
|
||||
}
|
||||
|
||||
fun isOnline(): Boolean {
|
||||
@@ -76,19 +81,28 @@ class ApiHandler(var ctx:Context) {
|
||||
return false
|
||||
}
|
||||
|
||||
fun makeRequest(request:Request, cb: (JSObject) -> Unit) {
|
||||
fun makeRequest(request:Request, httpClient:OkHttpClient?, cb: (JSObject) -> Unit) {
|
||||
val client = httpClient ?: defaultClient
|
||||
client.newCall(request).enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) {
|
||||
Log.d(tag, "FAILURE TO CONNECT")
|
||||
e.printStackTrace()
|
||||
cb(JSObject())
|
||||
|
||||
val jsobj = JSObject()
|
||||
jsobj.put("error", "Failed to connect")
|
||||
cb(jsobj)
|
||||
}
|
||||
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
response.use {
|
||||
if (!it.isSuccessful) throw IOException("Unexpected code $response")
|
||||
if (!it.isSuccessful) {
|
||||
val jsobj = JSObject()
|
||||
jsobj.put("error", "Unexpected code $response")
|
||||
cb(jsobj)
|
||||
return
|
||||
}
|
||||
|
||||
val bodyString = it.body!!.string()
|
||||
val bodyString = it.body!!.string()
|
||||
if (bodyString == "OK") {
|
||||
cb(JSObject())
|
||||
} else {
|
||||
@@ -108,7 +122,7 @@ class ApiHandler(var ctx:Context) {
|
||||
|
||||
fun getLibraries(cb: (List<Library>) -> Unit) {
|
||||
val mapper = jacksonMapper
|
||||
getRequest("/api/libraries") {
|
||||
getRequest("/api/libraries", null,null) {
|
||||
val libraries = mutableListOf<Library>()
|
||||
if (it.has("value")) {
|
||||
val array = it.getJSONArray("value")
|
||||
@@ -121,24 +135,34 @@ class ApiHandler(var ctx:Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun getLibraryItem(libraryItemId:String, cb: (LibraryItem) -> Unit) {
|
||||
getRequest("/api/items/$libraryItemId?expanded=1") {
|
||||
val libraryItem = jacksonMapper.readValue<LibraryItem>(it.toString())
|
||||
cb(libraryItem)
|
||||
fun getLibraryItem(libraryItemId:String, cb: (LibraryItem?) -> Unit) {
|
||||
getRequest("/api/items/$libraryItemId?expanded=1", null, null) {
|
||||
if (it.has("error")) {
|
||||
Log.e(tag, it.getString("error") ?: "getLibraryItem Failed")
|
||||
cb(null)
|
||||
} else {
|
||||
val libraryItem = jacksonMapper.readValue<LibraryItem>(it.toString())
|
||||
cb(libraryItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getLibraryItemWithProgress(libraryItemId:String, episodeId:String?, cb: (LibraryItem) -> Unit) {
|
||||
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<LibraryItem>(it.toString())
|
||||
cb(libraryItem)
|
||||
getRequest(requestUrl, null, null) {
|
||||
if (it.has("error")) {
|
||||
Log.e(tag, it.getString("error") ?: "getLibraryItemWithProgress Failed")
|
||||
cb(null)
|
||||
} else {
|
||||
val libraryItem = jacksonMapper.readValue<LibraryItem>(it.toString())
|
||||
cb(libraryItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getLibraryItems(libraryId:String, cb: (List<LibraryItem>) -> Unit) {
|
||||
getRequest("/api/libraries/$libraryId/items?limit=100&minified=1") {
|
||||
getRequest("/api/libraries/$libraryId/items?limit=100&minified=1", null, null) {
|
||||
val items = mutableListOf<LibraryItem>()
|
||||
if (it.has("results")) {
|
||||
val array = it.getJSONArray("results")
|
||||
@@ -152,7 +176,7 @@ class ApiHandler(var ctx:Context) {
|
||||
}
|
||||
|
||||
fun getLibraryCategories(libraryId:String, cb: (List<LibraryCategory>) -> Unit) {
|
||||
getRequest("/api/libraries/$libraryId/personalized") {
|
||||
getRequest("/api/libraries/$libraryId/personalized", null, null) {
|
||||
val items = mutableListOf<LibraryCategory>()
|
||||
if (it.has("value")) {
|
||||
val array = it.getJSONArray("value")
|
||||
@@ -172,28 +196,32 @@ class ApiHandler(var ctx:Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fun playLibraryItem(libraryItemId:String, episodeId:String?, forceTranscode:Boolean, mediaPlayer:String, cb: (PlaybackSession) -> Unit) {
|
||||
val payload = JSObject()
|
||||
payload.put("mediaPlayer", mediaPlayer)
|
||||
|
||||
// Only if direct play fails do we force transcode
|
||||
if (!forceTranscode) payload.put("forceDirectPlay", true)
|
||||
else payload.put("forceTranscode", true)
|
||||
fun playLibraryItem(libraryItemId:String, episodeId:String?, playItemRequestPayload:PlayItemRequestPayload, cb: (PlaybackSession?) -> Unit) {
|
||||
val payload = JSObject(jacksonMapper.writeValueAsString(playItemRequestPayload))
|
||||
|
||||
val endpoint = if (episodeId.isNullOrEmpty()) "/api/items/$libraryItemId/play" else "/api/items/$libraryItemId/play/$episodeId"
|
||||
postRequest(endpoint, payload) {
|
||||
it.put("serverConnectionConfigId", DeviceManager.serverConnectionConfig?.id)
|
||||
it.put("serverAddress", DeviceManager.serverAddress)
|
||||
val playbackSession = jacksonMapper.readValue<PlaybackSession>(it.toString())
|
||||
cb(playbackSession)
|
||||
if (it.has("error")) {
|
||||
Log.e(tag, it.getString("error") ?: "Play Library Item Failed")
|
||||
cb(null)
|
||||
} else {
|
||||
it.put("serverConnectionConfigId", DeviceManager.serverConnectionConfig?.id)
|
||||
it.put("serverAddress", DeviceManager.serverAddress)
|
||||
val playbackSession = jacksonMapper.readValue<PlaybackSession>(it.toString())
|
||||
cb(playbackSession)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun sendProgressSync(sessionId:String, syncData: MediaProgressSyncData, cb: () -> Unit) {
|
||||
fun sendProgressSync(sessionId:String, syncData: MediaProgressSyncData, cb: (Boolean) -> Unit) {
|
||||
val payload = JSObject(jacksonMapper.writeValueAsString(syncData))
|
||||
|
||||
postRequest("/api/session/$sessionId/sync", payload) {
|
||||
cb()
|
||||
if (!it.getString("error").isNullOrEmpty()) {
|
||||
cb(false)
|
||||
} else {
|
||||
cb(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,10 +251,12 @@ class ApiHandler(var ctx:Context) {
|
||||
Log.d(tag, "Sending sync local progress request with ${localMediaProgress.size} progress items")
|
||||
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()}")
|
||||
Log.d(tag, "Media Progress Sync payload $payload - response ${it}")
|
||||
|
||||
if (it.toString() == "{}") {
|
||||
Log.e(tag, "Progress sync received empty object")
|
||||
} else if (it.has("error")) {
|
||||
Log.e(tag, it.getString("error") ?: "Progress sync error")
|
||||
} else {
|
||||
val progressSyncResponsePayload = jacksonMapper.readValue<MediaProgressSyncResponsePayload>(it.toString())
|
||||
|
||||
@@ -257,4 +287,45 @@ class ApiHandler(var ctx:Context) {
|
||||
cb()
|
||||
}
|
||||
}
|
||||
|
||||
fun getMediaProgress(libraryItemId:String, episodeId:String?, serverConnectionConfig:ServerConnectionConfig?, cb: (MediaProgress?) -> Unit) {
|
||||
val endpoint = if(episodeId.isNullOrEmpty()) "/api/me/progress/$libraryItemId" else "/api/me/progress/$libraryItemId/$episodeId"
|
||||
|
||||
// TODO: Using ping client here allows for shorter timeout (3 seconds), maybe rename or make diff client for requests requiring quicker response
|
||||
getRequest(endpoint, pingClient, serverConnectionConfig) {
|
||||
if (it.has("error")) {
|
||||
Log.e(tag, "getMediaProgress: Failed to get progress")
|
||||
cb(null)
|
||||
} else {
|
||||
val progress = jacksonMapper.readValue<MediaProgress>(it.toString())
|
||||
cb(progress)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getPlaybackSession(playbackSessionId:String, cb: (PlaybackSession?) -> Unit) {
|
||||
val endpoint = "/api/session/$playbackSessionId"
|
||||
getRequest(endpoint, null, null) {
|
||||
val err = it.getString("error")
|
||||
if (!err.isNullOrEmpty()) {
|
||||
cb(null)
|
||||
} else {
|
||||
cb(jacksonMapper.readValue<PlaybackSession>(it.toString()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun pingServer(config:ServerConnectionConfig, cb: (Boolean) -> Unit) {
|
||||
Log.d(tag, "pingServer: Pinging ${config.address}")
|
||||
getRequest("/ping", pingClient, config) {
|
||||
val success = it.getString("success")
|
||||
if (success.isNullOrEmpty()) {
|
||||
Log.d(tag, "pingServer: Ping ${config.address} Failed")
|
||||
cb(false)
|
||||
} else {
|
||||
Log.d(tag, "pingServer: Ping ${config.address} Successful")
|
||||
cb(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,5 @@
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M18,13c0,3.31 -2.69,6 -6,6s-6,-2.69 -6,-6s2.69,-6 6,-6v4l5,-5l-5,-5v4c-4.42,0 -8,3.58 -8,8c0,4.42 3.58,8 8,8s8,-3.58 8,-8H18z"/>
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M10.86,15.94l0,-4.27l-0.09,0l-1.77,0.63l0,0.69l1.01,-0.31l0,3.26z"/>
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M12.25,13.44v0.74c0,1.9 1.31,1.82 1.44,1.82c0.14,0 1.44,0.09 1.44,-1.82v-0.74c0,-1.9 -1.31,-1.82 -1.44,-1.82C13.55,11.62 12.25,11.53 12.25,13.44zM14.29,13.32v0.97c0,0.77 -0.21,1.03 -0.59,1.03c-0.38,0 -0.6,-0.26 -0.6,-1.03v-0.97c0,-0.75 0.22,-1.01 0.59,-1.01C14.07,12.3 14.29,12.57 14.29,13.32z"/>
|
||||
</group>
|
||||
</vector>
|
||||
|
||||
@@ -11,11 +11,5 @@
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M11.99,5V1l-5,5l5,5V7c3.31,0 6,2.69 6,6s-2.69,6 -6,6s-6,-2.69 -6,-6h-2c0,4.42 3.58,8 8,8s8,-3.58 8,-8S16.41,5 11.99,5z"/>
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M10.89,16h-0.85v-3.26l-1.01,0.31v-0.69l1.77,-0.63h0.09V16z"/>
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M15.17,14.24c0,0.32 -0.03,0.6 -0.1,0.82s-0.17,0.42 -0.29,0.57s-0.28,0.26 -0.45,0.33s-0.37,0.1 -0.59,0.1s-0.41,-0.03 -0.59,-0.1s-0.33,-0.18 -0.46,-0.33s-0.23,-0.34 -0.3,-0.57s-0.11,-0.5 -0.11,-0.82V13.5c0,-0.32 0.03,-0.6 0.1,-0.82s0.17,-0.42 0.29,-0.57s0.28,-0.26 0.45,-0.33s0.37,-0.1 0.59,-0.1s0.41,0.03 0.59,0.1c0.18,0.07 0.33,0.18 0.46,0.33s0.23,0.34 0.3,0.57s0.11,0.5 0.11,0.82V14.24zM14.32,13.38c0,-0.19 -0.01,-0.35 -0.04,-0.48s-0.07,-0.23 -0.12,-0.31s-0.11,-0.14 -0.19,-0.17s-0.16,-0.05 -0.25,-0.05s-0.18,0.02 -0.25,0.05s-0.14,0.09 -0.19,0.17s-0.09,0.18 -0.12,0.31s-0.04,0.29 -0.04,0.48v0.97c0,0.19 0.01,0.35 0.04,0.48s0.07,0.24 0.12,0.32s0.11,0.14 0.19,0.17s0.16,0.05 0.25,0.05s0.18,-0.02 0.25,-0.05s0.14,-0.09 0.19,-0.17s0.09,-0.19 0.11,-0.32s0.04,-0.29 0.04,-0.48V13.38z"/>
|
||||
</group>
|
||||
</vector>
|
||||
|
||||
@@ -10,9 +10,6 @@
|
||||
android:translateY="-1.5294118">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M4,6H2v14c0,1.1 0.9,2 2,2h14v-2H4V6z"/>
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M20,2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM20,12l-2.5,-1.5L15,12L15,4h5v8z"/>
|
||||
android:pathData="M10,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V8c0,-1.1 -0.9,-2 -2,-2h-8l-2,-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
|
Before Width: | Height: | Size: 276 B |
|
After Width: | Height: | Size: 216 B |
|
Before Width: | Height: | Size: 199 B |
|
After Width: | Height: | Size: 164 B |
|
Before Width: | Height: | Size: 309 B |
|
After Width: | Height: | Size: 254 B |
|
Before Width: | Height: | Size: 430 B |
|
After Width: | Height: | Size: 466 B |
@@ -2,6 +2,4 @@
|
||||
android:viewportHeight="24" android:viewportWidth="24"
|
||||
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="@android:color/white" android:pathData="M18,13c0,3.31 -2.69,6 -6,6s-6,-2.69 -6,-6s2.69,-6 6,-6v4l5,-5l-5,-5v4c-4.42,0 -8,3.58 -8,8c0,4.42 3.58,8 8,8s8,-3.58 8,-8H18z"/>
|
||||
<path android:fillColor="@android:color/white" android:pathData="M10.86,15.94l0,-4.27l-0.09,0l-1.77,0.63l0,0.69l1.01,-0.31l0,3.26z"/>
|
||||
<path android:fillColor="@android:color/white" android:pathData="M12.25,13.44v0.74c0,1.9 1.31,1.82 1.44,1.82c0.14,0 1.44,0.09 1.44,-1.82v-0.74c0,-1.9 -1.31,-1.82 -1.44,-1.82C13.55,11.62 12.25,11.53 12.25,13.44zM14.29,13.32v0.97c0,0.77 -0.21,1.03 -0.59,1.03c-0.38,0 -0.6,-0.26 -0.6,-1.03v-0.97c0,-0.75 0.22,-1.01 0.59,-1.01C14.07,12.3 14.29,12.57 14.29,13.32z"/>
|
||||
</vector>
|
||||
|
||||
@@ -2,6 +2,4 @@
|
||||
android:viewportHeight="24" android:viewportWidth="24"
|
||||
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="@android:color/white" android:pathData="M11.99,5V1l-5,5l5,5V7c3.31,0 6,2.69 6,6s-2.69,6 -6,6s-6,-2.69 -6,-6h-2c0,4.42 3.58,8 8,8s8,-3.58 8,-8S16.41,5 11.99,5z"/>
|
||||
<path android:fillColor="@android:color/white" android:pathData="M10.89,16h-0.85v-3.26l-1.01,0.31v-0.69l1.77,-0.63h0.09V16z"/>
|
||||
<path android:fillColor="@android:color/white" android:pathData="M15.17,14.24c0,0.32 -0.03,0.6 -0.1,0.82s-0.17,0.42 -0.29,0.57s-0.28,0.26 -0.45,0.33s-0.37,0.1 -0.59,0.1s-0.41,-0.03 -0.59,-0.1s-0.33,-0.18 -0.46,-0.33s-0.23,-0.34 -0.3,-0.57s-0.11,-0.5 -0.11,-0.82V13.5c0,-0.32 0.03,-0.6 0.1,-0.82s0.17,-0.42 0.29,-0.57s0.28,-0.26 0.45,-0.33s0.37,-0.1 0.59,-0.1s0.41,0.03 0.59,0.1c0.18,0.07 0.33,0.18 0.46,0.33s0.23,0.34 0.3,0.57s0.11,0.5 0.11,0.82V14.24zM14.32,13.38c0,-0.19 -0.01,-0.35 -0.04,-0.48s-0.07,-0.23 -0.12,-0.31s-0.11,-0.14 -0.19,-0.17s-0.16,-0.05 -0.25,-0.05s-0.18,0.02 -0.25,0.05s-0.14,0.09 -0.19,0.17s-0.09,0.18 -0.12,0.31s-0.04,0.29 -0.04,0.48v0.97c0,0.19 0.01,0.35 0.04,0.48s0.07,0.24 0.12,0.32s0.11,0.14 0.19,0.17s0.16,0.05 0.25,0.05s0.18,-0.02 0.25,-0.05s0.14,-0.09 0.19,-0.17s0.09,-0.19 0.11,-0.32s0.04,-0.29 0.04,-0.48V13.38z"/>
|
||||
</vector>
|
||||
|
||||
@@ -19,6 +19,3 @@ project(':capacitor-status-bar').projectDir = new File('../node_modules/@capacit
|
||||
|
||||
include ':capacitor-storage'
|
||||
project(':capacitor-storage').projectDir = new File('../node_modules/@capacitor/storage/android')
|
||||
|
||||
include ':robingenz-capacitor-app-update'
|
||||
project(':robingenz-capacitor-app-update').projectDir = new File('../node_modules/@robingenz/capacitor-app-update/android')
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
@import "./fonts.css";
|
||||
@import './defaultStyles.css';
|
||||
|
||||
body {
|
||||
background-color: #262626;
|
||||
@@ -16,6 +17,7 @@ body {
|
||||
min-height: calc(100% - 64px);
|
||||
max-height: calc(100% - 64px);
|
||||
}
|
||||
|
||||
#content.playerOpen {
|
||||
height: calc(100% - 164px);
|
||||
min-height: calc(100% - 164px);
|
||||
@@ -46,6 +48,7 @@ body {
|
||||
.box-shadow-book {
|
||||
box-shadow: 4px 1px 8px #11111166, -4px 1px 8px #11111166, 1px -4px 8px #11111166;
|
||||
}
|
||||
|
||||
.shadow-height {
|
||||
height: calc(100% - 4px);
|
||||
}
|
||||
@@ -53,6 +56,7 @@ body {
|
||||
.bookshelfRow {
|
||||
background-image: url(/wood_panels.jpg);
|
||||
}
|
||||
|
||||
.bookshelfDivider {
|
||||
background: rgb(149, 119, 90);
|
||||
background: linear-gradient(180deg, rgba(149, 119, 90, 1) 0%, rgba(103, 70, 37, 1) 17%, rgba(103, 70, 37, 1) 88%, rgba(71, 48, 25, 1) 100%);
|
||||
@@ -63,9 +67,9 @@ body {
|
||||
Bookshelf Label
|
||||
*/
|
||||
.categoryPlacard {
|
||||
background-image: url(https://image.freepik.com/free-photo/brown-wooden-textured-flooring-background_53876-128537.jpg);
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.shinyBlack {
|
||||
background-color: #2d3436;
|
||||
background-image: linear-gradient(315deg, #19191a 0%, rgb(15, 15, 15) 74%);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
|
||||
This is for setting regular html styles for places where embedding HTML will be
|
||||
like podcast episode descriptions. Otherwise TailwindCSS will have stripped all default markup.
|
||||
|
||||
*/
|
||||
|
||||
.default-style p {
|
||||
display: block;
|
||||
margin-block-start: 1em;
|
||||
margin-block-end: 1em;
|
||||
margin-inline-start: 0px;
|
||||
margin-inline-end: 0px;
|
||||
}
|
||||
|
||||
.default-style a {
|
||||
text-decoration: none;
|
||||
color: #5985ff;
|
||||
}
|
||||
|
||||
.default-style ul {
|
||||
display: block;
|
||||
list-style: circle;
|
||||
list-style-type: disc;
|
||||
margin-block-start: 1em;
|
||||
margin-block-end: 1em;
|
||||
margin-inline-start: 0px;
|
||||
margin-inline-end: 0px;
|
||||
padding-inline-start: 40px;
|
||||
}
|
||||
|
||||
.default-style ol {
|
||||
display: block;
|
||||
list-style: decimal;
|
||||
list-style-type: decimal;
|
||||
margin-block-start: 1em;
|
||||
margin-block-end: 1em;
|
||||
margin-inline-start: 0px;
|
||||
margin-inline-end: 0px;
|
||||
padding-inline-start: 40px;
|
||||
}
|
||||
|
||||
.default-style li {
|
||||
display: list-item;
|
||||
text-align: -webkit-match-parent;
|
||||
}
|
||||
|
||||
.default-style li::marker {
|
||||
unicode-bidi: isolate;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-transform: none;
|
||||
text-indent: 0px !important;
|
||||
text-align: start !important;
|
||||
text-align-last: start !important;
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
<a v-if="showBack" @click="back" class="rounded-full h-10 w-10 flex items-center justify-center hover:bg-white hover:bg-opacity-10 mr-2 cursor-pointer">
|
||||
<span class="material-icons text-3xl text-white">arrow_back</span>
|
||||
</a>
|
||||
<div v-if="user">
|
||||
<div v-if="user && currentLibrary">
|
||||
<div class="pl-3 pr-4 py-2 bg-bg bg-opacity-30 rounded-md flex items-center" @click="clickShowLibraryModal">
|
||||
<widgets-library-icon :icon="currentLibraryIcon" :size="4" />
|
||||
<p class="text-base font-book leading-4 ml-2 mt-0.5">{{ currentLibraryName }}</p>
|
||||
@@ -51,14 +51,11 @@ export default {
|
||||
this.$store.commit('setCastAvailable', val)
|
||||
}
|
||||
},
|
||||
socketConnected() {
|
||||
return this.$store.state.socketConnected
|
||||
},
|
||||
currentLibrary() {
|
||||
return this.$store.getters['libraries/getCurrentLibrary']
|
||||
},
|
||||
currentLibraryName() {
|
||||
return this.currentLibrary ? this.currentLibrary.name : 'Main'
|
||||
return this.currentLibrary ? this.currentLibrary.name : ''
|
||||
},
|
||||
currentLibraryIcon() {
|
||||
return this.currentLibrary ? this.currentLibrary.icon : 'database'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div v-if="playbackSession" id="streamContainer" class="fixed top-0 left-0 layout-wrapper right-0 z-50 pointer-events-none" :class="showFullscreen ? 'fullscreen' : ''">
|
||||
<div v-if="playbackSession" id="streamContainer" class="playerContainer fixed top-0 left-0 layout-wrapper right-0 z-50 pointer-events-none" :class="{ fullscreen: showFullscreen, 'ios-player': $platform === 'ios', 'web-player': $platform === 'web' }">
|
||||
<div v-if="showFullscreen" class="w-full h-full z-10 bg-bg absolute top-0 left-0 pointer-events-auto">
|
||||
<div class="top-2 left-4 absolute cursor-pointer">
|
||||
<span class="material-icons text-5xl" @click="collapseFullscreen">expand_more</span>
|
||||
@@ -30,18 +30,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="cover-wrapper absolute z-30 pointer-events-auto" :class="bookCoverAspectRatio === 1 ? 'square-cover' : ''" @click="clickContainer">
|
||||
<div class="cover-wrapper absolute z-30 pointer-events-auto" @click="clickContainer">
|
||||
<div class="cover-container bookCoverWrapper bg-black bg-opacity-75 w-full h-full">
|
||||
<covers-book-cover v-if="libraryItem || localLibraryItemCoverSrc" :library-item="libraryItem" :download-cover="localLibraryItemCoverSrc" :width="bookCoverWidth" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="title-author-texts absolute z-30 left-0 right-0 overflow-hidden">
|
||||
<div class="title-author-texts absolute z-30 left-0 right-0 overflow-hidden" @click="clickTitleAndAuthor">
|
||||
<p class="title-text font-book truncate">{{ title }}</p>
|
||||
<p class="author-text text-white text-opacity-75 truncate">by {{ authorName }}</p>
|
||||
</div>
|
||||
|
||||
<div id="streamContainer" class="w-full z-20 bg-primary absolute bottom-0 left-0 right-0 p-2 pointer-events-auto transition-all" @click="clickContainer">
|
||||
<div id="playerContent" class="playerContainer w-full z-20 bg-primary absolute bottom-0 left-0 right-0 p-2 pointer-events-auto transition-all" @click="clickContainer">
|
||||
<div v-if="showFullscreen" class="absolute top-0 left-0 right-0 w-full py-3 mx-auto px-3" style="max-width: 380px">
|
||||
<div class="flex items-center justify-between pointer-events-auto">
|
||||
<span v-if="!isPodcast && !isLocalPlayMethod" class="material-icons text-3xl text-white text-opacity-75 cursor-pointer" @click="$emit('showBookmarks')">{{ bookmarks.length ? 'bookmark' : 'bookmark_border' }}</span>
|
||||
@@ -63,23 +63,24 @@
|
||||
<div id="playerControls" class="absolute right-0 bottom-0 py-2">
|
||||
<div class="flex items-center justify-center">
|
||||
<span v-show="showFullscreen" class="material-icons next-icon text-white text-opacity-75 cursor-pointer" :class="isLoading ? 'text-opacity-10' : 'text-opacity-75'" @click.stop="jumpChapterStart">first_page</span>
|
||||
<span class="material-icons jump-icon text-white cursor-pointer" :class="isLoading ? 'text-opacity-10' : 'text-opacity-75'" @click.stop="backward10">replay_10</span>
|
||||
<span class="material-icons jump-icon text-white cursor-pointer" :class="isLoading ? 'text-opacity-10' : 'text-opacity-75'" @click.stop="jumpBackwards">{{ jumpBackwardsIcon }}</span>
|
||||
<div class="play-btn cursor-pointer shadow-sm flex items-center justify-center rounded-full text-primary mx-4" :class="{ 'animate-spin': seekLoading, 'bg-accent': !isLocalPlayMethod, 'bg-success': isLocalPlayMethod }" @mousedown.prevent @mouseup.prevent @click.stop="playPauseClick">
|
||||
<span v-if="!isLoading" class="material-icons">{{ seekLoading ? 'autorenew' : !isPlaying ? 'play_arrow' : 'pause' }}</span>
|
||||
<widgets-spinner-icon v-else class="h-8 w-8" />
|
||||
</div>
|
||||
<span class="material-icons jump-icon text-white cursor-pointer" :class="isLoading ? 'text-opacity-10' : 'text-opacity-75'" @click.stop="forward10">forward_10</span>
|
||||
<span class="material-icons jump-icon text-white cursor-pointer" :class="isLoading ? 'text-opacity-10' : 'text-opacity-75'" @click.stop="jumpForward">{{ jumpForwardIcon }}</span>
|
||||
<span v-show="showFullscreen" class="material-icons next-icon text-white cursor-pointer" :class="nextChapter && !isLoading ? 'text-opacity-75' : 'text-opacity-10'" @click.stop="jumpNextChapter">last_page</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="playerTrack" class="absolute bottom-0 left-0 w-full px-3">
|
||||
<div ref="track" class="h-2 w-full bg-gray-500 bg-opacity-50 relative" :class="isLoading ? 'animate-pulse' : ''" @click="clickTrack">
|
||||
<div ref="track" class="h-2 w-full bg-gray-500 bg-opacity-50 relative" :class="isLoading ? 'animate-pulse' : ''" @touchstart="touchstartTrack" @click="clickTrack">
|
||||
<div ref="readyTrack" class="h-full bg-gray-600 absolute top-0 left-0 pointer-events-none" />
|
||||
<div ref="bufferedTrack" class="h-full bg-gray-500 absolute top-0 left-0 pointer-events-none" />
|
||||
<div ref="playedTrack" class="h-full bg-gray-200 absolute top-0 left-0 pointer-events-none" />
|
||||
<div ref="draggingTrack" class="h-full bg-warning bg-opacity-25 absolute top-0 left-0 pointer-events-none" />
|
||||
</div>
|
||||
<div class="flex pt-0.5">
|
||||
<div id="timestamp-row" class="flex pt-0.5">
|
||||
<p class="font-mono text-white text-opacity-90" style="font-size: 0.8rem" ref="currentTimestamp">0:00</p>
|
||||
<div class="flex-grow" />
|
||||
<p v-show="showFullscreen" class="text-sm truncate text-white text-opacity-75" style="max-width: 65%">{{ currentChapterTitle }}</p>
|
||||
@@ -108,6 +109,7 @@ export default {
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
windowHeight: 0,
|
||||
playbackSession: null,
|
||||
showChapterModal: false,
|
||||
showFullscreen: false,
|
||||
@@ -121,7 +123,6 @@ export default {
|
||||
isEnded: false,
|
||||
volume: 0.5,
|
||||
readyTrackWidth: 0,
|
||||
playedTrackWidth: 0,
|
||||
seekedTime: 0,
|
||||
seekLoading: false,
|
||||
onPlaybackSessionListener: null,
|
||||
@@ -132,7 +133,15 @@ export default {
|
||||
touchStartTime: 0,
|
||||
touchEndY: 0,
|
||||
useChapterTrack: false,
|
||||
isLoading: false
|
||||
isLoading: false,
|
||||
touchTrackStart: false,
|
||||
dragPercent: 0
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
showFullscreen(val) {
|
||||
this.updateScreenSize()
|
||||
this.$store.commit('setPlayerFullscreen', !!val)
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@@ -150,14 +159,31 @@ export default {
|
||||
})
|
||||
return items
|
||||
},
|
||||
jumpForwardIcon() {
|
||||
return this.$store.getters['globals/getJumpForwardIcon'](this.jumpForwardTime)
|
||||
},
|
||||
jumpBackwardsIcon() {
|
||||
return this.$store.getters['globals/getJumpBackwardsIcon'](this.jumpBackwardsTime)
|
||||
},
|
||||
jumpForwardTime() {
|
||||
return this.$store.getters['getJumpForwardTime']
|
||||
},
|
||||
jumpBackwardsTime() {
|
||||
return this.$store.getters['getJumpBackwardsTime']
|
||||
},
|
||||
bookCoverAspectRatio() {
|
||||
return this.$store.getters['getBookCoverAspectRatio']
|
||||
},
|
||||
bookCoverWidth() {
|
||||
if (this.showFullscreen) return this.fullscreenBookCoverWidth
|
||||
return 60
|
||||
},
|
||||
fullscreenBookCoverWidth() {
|
||||
var heightScale = (this.windowHeight - 200) / 651
|
||||
if (this.bookCoverAspectRatio === 1) {
|
||||
return this.showFullscreen ? 260 : 60
|
||||
return 260 * heightScale
|
||||
}
|
||||
return this.showFullscreen ? 200 : 60
|
||||
return 200 * heightScale
|
||||
},
|
||||
showCastBtn() {
|
||||
return this.$store.state.isCastAvailable
|
||||
@@ -268,6 +294,18 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
clickTitleAndAuthor() {
|
||||
if (!this.showFullscreen) return
|
||||
const llid = this.libraryItem ? this.libraryItem.id : this.localLibraryItem ? this.localLibraryItem.id : null
|
||||
if (llid) {
|
||||
this.$router.push(`/item/${llid}`)
|
||||
this.showFullscreen = false
|
||||
}
|
||||
},
|
||||
touchstartTrack(e) {
|
||||
if (!e || !e.touches || !this.$refs.track || !this.showFullscreen) return
|
||||
this.touchTrackStart = true
|
||||
},
|
||||
selectChapter(chapter) {
|
||||
this.seek(chapter.start)
|
||||
this.showChapterModal = false
|
||||
@@ -324,13 +362,13 @@ export default {
|
||||
restart() {
|
||||
this.seek(0)
|
||||
},
|
||||
backward10() {
|
||||
jumpBackwards() {
|
||||
if (this.isLoading) return
|
||||
AbsAudioPlayer.seekBackward({ value: 10 })
|
||||
AbsAudioPlayer.seekBackward({ value: this.jumpBackwardsTime })
|
||||
},
|
||||
forward10() {
|
||||
jumpForward() {
|
||||
if (this.isLoading) return
|
||||
AbsAudioPlayer.seekForward({ value: 10 })
|
||||
AbsAudioPlayer.seekForward({ value: this.jumpForwardTime })
|
||||
},
|
||||
setStreamReady() {
|
||||
this.readyTrackWidth = this.trackWidth
|
||||
@@ -412,12 +450,8 @@ export default {
|
||||
bufferedPercent = (this.bufferedTime - this.currentChapter.start) / this.currentChapterDuration
|
||||
}
|
||||
var ptWidth = Math.round(percentDone * this.trackWidth)
|
||||
if (this.playedTrackWidth === ptWidth) {
|
||||
return
|
||||
}
|
||||
this.$refs.playedTrack.style.width = ptWidth + 'px'
|
||||
this.$refs.bufferedTrack.style.width = Math.round(bufferedPercent * this.trackWidth) + 'px'
|
||||
this.playedTrackWidth = ptWidth
|
||||
|
||||
if (this.useChapterTrack) {
|
||||
if (this.$refs.totalPlayedTrack) this.$refs.totalPlayedTrack.style.width = Math.round(totalPercentDone * this.trackWidth) + 'px'
|
||||
@@ -440,7 +474,6 @@ export default {
|
||||
var perc = time / this.totalDuration
|
||||
var ptWidth = Math.round(perc * this.trackWidth)
|
||||
this.$refs.playedTrack.style.width = ptWidth + 'px'
|
||||
this.playedTrackWidth = ptWidth
|
||||
|
||||
this.$refs.playedTrack.classList.remove('bg-gray-200')
|
||||
this.$refs.playedTrack.classList.add('bg-yellow-300')
|
||||
@@ -517,15 +550,60 @@ export default {
|
||||
this.touchStartTime = Date.now()
|
||||
},
|
||||
touchend(e) {
|
||||
if (!this.showFullscreen || !e.changedTouches) return
|
||||
if (!e.changedTouches) return
|
||||
|
||||
this.touchEndY = e.changedTouches[0].screenY
|
||||
var touchDuration = Date.now() - this.touchStartTime
|
||||
if (touchDuration > 1200) {
|
||||
// console.log('touch too long', touchDuration)
|
||||
return
|
||||
if (this.touchTrackStart) {
|
||||
var touch = e.changedTouches[0]
|
||||
const touchOnTrackPos = touch.pageX - 12
|
||||
const dragPercent = Math.max(0, Math.min(1, touchOnTrackPos / this.trackWidth))
|
||||
|
||||
var seekToTime = 0
|
||||
if (this.useChapterTrack && this.currentChapter) {
|
||||
const currChapTime = dragPercent * this.currentChapterDuration
|
||||
seekToTime = this.currentChapter.start + currChapTime
|
||||
} else {
|
||||
seekToTime = dragPercent * this.totalDuration
|
||||
}
|
||||
this.seek(seekToTime)
|
||||
|
||||
if (this.$refs.draggingTrack) {
|
||||
this.$refs.draggingTrack.style.width = '0px'
|
||||
}
|
||||
this.touchTrackStart = false
|
||||
} else if (this.showFullscreen) {
|
||||
this.touchEndY = e.changedTouches[0].screenY
|
||||
var touchDuration = Date.now() - this.touchStartTime
|
||||
if (touchDuration > 1200) {
|
||||
// console.log('touch too long', touchDuration)
|
||||
return
|
||||
}
|
||||
this.handleGesture()
|
||||
}
|
||||
},
|
||||
touchmove(e) {
|
||||
if (!this.touchTrackStart) return
|
||||
|
||||
var touch = e.touches[0]
|
||||
const touchOnTrackPos = touch.pageX - 12
|
||||
const dragPercent = Math.max(0, Math.min(1, touchOnTrackPos / this.trackWidth))
|
||||
this.dragPercent = dragPercent
|
||||
|
||||
if (this.$refs.draggingTrack) {
|
||||
this.$refs.draggingTrack.style.width = this.dragPercent * this.trackWidth + 'px'
|
||||
}
|
||||
|
||||
var ts = this.$refs.currentTimestamp
|
||||
if (ts) {
|
||||
var currTimeStr = ''
|
||||
if (this.useChapterTrack && this.currentChapter) {
|
||||
const currChapTime = dragPercent * this.currentChapterDuration
|
||||
currTimeStr = this.$secondsToTimestamp(currChapTime)
|
||||
} else {
|
||||
const dragTime = dragPercent * this.totalDuration
|
||||
currTimeStr = this.$secondsToTimestamp(dragTime)
|
||||
}
|
||||
ts.innerText = currTimeStr
|
||||
}
|
||||
this.handleGesture()
|
||||
},
|
||||
clickMenuAction(action) {
|
||||
if (action === 'chapter_track') {
|
||||
@@ -610,7 +688,6 @@ export default {
|
||||
})
|
||||
},
|
||||
onPlaybackClosed() {
|
||||
console.log('Received onPlaybackClosed evt')
|
||||
this.endPlayback()
|
||||
},
|
||||
onPlaybackFailed(data) {
|
||||
@@ -627,23 +704,48 @@ export default {
|
||||
this.onPlaybackFailedListener = AbsAudioPlayer.addListener('onPlaybackFailed', this.onPlaybackFailed)
|
||||
this.onPlayingUpdateListener = AbsAudioPlayer.addListener('onPlayingUpdate', this.onPlayingUpdate)
|
||||
this.onMetadataListener = AbsAudioPlayer.addListener('onMetadata', this.onMetadata)
|
||||
},
|
||||
screenOrientationChange() {
|
||||
setTimeout(this.updateScreenSize, 50)
|
||||
},
|
||||
updateScreenSize() {
|
||||
this.windowHeight = window.innerHeight
|
||||
var coverHeight = this.fullscreenBookCoverWidth * this.bookCoverAspectRatio
|
||||
document.documentElement.style.setProperty('--cover-image-width', this.fullscreenBookCoverWidth + 'px')
|
||||
document.documentElement.style.setProperty('--cover-image-height', coverHeight + 'px')
|
||||
},
|
||||
minimizePlayerEvt() {
|
||||
console.log('Minimize Player Evt')
|
||||
this.showFullscreen = false
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.updateScreenSize()
|
||||
if (screen.orientation) {
|
||||
screen.orientation.addEventListener('change', this.screenOrientationChange)
|
||||
}
|
||||
|
||||
this.$eventBus.$on('minimize-player', this.minimizePlayerEvt)
|
||||
document.body.addEventListener('touchstart', this.touchstart)
|
||||
document.body.addEventListener('touchend', this.touchend)
|
||||
|
||||
document.body.addEventListener('touchmove', this.touchmove)
|
||||
this.$nextTick(this.init)
|
||||
},
|
||||
beforeDestroy() {
|
||||
if (screen.orientation) {
|
||||
screen.orientation.removeEventListener('change', this.screenOrientationChange)
|
||||
}
|
||||
|
||||
if (this.playbackSession) {
|
||||
console.log('[AudioPlayer] Before destroy closing playback')
|
||||
this.closePlayback()
|
||||
}
|
||||
|
||||
this.forceCloseDropdownMenu()
|
||||
this.$eventBus.$off('minimize-player', this.minimizePlayerEvt)
|
||||
document.body.removeEventListener('touchstart', this.touchstart)
|
||||
document.body.removeEventListener('touchend', this.touchend)
|
||||
document.body.removeEventListener('touchmove', this.touchmove)
|
||||
|
||||
if (this.onPlayingUpdateListener) this.onPlayingUpdateListener.remove()
|
||||
if (this.onMetadataListener) this.onMetadataListener.remove()
|
||||
@@ -656,16 +758,24 @@ export default {
|
||||
</script>
|
||||
|
||||
<style>
|
||||
:root {
|
||||
--cover-image-width: 0px;
|
||||
--cover-image-height: 0px;
|
||||
--cover-image-width-collapsed: 60px;
|
||||
--cover-image-height-collapsed: 60px;
|
||||
}
|
||||
.bookCoverWrapper {
|
||||
box-shadow: 3px -2px 5px #00000066;
|
||||
}
|
||||
#streamContainer {
|
||||
box-shadow: 0px -8px 8px #11111155;
|
||||
.playerContainer {
|
||||
height: 100px;
|
||||
}
|
||||
.fullscreen #streamContainer {
|
||||
.fullscreen .playerContainer {
|
||||
height: 200px;
|
||||
}
|
||||
#playerContent {
|
||||
box-shadow: 0px -8px 8px #11111155;
|
||||
}
|
||||
|
||||
#playerTrack {
|
||||
transition: all 0.15s cubic-bezier(0.39, 0.575, 0.565, 1);
|
||||
@@ -676,18 +786,20 @@ export default {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.ios-player #timestamp-row {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
|
||||
.cover-wrapper {
|
||||
bottom: 44px;
|
||||
left: 12px;
|
||||
height: 96px;
|
||||
width: 60px;
|
||||
height: var(--cover-image-height-collapsed);
|
||||
width: var(--cover-image-width-collapsed);
|
||||
transition: all 0.25s cubic-bezier(0.39, 0.575, 0.565, 1);
|
||||
transition-property: left, bottom, width, height;
|
||||
transform-origin: left bottom;
|
||||
}
|
||||
.cover-wrapper.square-cover {
|
||||
height: 60px;
|
||||
}
|
||||
|
||||
.total-track {
|
||||
bottom: 215px;
|
||||
@@ -719,16 +831,18 @@ export default {
|
||||
}
|
||||
|
||||
.fullscreen .title-author-texts {
|
||||
bottom: 36%;
|
||||
bottom: calc(50% - var(--cover-image-height) / 2 + 50px);
|
||||
width: 80%;
|
||||
left: 10%;
|
||||
text-align: center;
|
||||
padding-bottom: calc(((260px - var(--cover-image-height)) / 260) * 40);
|
||||
pointer-events: auto;
|
||||
}
|
||||
.fullscreen .title-author-texts .title-text {
|
||||
font-size: 1.2rem;
|
||||
font-size: clamp(0.8rem, calc(var(--cover-image-height) / 260 * 20), 1.2rem);
|
||||
}
|
||||
.fullscreen .title-author-texts .author-text {
|
||||
font-size: 1rem;
|
||||
font-size: clamp(0.6rem, calc(var(--cover-image-height) / 260 * 16), 1rem);
|
||||
}
|
||||
|
||||
#playerControls {
|
||||
@@ -766,16 +880,11 @@ export default {
|
||||
}
|
||||
|
||||
.fullscreen .cover-wrapper {
|
||||
bottom: 46%;
|
||||
left: calc(50% - 100px);
|
||||
margin: 0 auto;
|
||||
height: 320px;
|
||||
width: 200px;
|
||||
}
|
||||
.fullscreen .cover-wrapper.square-cover {
|
||||
height: 260px;
|
||||
width: 260px;
|
||||
left: calc(50% - 130px);
|
||||
height: var(--cover-image-height);
|
||||
width: var(--cover-image-width);
|
||||
left: calc(50% - (calc(var(--cover-image-width)) / 2));
|
||||
bottom: calc(50% + 120px - (calc(var(--cover-image-height)) / 2));
|
||||
}
|
||||
|
||||
.fullscreen #playerControls {
|
||||
|
||||
@@ -30,9 +30,11 @@ export default {
|
||||
onSleepTimerEndedListener: null,
|
||||
onSleepTimerSetListener: null,
|
||||
onMediaPlayerChangedListener: null,
|
||||
onProgressSyncFailing: null,
|
||||
sleepInterval: null,
|
||||
currentEndOfChapterTime: 0,
|
||||
serverLibraryItemId: null
|
||||
serverLibraryItemId: null,
|
||||
syncFailedToast: null
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
@@ -183,11 +185,17 @@ export default {
|
||||
}
|
||||
AbsAudioPlayer.prepareLibraryItem({ libraryItemId, episodeId: null, playWhenReady: false, playbackRate })
|
||||
.then((data) => {
|
||||
console.log('Library item play response', JSON.stringify(data))
|
||||
AbsAudioPlayer.requestSession()
|
||||
if (data.error) {
|
||||
const errorMsg = data.error || 'Failed to play'
|
||||
this.$toast.error(errorMsg)
|
||||
} else {
|
||||
console.log('Library item play response', JSON.stringify(data))
|
||||
AbsAudioPlayer.requestSession()
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed', error)
|
||||
this.$toast.error('Failed to play')
|
||||
})
|
||||
},
|
||||
async playLibraryItem(payload) {
|
||||
@@ -218,15 +226,21 @@ export default {
|
||||
console.log('Called playLibraryItem', libraryItemId)
|
||||
AbsAudioPlayer.prepareLibraryItem({ libraryItemId, episodeId, playWhenReady: true, playbackRate })
|
||||
.then((data) => {
|
||||
console.log('Library item play response', JSON.stringify(data))
|
||||
if (!libraryItemId.startsWith('local')) {
|
||||
this.serverLibraryItemId = libraryItemId
|
||||
if (data.error) {
|
||||
const errorMsg = data.error || 'Failed to play'
|
||||
this.$toast.error(errorMsg)
|
||||
} else {
|
||||
this.serverLibraryItemId = serverLibraryItemId
|
||||
console.log('Library item play response', JSON.stringify(data))
|
||||
if (!libraryItemId.startsWith('local')) {
|
||||
this.serverLibraryItemId = libraryItemId
|
||||
} else {
|
||||
this.serverLibraryItemId = serverLibraryItemId
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed', error)
|
||||
this.$toast.error('Failed to play')
|
||||
})
|
||||
},
|
||||
pauseItem() {
|
||||
@@ -241,6 +255,10 @@ export default {
|
||||
onMediaPlayerChanged(data) {
|
||||
var mediaPlayer = data.value
|
||||
this.$store.commit('setMediaPlayer', mediaPlayer)
|
||||
},
|
||||
showProgressSyncIsFailing() {
|
||||
if (!isNaN(this.syncFailedToast)) this.$toast.dismiss(this.syncFailedToast)
|
||||
this.syncFailedToast = this.$toast('Progress is not being synced', { timeout: false, type: 'error' })
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
@@ -248,6 +266,7 @@ export default {
|
||||
this.onSleepTimerEndedListener = AbsAudioPlayer.addListener('onSleepTimerEnded', this.onSleepTimerEnded)
|
||||
this.onSleepTimerSetListener = AbsAudioPlayer.addListener('onSleepTimerSet', this.onSleepTimerSet)
|
||||
this.onMediaPlayerChangedListener = AbsAudioPlayer.addListener('onMediaPlayerChanged', this.onMediaPlayerChanged)
|
||||
this.onProgressSyncFailing = AbsAudioPlayer.addListener('onProgressSyncFailing', this.showProgressSyncIsFailing)
|
||||
|
||||
this.playbackSpeed = this.$store.getters['user/getUserSetting']('playbackRate')
|
||||
console.log(`[AudioPlayerContainer] Init Playback Speed: ${this.playbackSpeed}`)
|
||||
@@ -264,6 +283,7 @@ export default {
|
||||
if (this.onSleepTimerEndedListener) this.onSleepTimerEndedListener.remove()
|
||||
if (this.onSleepTimerSetListener) this.onSleepTimerSetListener.remove()
|
||||
if (this.onMediaPlayerChangedListener) this.onMediaPlayerChangedListener.remove()
|
||||
if (this.onProgressSyncFailing) this.onProgressSyncFailing.remove()
|
||||
|
||||
// if (this.$server.socket) {
|
||||
// this.$server.socket.off('stream_open', this.streamOpen)
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
</div>
|
||||
<div class="absolute bottom-0 left-0 w-full py-6 px-6 text-gray-300">
|
||||
<div v-if="serverConnectionConfig" class="mb-4 flex justify-center">
|
||||
<p class="text-xs">{{ serverConnectionConfig.address }}</p>
|
||||
<p class="text-xs" style="word-break: break-word">{{ serverConnectionConfig.address }} (v{{ serverSettings.version }})</p>
|
||||
</div>
|
||||
<div class="flex items-center">
|
||||
<p class="text-xs">{{ $config.version }}</p>
|
||||
@@ -71,12 +71,12 @@ export default {
|
||||
serverConnectionConfig() {
|
||||
return this.$store.state.user.serverConnectionConfig
|
||||
},
|
||||
serverSettings() {
|
||||
return this.$store.state.serverSettings || {}
|
||||
},
|
||||
username() {
|
||||
return this.user ? this.user.username : ''
|
||||
},
|
||||
socketConnected() {
|
||||
return this.$store.state.socketConnected
|
||||
},
|
||||
navItems() {
|
||||
var items = [
|
||||
{
|
||||
@@ -108,12 +108,12 @@ export default {
|
||||
text: 'Local Media',
|
||||
to: '/localMedia/folders'
|
||||
})
|
||||
// items.push({
|
||||
// icon: 'settings',
|
||||
// text: 'Settings',
|
||||
// to: '/settings'
|
||||
// })
|
||||
}
|
||||
items.push({
|
||||
icon: 'settings',
|
||||
text: 'Settings',
|
||||
to: '/settings'
|
||||
})
|
||||
return items
|
||||
},
|
||||
currentRoutePath() {
|
||||
@@ -125,11 +125,15 @@ export default {
|
||||
this.show = false
|
||||
},
|
||||
async logout() {
|
||||
await this.$axios.$post('/logout').catch((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
if (this.user) {
|
||||
await this.$axios.$post('/logout').catch((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
}
|
||||
|
||||
this.$socket.logout()
|
||||
await this.$db.logout()
|
||||
this.$localStore.removeLastLibraryId()
|
||||
this.$store.commit('user/logout')
|
||||
this.$router.push('/connect')
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<template v-for="shelf in totalShelves">
|
||||
<div :key="shelf" class="w-full px-2 relative" :class="showBookshelfListView ? '' : 'bookshelfRow'" :id="`shelf-${shelf - 1}`" :style="{ height: shelfHeight + 'px' }">
|
||||
<div v-if="!showBookshelfListView" class="bookshelfDivider w-full absolute bottom-0 left-0 z-30" style="min-height: 16px" :class="`h-${shelfDividerHeightIndex}`" />
|
||||
<div v-else class="flex border-t border-white border-opacity-10 my-3 py-1"/>
|
||||
<div v-else class="flex border-t border-white border-opacity-10" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -25,11 +25,12 @@ export default {
|
||||
mixins: [bookshelfCardsHelpers],
|
||||
data() {
|
||||
return {
|
||||
routeFullPath: null,
|
||||
entitiesPerShelf: 2,
|
||||
bookshelfHeight: 0,
|
||||
bookshelfWidth: 0,
|
||||
bookshelfMarginLeft: 0,
|
||||
shelvesPerPage: 0,
|
||||
entitiesPerShelf: 2,
|
||||
currentPage: 0,
|
||||
booksPerFetch: 20,
|
||||
initialized: false,
|
||||
@@ -72,6 +73,7 @@ export default {
|
||||
return this.page
|
||||
},
|
||||
hasFilter() {
|
||||
if (this.page === 'series' || this.page === 'collections') return false
|
||||
return this.filterBy !== 'all'
|
||||
},
|
||||
orderBy() {
|
||||
@@ -83,14 +85,11 @@ export default {
|
||||
filterBy() {
|
||||
return this.$store.getters['user/getUserSetting']('mobileFilterBy')
|
||||
},
|
||||
coverAspectRatio() {
|
||||
return this.$store.getters['getServerSetting']('coverAspectRatio')
|
||||
},
|
||||
isCoverSquareAspectRatio() {
|
||||
return this.coverAspectRatio === this.$constants.BookCoverAspectRatio.SQUARE
|
||||
return this.bookCoverAspectRatio === 1
|
||||
},
|
||||
bookCoverAspectRatio() {
|
||||
return this.isCoverSquareAspectRatio ? 1 : 1.6
|
||||
return this.$store.getters['getBookCoverAspectRatio']
|
||||
},
|
||||
bookWidth() {
|
||||
var coverSize = 100
|
||||
@@ -119,7 +118,7 @@ export default {
|
||||
return this.$store.getters['libraries/getCurrentLibraryMediaType']
|
||||
},
|
||||
shelfHeight() {
|
||||
if (this.showBookshelfListView) return this.entityHeight
|
||||
if (this.showBookshelfListView) return this.entityHeight + 16
|
||||
return this.entityHeight + 40
|
||||
},
|
||||
totalEntityCardWidth() {
|
||||
@@ -300,10 +299,12 @@ export default {
|
||||
this.bookshelfHeight = clientHeight
|
||||
this.bookshelfWidth = clientWidth
|
||||
this.entitiesPerShelf = this.showBookshelfListView ? 1 : Math.floor((this.bookshelfWidth - 16) / this.totalEntityCardWidth)
|
||||
|
||||
this.shelvesPerPage = Math.ceil(this.bookshelfHeight / this.shelfHeight) + 2
|
||||
this.bookshelfMarginLeft = (this.bookshelfWidth - this.entitiesPerShelf * this.totalEntityCardWidth) / 2
|
||||
|
||||
const entitiesPerPage = this.shelvesPerPage * this.entitiesPerShelf
|
||||
this.booksPerFetch = Math.ceil(entitiesPerPage / 20) * 20 // Round up to the nearest 20
|
||||
|
||||
if (this.totalEntities) {
|
||||
this.totalShelves = Math.ceil(this.totalEntities / this.entitiesPerShelf)
|
||||
}
|
||||
@@ -320,6 +321,15 @@ export default {
|
||||
await this.loadPage(0)
|
||||
var lastBookIndex = Math.min(this.totalEntities, this.shelvesPerPage * this.entitiesPerShelf)
|
||||
this.mountEntites(0, lastBookIndex)
|
||||
|
||||
// Set last scroll position for this bookshelf page
|
||||
if (this.$store.state.lastBookshelfScrollData[this.page] && window['bookshelf-wrapper']) {
|
||||
const { path, scrollTop } = this.$store.state.lastBookshelfScrollData[this.page]
|
||||
if (path === this.routeFullPath) {
|
||||
// Exact path match with query so use scroll position
|
||||
window['bookshelf-wrapper'].scrollTop = scrollTop
|
||||
}
|
||||
}
|
||||
},
|
||||
scroll(e) {
|
||||
if (!e || !e.target) return
|
||||
@@ -362,6 +372,8 @@ export default {
|
||||
if (newSearchParams !== this.currentSFQueryString || newSearchParams !== currentQueryString) {
|
||||
let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + newSearchParams
|
||||
window.history.replaceState({ path: newurl }, '', newurl)
|
||||
|
||||
this.routeFullPath = window.location.pathname + (window.location.search || '') // Update for saving scroll position
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -373,7 +385,7 @@ export default {
|
||||
this.resetEntities()
|
||||
}
|
||||
},
|
||||
libraryChanged(libid) {
|
||||
libraryChanged() {
|
||||
if (this.hasFilter) {
|
||||
this.clearFilter()
|
||||
} else {
|
||||
@@ -456,12 +468,22 @@ export default {
|
||||
this.$socket.$off('items_added', this.libraryItemsAdded)
|
||||
}
|
||||
},
|
||||
updated() {
|
||||
this.routeFullPath = window.location.pathname + (window.location.search || '')
|
||||
},
|
||||
mounted() {
|
||||
this.routeFullPath = window.location.pathname + (window.location.search || '')
|
||||
|
||||
this.init()
|
||||
this.initListeners()
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.removeListeners()
|
||||
|
||||
// Set bookshelf scroll position for specific bookshelf page and query
|
||||
if (window['bookshelf-wrapper']) {
|
||||
this.$store.commit('setLastBookshelfScrollData', { scrollTop: window['bookshelf-wrapper'].scrollTop || 0, path: this.routeFullPath, name: this.page })
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -353,7 +353,34 @@ export default {
|
||||
this.isSelectionMode = val
|
||||
if (!val) this.selected = false
|
||||
},
|
||||
setEntity(libraryItem) {
|
||||
setEntity(_libraryItem) {
|
||||
var libraryItem = _libraryItem
|
||||
|
||||
// this code block is only necessary when showing a selected series with sequence #
|
||||
// it will update the selected series so we get realtime updates for series sequence changes
|
||||
if (this.series) {
|
||||
// i know.. but the libraryItem passed to this func cannot be modified so we need to create a copy
|
||||
libraryItem = {
|
||||
..._libraryItem,
|
||||
media: {
|
||||
..._libraryItem.media,
|
||||
metadata: {
|
||||
..._libraryItem.media.metadata
|
||||
}
|
||||
}
|
||||
}
|
||||
var mediaMetadata = libraryItem.media.metadata
|
||||
if (mediaMetadata.series) {
|
||||
var newSeries = mediaMetadata.series.find((se) => se.id === this.series.id)
|
||||
if (newSeries) {
|
||||
// update selected series
|
||||
libraryItem.media.metadata.series = newSeries
|
||||
this.libraryItem = libraryItem
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.libraryItem = libraryItem
|
||||
},
|
||||
setLocalLibraryItem(localLibraryItem) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="w-full max-w-md mx-auto px-4 sm:px-6 lg:px-8 z-10">
|
||||
<div v-show="!loggedIn" class="mt-8 bg-primary overflow-hidden shadow rounded-lg p-6 w-full">
|
||||
<div class="w-full max-w-md mx-auto px-2 sm:px-4 lg:px-8 z-10">
|
||||
<div v-show="!loggedIn" class="mt-8 bg-primary overflow-hidden shadow rounded-lg px-4 py-6 w-full">
|
||||
<template v-if="!showForm">
|
||||
<div v-for="config in serverConnectionConfigs" :key="config.id" class="flex items-center py-4 my-1 border-b border-white border-opacity-10 relative" @click="connectToServer(config)">
|
||||
<span class="material-icons-outlined text-xl text-gray-300">dns</span>
|
||||
@@ -17,9 +17,14 @@
|
||||
<div v-else class="w-full">
|
||||
<form v-show="!showAuth" @submit.prevent="submit" novalidate class="w-full">
|
||||
<h2 class="text-lg leading-7 mb-2">Server address</h2>
|
||||
<ui-text-input v-model="serverConfig.address" :disabled="processing || !networkConnected || serverConfig.id" placeholder="http://55.55.55.55:13378" type="url" class="w-full sm:w-72 h-10" />
|
||||
<div class="flex justify-end">
|
||||
<ui-btn :disabled="processing || !networkConnected" type="submit" :padding-x="3" class="h-10 mt-4">{{ networkConnected ? 'Submit' : 'No Internet' }}</ui-btn>
|
||||
<ui-text-input v-model="serverConfig.address" :disabled="processing || !networkConnected || !!serverConfig.id" placeholder="http://55.55.55.55:13378" type="url" class="w-full h-10" />
|
||||
<div class="flex justify-end items-center mt-6">
|
||||
<!-- <div class="relative flex">
|
||||
<button class="outline-none uppercase tracking-wide font-semibold text-xs text-gray-300" type="button" @click="addCustomHeaders">Add Custom Headers</button>
|
||||
<div v-if="numCustomHeaders" class="rounded-full h-5 w-5 flex items-center justify-center text-xs bg-success bg-opacity-40 leading-3 font-semibold font-mono ml-1">{{ numCustomHeaders }}</div>
|
||||
</div> -->
|
||||
|
||||
<ui-btn :disabled="processing || !networkConnected" type="submit" :padding-x="3" class="h-10">{{ networkConnected ? 'Submit' : 'No Internet' }}</ui-btn>
|
||||
</div>
|
||||
</form>
|
||||
<template v-if="showAuth">
|
||||
@@ -62,6 +67,8 @@
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<modals-custom-headers-modal v-model="showAddCustomHeaders" :custom-headers.sync="serverConfig.customHeaders" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -69,23 +76,26 @@
|
||||
import { Dialog } from '@capacitor/dialog'
|
||||
|
||||
export default {
|
||||
props: {},
|
||||
data() {
|
||||
return {
|
||||
deviceData: null,
|
||||
loggedIn: false,
|
||||
showAuth: false,
|
||||
processing: false,
|
||||
serverConfig: {
|
||||
address: null,
|
||||
username: null
|
||||
username: null,
|
||||
customHeaders: null
|
||||
},
|
||||
password: null,
|
||||
error: null,
|
||||
showForm: false
|
||||
showForm: false,
|
||||
showAddCustomHeaders: false
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
deviceData() {
|
||||
return this.$store.state.deviceData || {}
|
||||
},
|
||||
networkConnected() {
|
||||
return this.$store.state.networkConnected
|
||||
},
|
||||
@@ -98,9 +108,16 @@ export default {
|
||||
lastServerConnectionConfig() {
|
||||
if (!this.lastServerConnectionConfigId || !this.serverConnectionConfigs.length) return null
|
||||
return this.serverConnectionConfigs.find((s) => s.id == this.lastServerConnectionConfigId)
|
||||
},
|
||||
numCustomHeaders() {
|
||||
if (!this.serverConfig.customHeaders) return 0
|
||||
return Object.keys(this.serverConfig.customHeaders).length
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
addCustomHeaders() {
|
||||
this.showAddCustomHeaders = true
|
||||
},
|
||||
showServerList() {
|
||||
this.showForm = false
|
||||
this.showAuth = false
|
||||
@@ -147,7 +164,10 @@ export default {
|
||||
if (value) {
|
||||
this.processing = true
|
||||
await this.$db.removeServerConnectionConfig(this.serverConfig.id)
|
||||
this.deviceData.serverConnectionConfigs = this.deviceData.serverConnectionConfigs.filter((scc) => scc.id != this.serverConfig.id)
|
||||
const updatedDeviceData = { ...this.deviceData }
|
||||
updatedDeviceData.serverConnectionConfigs = this.deviceData.serverConnectionConfigs.filter((scc) => scc.id != this.serverConfig.id)
|
||||
this.$store.commit('setDeviceData', updatedDeviceData)
|
||||
|
||||
this.serverConfig = {
|
||||
address: null,
|
||||
userId: null,
|
||||
@@ -165,7 +185,6 @@ export default {
|
||||
}
|
||||
this.showForm = true
|
||||
this.showAuth = true
|
||||
console.log('Edit server config', serverConfig)
|
||||
},
|
||||
newServerConfigClick() {
|
||||
this.serverConfig = {
|
||||
@@ -192,9 +211,13 @@ export default {
|
||||
return null
|
||||
}
|
||||
},
|
||||
pingServerAddress(address) {
|
||||
pingServerAddress(address, customHeaders) {
|
||||
const options = { timeout: 3000 }
|
||||
if (customHeaders) {
|
||||
options.headers = customHeaders
|
||||
}
|
||||
return this.$axios
|
||||
.$get(`${address}/ping`, { timeout: 3000 })
|
||||
.$get(`${address}/ping`, options)
|
||||
.then((data) => data.success)
|
||||
.catch((error) => {
|
||||
console.error('Server check failed', error)
|
||||
@@ -203,8 +226,12 @@ export default {
|
||||
})
|
||||
},
|
||||
requestServerLogin() {
|
||||
const options = {}
|
||||
if (this.serverConfig.customHeaders) {
|
||||
options.headers = this.serverConfig.customHeaders
|
||||
}
|
||||
return this.$axios
|
||||
.$post(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password })
|
||||
.$post(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password }, options)
|
||||
.then((data) => {
|
||||
if (!data.user) {
|
||||
console.error(data.error)
|
||||
@@ -236,7 +263,7 @@ export default {
|
||||
this.processing = true
|
||||
this.error = null
|
||||
|
||||
var success = await this.pingServerAddress(this.serverConfig.address)
|
||||
var success = await this.pingServerAddress(this.serverConfig.address, this.serverConfig.customHeaders)
|
||||
this.processing = false
|
||||
if (success) this.showAuth = true
|
||||
},
|
||||
@@ -246,6 +273,12 @@ export default {
|
||||
this.error = 'Invalid username'
|
||||
return
|
||||
}
|
||||
const duplicateConfig = this.serverConnectionConfigs.find((scc) => scc.address === this.serverConfig.address && scc.username === this.serverConfig.username)
|
||||
if (duplicateConfig) {
|
||||
this.error = 'Config already exists for this address and username'
|
||||
return
|
||||
}
|
||||
|
||||
this.error = null
|
||||
this.processing = true
|
||||
|
||||
@@ -298,8 +331,6 @@ export default {
|
||||
return authRes
|
||||
},
|
||||
async init() {
|
||||
this.deviceData = await this.$db.getDeviceData()
|
||||
|
||||
if (this.lastServerConnectionConfig) {
|
||||
this.connectToServer(this.lastServerConnectionConfig)
|
||||
} else {
|
||||
|
||||
@@ -54,16 +54,16 @@ export default {
|
||||
updatedAt() {
|
||||
return this._author.updatedAt
|
||||
},
|
||||
serverAddres() {
|
||||
serverAddress() {
|
||||
return this.$store.getters['user/getServerAddress']
|
||||
},
|
||||
imgSrc() {
|
||||
if (!this.imagePath || !this.serverAddres) return null
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
if (!this.imagePath || !this.serverAddress) return null
|
||||
if (process.env.NODE_ENV !== 'production' && this.serverAddress.startsWith('http://192.168')) {
|
||||
// Testing
|
||||
return `http://localhost:3333/api/authors/${this.authorId}/image?token=${this.userToken}&ts=${this.updatedAt}`
|
||||
}
|
||||
return `${this.serverAddres}/api/authors/${this.authorId}/image?token=${this.userToken}&ts=${this.updatedAt}`
|
||||
return `${this.serverAddress}/api/authors/${this.authorId}/image?token=${this.userToken}&ts=${this.updatedAt}`
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<div class="absolute cover-bg" ref="coverBg" />
|
||||
</div>
|
||||
|
||||
<img v-if="fullCoverUrl" ref="cover" :src="fullCoverUrl" loading="lazy" @error="imageError" @load="imageLoaded" class="w-full h-full absolute top-0 left-0 z-10 duration-300 transition-opacity" :style="{ opacity: imageReady ? 1 : 0 }" :class="showCoverBg && !hasCover ? 'object-contain' : 'object-fill'" />
|
||||
<img v-if="fullCoverUrl" ref="cover" :src="fullCoverUrl" loading="lazy" @error="imageError" @load="imageLoaded" class="w-full h-full absolute top-0 left-0 z-10 duration-300 transition-opacity" :style="{ opacity: imageReady ? 1 : 0 }" :class="showCoverBg && hasCover ? 'object-contain' : 'object-fill'" />
|
||||
|
||||
<div v-show="loading && libraryItem" class="absolute top-0 left-0 h-full w-full flex items-center justify-center">
|
||||
<p class="font-book text-center" :style="{ fontSize: 0.75 * sizeMultiplier + 'rem' }">{{ title }}</p>
|
||||
@@ -121,7 +121,7 @@ export default {
|
||||
return this.media.coverPath || this.placeholderUrl
|
||||
},
|
||||
hasCover() {
|
||||
return !!this.media.coverPath || this.localCover || this.downloadCover
|
||||
return (!!this.media.coverPath && !this.isLocal) || this.localCover || this.downloadCover
|
||||
},
|
||||
sizeMultiplier() {
|
||||
var baseSize = this.squareAspectRatio ? 128 : 96
|
||||
|
||||
@@ -83,11 +83,7 @@ export default {
|
||||
this.$emit('input', val)
|
||||
}
|
||||
},
|
||||
isConnected() {
|
||||
return this.$store.state.socketConnected
|
||||
},
|
||||
canCreateBookmark() {
|
||||
if (!this.isConnected) return false
|
||||
return !this.bookmarks.find((bm) => bm.time === this.currentTime)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<template>
|
||||
<modals-modal v-model="show" :width="'90%'" :max-width="'420px'" height="100%">
|
||||
<template #outer>
|
||||
<div class="absolute top-5 left-4 z-40">
|
||||
<p class="text-white text-2xl truncate">Custom Headers</p>
|
||||
</div>
|
||||
</template>
|
||||
<div class="w-full h-full overflow-hidden absolute top-0 left-0 flex items-center justify-center" @click="show = false">
|
||||
<div ref="container" class="w-full rounded-lg bg-primary border border-white border-opacity-20 overflow-y-auto overflow-x-hidden" style="max-height: 80vh" @click.stop>
|
||||
<div class="w-full h-full p-4" v-if="showAddHeader">
|
||||
<div class="mb-4">
|
||||
<ui-icon-btn icon="arrow_back" borderless @click="showAddHeader = false" />
|
||||
</div>
|
||||
<form @submit.prevent="submitForm">
|
||||
<ui-text-input-with-label v-model="newHeaderKey" label="Name" class="mb-2" />
|
||||
<ui-text-input-with-label v-model="newHeaderValue" label="Value" class="mb-4" />
|
||||
|
||||
<ui-btn type="submit" class="w-full">Submit</ui-btn>
|
||||
</form>
|
||||
</div>
|
||||
<div class="w-full h-full p-4" v-else>
|
||||
<template v-for="[key, value] in Object.entries(headersCopy)">
|
||||
<div :key="key" class="w-full rounded-lg bg-white bg-opacity-5 py-2 pl-4 pr-12 relative mb-2">
|
||||
<p class="text-base font-semibold text-gray-200 leading-5">{{ key }}</p>
|
||||
<p class="text-sm text-gray-400">{{ value }}</p>
|
||||
|
||||
<div class="absolute top-0 bottom-0 right-0 h-full p-4 flex items-center justify-center text-error">
|
||||
<button @click="removeHeader(key)"><span class="material-icons text-lg">delete</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="!Object.keys(headersCopy).length" class="py-4 text-center">No Custom Headers</p>
|
||||
|
||||
<div class="w-full flex justify-center pt-4">
|
||||
<ui-btn @click="showAddHeader = true" class="w-full">Add Custom Header</ui-btn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</modals-modal>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
value: Boolean,
|
||||
customHeaders: {
|
||||
type: Object,
|
||||
default: () => {}
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
newHeaderKey: '',
|
||||
newHeaderValue: '',
|
||||
headersCopy: {},
|
||||
showAddHeader: false
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
show(val) {
|
||||
if (val) this.init()
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
show: {
|
||||
get() {
|
||||
return this.value
|
||||
},
|
||||
set(val) {
|
||||
this.$emit('input', val)
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
removeHeader(key) {
|
||||
this.$delete(this.headersCopy, key)
|
||||
this.$emit('update:customHeaders', { ...this.headersCopy })
|
||||
},
|
||||
submitForm() {
|
||||
console.log('Submit form', this.newHeaderKey, this.newHeaderValue)
|
||||
this.headersCopy[this.newHeaderKey] = this.newHeaderValue
|
||||
this.newHeaderKey = ''
|
||||
this.newHeaderValue = ''
|
||||
this.showAddHeader = false
|
||||
this.$emit('update:customHeaders', { ...this.headersCopy })
|
||||
},
|
||||
init() {
|
||||
this.newHeaderKey = ''
|
||||
this.newHeaderValue = ''
|
||||
this.headersCopy = this.customHeaders ? { ...this.customHeaders } : {}
|
||||
}
|
||||
},
|
||||
mounted() {}
|
||||
}
|
||||
</script>
|
||||
@@ -10,7 +10,7 @@
|
||||
<div ref="container" class="w-full overflow-x-hidden overflow-y-auto bg-primary rounded-lg border border-white border-opacity-20" style="max-height: 75%" @click.stop>
|
||||
<ul class="h-full w-full" role="listbox" aria-labelledby="listbox-label">
|
||||
<template v-for="item in items">
|
||||
<li :key="item.value" class="text-gray-50 select-none relative py-4 cursor-pointer hover:bg-black-400" role="option" @click="clickedOption(item.value)">
|
||||
<li :key="item.value" class="text-gray-50 select-none relative py-4 cursor-pointer hover:bg-black-400" :class="selected === item.value ? 'bg-success bg-opacity-10' : ''" role="option" @click="clickedOption(item.value)">
|
||||
<div class="relative flex items-center px-3">
|
||||
<p class="font-normal block truncate text-base text-white text-opacity-80">{{ item.text }}</p>
|
||||
</div>
|
||||
@@ -30,7 +30,8 @@ export default {
|
||||
items: {
|
||||
type: Array,
|
||||
default: () => []
|
||||
}
|
||||
},
|
||||
selected: String // optional
|
||||
},
|
||||
data() {
|
||||
return {}
|
||||
|
||||
@@ -166,7 +166,7 @@ export default {
|
||||
return this.filterData.narrators || []
|
||||
},
|
||||
progress() {
|
||||
return ['Finished', 'In Progress', 'Not Started']
|
||||
return ['Finished', 'In Progress', 'Not Started', 'Not Finished']
|
||||
},
|
||||
sublistItems() {
|
||||
return (this[this.sublist] || []).map((item) => {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<template>
|
||||
<modals-modal v-model="show" width="100%" height="100%" max-width="100%">
|
||||
<div class="w-full h-full overflow-hidden absolute top-0 left-0 flex items-center justify-center" @click="show = false">
|
||||
<covers-book-cover :library-item="libraryItem" :width="width" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
</div>
|
||||
</modals-modal>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
value: Boolean,
|
||||
libraryItem: {
|
||||
type: Object,
|
||||
default: () => {}
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
width: 0
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
show(val) {
|
||||
if (val) {
|
||||
this.setWidth()
|
||||
this.setListeners()
|
||||
} else {
|
||||
this.removeListeners()
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
show: {
|
||||
get() {
|
||||
return this.value
|
||||
},
|
||||
set(val) {
|
||||
this.$emit('input', val)
|
||||
}
|
||||
},
|
||||
bookCoverAspectRatio() {
|
||||
return this.$store.getters['getBookCoverAspectRatio']
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
screenOrientationChange() {
|
||||
setTimeout(this.setWidth, 50)
|
||||
},
|
||||
setListeners() {
|
||||
screen.orientation.addEventListener('change', this.screenOrientationChange)
|
||||
},
|
||||
removeListeners() {
|
||||
screen.orientation.removeEventListener('change', this.screenOrientationChange)
|
||||
},
|
||||
setWidth() {
|
||||
if (window.innerHeight > window.innerWidth) {
|
||||
this.width = window.innerWidth
|
||||
} else {
|
||||
this.width = window.innerHeight / this.bookCoverAspectRatio
|
||||
}
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.setWidth()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.filter-modal-wrapper {
|
||||
max-height: calc(100% - 320px);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<modals-modal v-model="show" :width="400" height="100%">
|
||||
<template #outer>
|
||||
<div class="absolute top-5 left-4 z-40">
|
||||
<p class="text-white text-2xl truncate">Details</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="w-full h-full overflow-hidden absolute top-0 left-0 flex items-center justify-center" @click="show = false">
|
||||
<div class="w-full overflow-x-hidden overflow-y-auto bg-primary rounded-lg border border-white border-opacity-20 p-2" style="max-height: 75%" @click.stop>
|
||||
<p class="mb-1">{{ mediaMetadata.title }}</p>
|
||||
<p class="mb-1 text-xs text-gray-200">ID: {{ _libraryItem.id }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</modals-modal>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
value: Boolean,
|
||||
libraryItem: {
|
||||
type: Object,
|
||||
default: () => {}
|
||||
}
|
||||
},
|
||||
data() {
|
||||
return {}
|
||||
},
|
||||
computed: {
|
||||
show: {
|
||||
get() {
|
||||
return this.value
|
||||
},
|
||||
set(val) {
|
||||
this.$emit('input', val)
|
||||
}
|
||||
},
|
||||
_libraryItem() {
|
||||
return this.libraryItem || {}
|
||||
},
|
||||
media() {
|
||||
return this._libraryItem.media || {}
|
||||
},
|
||||
mediaMetadata() {
|
||||
return this.media.metadata || {}
|
||||
}
|
||||
},
|
||||
methods: {},
|
||||
mounted() {}
|
||||
}
|
||||
</script>
|
||||
@@ -51,7 +51,7 @@ export default {
|
||||
async clickedOption(lib) {
|
||||
this.show = false
|
||||
await this.$store.dispatch('libraries/fetch', lib.id)
|
||||
this.$eventBus.$emit('library-changed', lib.id)
|
||||
this.$eventBus.$emit('library-changed')
|
||||
this.$localStore.setLastLibraryId(lib.id)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<span class="material-icons text-4xl">close</span>
|
||||
</div>
|
||||
<slot name="outer" />
|
||||
<div ref="content" style="max-width: 90%; min-height: 200px" class="relative text-white max-h-screen" :style="{ height: modalHeight, width: modalWidth }" v-click-outside="clickBg">
|
||||
<div ref="content" style="min-height: 200px" class="relative text-white max-h-screen" :style="{ height: modalHeight, width: modalWidth, maxWidth: maxWidth }" v-click-outside="clickBg">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
@@ -28,6 +28,10 @@ export default {
|
||||
height: {
|
||||
type: [String, Number],
|
||||
default: 'unset'
|
||||
},
|
||||
maxWidth: {
|
||||
type: String,
|
||||
default: '90%'
|
||||
}
|
||||
},
|
||||
data() {
|
||||
@@ -73,6 +77,8 @@ export default {
|
||||
}
|
||||
},
|
||||
setShow() {
|
||||
this.$store.commit('globals/setIsModalOpen', true)
|
||||
|
||||
document.body.appendChild(this.el)
|
||||
setTimeout(() => {
|
||||
this.content.style.transform = 'scale(1)'
|
||||
@@ -80,18 +86,28 @@ export default {
|
||||
document.documentElement.classList.add('modal-open')
|
||||
},
|
||||
setHide() {
|
||||
this.$store.commit('globals/setIsModalOpen', false)
|
||||
|
||||
this.content.style.transform = 'scale(0)'
|
||||
this.el.remove()
|
||||
document.documentElement.classList.remove('modal-open')
|
||||
},
|
||||
closeModalEvt() {
|
||||
console.log('Close modal event')
|
||||
this.show = false
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.$eventBus.$on('close-modal', this.closeModalEvt)
|
||||
this.el = this.$refs.wrapper
|
||||
this.content = this.$refs.content
|
||||
this.content.style.transform = 'scale(0)'
|
||||
this.content.style.transition = 'transform 0.25s cubic-bezier(0.16, 1, 0.3, 1)'
|
||||
this.el.style.opacity = 1
|
||||
this.el.remove()
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.$eventBus.$off('close-modal', this.closeModalEvt)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -47,6 +47,10 @@ export default {
|
||||
text: 'Size',
|
||||
value: 'size'
|
||||
},
|
||||
{
|
||||
text: 'Duration',
|
||||
value: 'media.duration'
|
||||
},
|
||||
{
|
||||
text: 'File Birthtime',
|
||||
value: 'birthtimeMs'
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<template>
|
||||
<modals-modal v-model="show" :width="200" height="100%">
|
||||
<modals-modal v-model="show" @input="modalInput" :width="200" height="100%">
|
||||
<template #outer>
|
||||
<div class="absolute top-5 left-4 z-40">
|
||||
<p class="text-white text-2xl truncate">Playback Speed</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="w-full h-full overflow-hidden absolute top-0 left-0 flex items-center justify-center" @click="closeMenu">
|
||||
<div class="w-full h-full overflow-hidden absolute top-0 left-0 flex items-center justify-center">
|
||||
<div class="w-full overflow-x-hidden overflow-y-auto bg-primary rounded-lg border border-white border-opacity-20" style="max-height: 75%" @click.stop>
|
||||
<ul class="w-full" role="listbox" aria-labelledby="listbox-label">
|
||||
<template v-for="rate in rates">
|
||||
@@ -91,15 +91,17 @@ export default {
|
||||
var newPlaybackRate = this.selected - 0.1
|
||||
this.selected = Number(newPlaybackRate.toFixed(1))
|
||||
},
|
||||
closeMenu() {
|
||||
if (this.currentPlaybackRate !== this.selected) {
|
||||
this.$emit('change', this.selected)
|
||||
modalInput(val) {
|
||||
if (!val) {
|
||||
if (this.currentPlaybackRate !== this.selected) {
|
||||
this.$emit('change', this.selected)
|
||||
}
|
||||
}
|
||||
this.show = false
|
||||
},
|
||||
clickedOption(rate) {
|
||||
this.selected = Number(rate)
|
||||
this.$nextTick(this.closeMenu)
|
||||
this.show = false
|
||||
this.$emit('change', Number(rate))
|
||||
}
|
||||
},
|
||||
mounted() {}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
<template>
|
||||
<div class="w-full px-2 py-2 overflow-hidden relative">
|
||||
<div v-if="book" class="flex h-20">
|
||||
<div v-if="book" class="flex w-full">
|
||||
<div class="h-full relative" :style="{ width: bookWidth + 'px' }">
|
||||
<covers-book-cover :library-item="book" :width="bookWidth" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
</div>
|
||||
<div class="w-80 h-full px-2 flex items-center">
|
||||
<div>
|
||||
<nuxt-link :to="`/item/${book.id}`" class="truncate text-sm">{{ bookTitle }}</nuxt-link>
|
||||
<div class="flex-grow book-table-content h-full px-2 flex items-center">
|
||||
<div class="max-w-full">
|
||||
<nuxt-link :to="`/item/${book.id}`" class="truncate block text-sm">{{ bookTitle }}</nuxt-link>
|
||||
<p class="truncate block text-gray-400 text-xs">{{ bookAuthor }}</p>
|
||||
<p class="text-xxs text-gray-500">{{ bookDuration }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -46,13 +47,13 @@ export default {
|
||||
return this.mediaMetadata.authorName || ''
|
||||
},
|
||||
bookDuration() {
|
||||
return this.$secondsToTimestamp(this.media.duration)
|
||||
return this.$elapsedPretty(this.media.duration)
|
||||
},
|
||||
bookCoverAspectRatio() {
|
||||
return this.$store.getters['getBookCoverAspectRatio']
|
||||
},
|
||||
bookWidth() {
|
||||
if (this.bookCoverAspectRatio === 1) return 80
|
||||
if (this.bookCoverAspectRatio === 1) return 50
|
||||
return 50
|
||||
},
|
||||
isMissing() {
|
||||
@@ -78,4 +79,11 @@ export default {
|
||||
},
|
||||
mounted() {}
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.book-table-content {
|
||||
width: calc(100% - 50px);
|
||||
max-width: calc(100% - 50px);
|
||||
}
|
||||
</style>
|
||||
@@ -16,9 +16,8 @@
|
||||
<p class="text-sm font-semibold">
|
||||
{{ title }}
|
||||
</p>
|
||||
<p class="text-sm text-gray-200 episode-subtitle mt-1.5 mb-0.5">
|
||||
{{ description }}
|
||||
</p>
|
||||
<p class="text-sm text-gray-200 episode-subtitle mt-1.5 mb-0.5 default-style" v-html="description" />
|
||||
|
||||
<div class="flex items-center pt-2">
|
||||
<div class="h-8 px-4 border border-white border-opacity-20 hover:bg-white hover:bg-opacity-10 rounded-full flex items-center justify-center cursor-pointer" :class="userIsFinished ? 'text-white text-opacity-40' : ''" @click="playClick">
|
||||
<span class="material-icons" :class="streamIsPlaying ? '' : 'text-success'">{{ streamIsPlaying ? 'pause' : 'play_arrow' }}</span>
|
||||
@@ -27,7 +26,7 @@
|
||||
|
||||
<ui-read-icon-btn :disabled="isProcessingReadUpdate" :is-read="userIsFinished" borderless class="mx-1 mt-0.5" @click="toggleFinished" />
|
||||
|
||||
<div v-if="!isIos">
|
||||
<div v-if="!isIos && userCanDownload">
|
||||
<span v-if="isLocal" class="material-icons-outlined px-2 text-success text-lg">audio_file</span>
|
||||
<span v-else-if="!localEpisode" class="material-icons mx-1 mt-2" :class="downloadItem ? 'animate-bounce text-warning text-opacity-75 text-xl' : 'text-gray-300 text-xl'" @click="downloadClick">{{ downloadItem ? 'downloading' : 'download' }}</span>
|
||||
<span v-else class="material-icons px-2 text-success text-xl">download_done</span>
|
||||
@@ -41,7 +40,7 @@
|
||||
|
||||
<script>
|
||||
import { Dialog } from '@capacitor/dialog'
|
||||
import { AbsDownloader } from '@/plugins/capacitor'
|
||||
import { AbsFileSystem, AbsDownloader } from '@/plugins/capacitor'
|
||||
|
||||
export default {
|
||||
props: {
|
||||
@@ -69,6 +68,9 @@ export default {
|
||||
mediaType() {
|
||||
return 'podcast'
|
||||
},
|
||||
userCanDownload() {
|
||||
return this.$store.getters['user/getUserCanDownload']
|
||||
},
|
||||
audioFile() {
|
||||
return this.episode.audioFile
|
||||
},
|
||||
@@ -132,8 +134,12 @@ export default {
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
selectFolder() {
|
||||
this.$toast.error('Folder selector not implemented for podcasts yet')
|
||||
async selectFolder() {
|
||||
var folderObj = await AbsFileSystem.selectFolder({ mediaType: this.mediaType })
|
||||
if (folderObj.error) {
|
||||
return this.$toast.error(`Error: ${folderObj.error || 'Unknown Error'}`)
|
||||
}
|
||||
return folderObj
|
||||
},
|
||||
downloadClick() {
|
||||
if (this.downloadItem) return
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
<template>
|
||||
<div class="w-full">
|
||||
<p class="text-lg mb-1 font-semibold">Episodes ({{ episodes.length }})</p>
|
||||
<div class="flex items-center">
|
||||
<p class="text-lg mb-1 font-semibold">Episodes ({{ episodesFiltered.length }})</p>
|
||||
<div class="flex-grow" />
|
||||
<button class="outline:none mx-3 pt-0.5 relative" @click="showFilters">
|
||||
<span class="material-icons text-xl text-gray-200">filter_alt</span>
|
||||
<div v-show="filterKey !== 'all' && episodesAreFiltered" class="absolute top-0 right-0 w-1.5 h-1.5 rounded-full bg-success border border-green-300 shadow-sm z-10 pointer-events-none" />
|
||||
</button>
|
||||
|
||||
<template v-for="episode in episodes">
|
||||
<div class="flex items-center border border-white border-opacity-25 rounded px-2" @click="clickSort">
|
||||
<p class="text-sm text-gray-200">{{ sortText }}</p>
|
||||
<span class="material-icons ml-1 text-gray-200">{{ sortDesc ? 'arrow_drop_down' : 'arrow_drop_up' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-for="episode in episodesSorted">
|
||||
<tables-podcast-episode-row :episode="episode" :local-episode="localEpisodeMap[episode.id]" :library-item-id="libraryItemId" :local-library-item-id="localLibraryItemId" :is-local="isLocal" :key="episode.id" />
|
||||
</template>
|
||||
|
||||
<!-- What in tarnation is going on here?
|
||||
Without anything below the template it will not re-render -->
|
||||
<p> </p>
|
||||
|
||||
<modals-dialog v-model="showFiltersModal" title="Episode Filter" :items="filterItems" :selected="filterKey" @action="setFilter" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -24,9 +42,86 @@ export default {
|
||||
isLocal: Boolean // If is local then episodes and libraryItemId are local, otherwise local is passed in localLibraryItemId and localEpisodes
|
||||
},
|
||||
data() {
|
||||
return {}
|
||||
return {
|
||||
episodesCopy: [],
|
||||
showFiltersModal: false,
|
||||
sortKey: 'publishedAt',
|
||||
sortDesc: false,
|
||||
filterKey: 'incomplete',
|
||||
episodeSortItems: [
|
||||
{
|
||||
text: 'Pub Date',
|
||||
value: 'publishedAt'
|
||||
},
|
||||
{
|
||||
text: 'Title',
|
||||
value: 'title'
|
||||
},
|
||||
{
|
||||
text: 'Season',
|
||||
value: 'season'
|
||||
},
|
||||
{
|
||||
text: 'Episode',
|
||||
value: 'episode'
|
||||
}
|
||||
],
|
||||
filterItems: [
|
||||
{
|
||||
text: 'Show All',
|
||||
value: 'all'
|
||||
},
|
||||
{
|
||||
text: 'Incomplete',
|
||||
value: 'incomplete'
|
||||
},
|
||||
{
|
||||
text: 'In Progress',
|
||||
value: 'inProgress'
|
||||
},
|
||||
{
|
||||
text: 'Complete',
|
||||
value: 'complete'
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
episodes: {
|
||||
immediate: true,
|
||||
handler() {
|
||||
this.init()
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
episodesAreFiltered() {
|
||||
return this.episodesFiltered.length !== this.episodesCopy.length
|
||||
},
|
||||
episodesFiltered() {
|
||||
return this.episodesCopy.filter((ep) => {
|
||||
var mediaProgress = this.getEpisodeProgress(ep)
|
||||
if (this.filterKey === 'incomplete') {
|
||||
return !mediaProgress || !mediaProgress.isFinished
|
||||
} else if (this.filterKey === 'complete') {
|
||||
return mediaProgress && mediaProgress.isFinished
|
||||
} else if (this.filterKey === 'inProgress') {
|
||||
return mediaProgress && !mediaProgress.isFinished
|
||||
} else if (this.filterKey === 'all') {
|
||||
console.log('Filter key is all')
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
},
|
||||
episodesSorted() {
|
||||
return this.episodesFiltered.sort((a, b) => {
|
||||
if (this.sortDesc) {
|
||||
return String(b[this.sortKey]).localeCompare(String(a[this.sortKey]), undefined, { numeric: true, sensitivity: 'base' })
|
||||
}
|
||||
return String(a[this.sortKey]).localeCompare(String(b[this.sortKey]), undefined, { numeric: true, sensitivity: 'base' })
|
||||
})
|
||||
},
|
||||
// Map of local episodes where server episode id is key
|
||||
localEpisodeMap() {
|
||||
var epmap = {}
|
||||
@@ -36,9 +131,36 @@ export default {
|
||||
}
|
||||
})
|
||||
return epmap
|
||||
},
|
||||
sortText() {
|
||||
if (!this.sortKey) return ''
|
||||
var _sel = this.episodeSortItems.find((i) => i.value === this.sortKey)
|
||||
if (!_sel) return ''
|
||||
return _sel.text
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
setFilter(filter) {
|
||||
this.filterKey = filter
|
||||
console.log('Set filter', this.filterKey)
|
||||
this.showFiltersModal = false
|
||||
},
|
||||
showFilters() {
|
||||
this.showFiltersModal = true
|
||||
},
|
||||
clickSort() {
|
||||
this.sortDesc = !this.sortDesc
|
||||
},
|
||||
getEpisodeProgress(episode) {
|
||||
if (this.isLocal) return this.$store.getters['globals/getLocalMediaProgressById'](this.libraryItemId, episode.id)
|
||||
return this.$store.getters['user/getUserMediaProgress'](this.libraryItemId, episode.id)
|
||||
},
|
||||
init() {
|
||||
this.episodesCopy = this.episodes.map((ep) => {
|
||||
return { ...ep }
|
||||
})
|
||||
}
|
||||
},
|
||||
methods: {},
|
||||
mounted() {}
|
||||
}
|
||||
</script>
|
||||
@@ -23,6 +23,11 @@
|
||||
3AF1970E2806E3CA0096F747 /* AbsAudioPlayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AF1970D2806E3CA0096F747 /* AbsAudioPlayer.swift */; };
|
||||
3AF197102806E3DC0096F747 /* AbsAudioPlayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 3AF1970F2806E3DC0096F747 /* AbsAudioPlayer.m */; };
|
||||
3AFCB5E827EA240D00ECCC05 /* NowPlayingInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AFCB5E727EA240D00ECCC05 /* NowPlayingInfo.swift */; };
|
||||
4D66B952282EE822008272D4 /* AbsDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D66B951282EE822008272D4 /* AbsDownloader.m */; };
|
||||
4D66B954282EE87C008272D4 /* AbsDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D66B953282EE87C008272D4 /* AbsDownloader.swift */; };
|
||||
4D66B956282EE951008272D4 /* AbsFileSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D66B955282EE951008272D4 /* AbsFileSystem.m */; };
|
||||
4D66B958282EEA14008272D4 /* AbsFileSystem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D66B957282EEA14008272D4 /* AbsFileSystem.swift */; };
|
||||
4DF74912287105C600AC7814 /* DeviceSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DF74911287105C600AC7814 /* DeviceSettings.swift */; };
|
||||
50379B232058CBB4000EE86E /* capacitor.config.json in Resources */ = {isa = PBXBuildFile; fileRef = 50379B222058CBB4000EE86E /* capacitor.config.json */; };
|
||||
504EC3081FED79650016851F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 504EC3071FED79650016851F /* AppDelegate.swift */; };
|
||||
504EC30D1FED79650016851F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30B1FED79650016851F /* Main.storyboard */; };
|
||||
@@ -50,7 +55,12 @@
|
||||
3AF1970D2806E3CA0096F747 /* AbsAudioPlayer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsAudioPlayer.swift; sourceTree = "<group>"; };
|
||||
3AF1970F2806E3DC0096F747 /* AbsAudioPlayer.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AbsAudioPlayer.m; sourceTree = "<group>"; };
|
||||
3AFCB5E727EA240D00ECCC05 /* NowPlayingInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowPlayingInfo.swift; sourceTree = "<group>"; };
|
||||
4D66B951282EE822008272D4 /* AbsDownloader.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AbsDownloader.m; sourceTree = "<group>"; };
|
||||
4D66B953282EE87C008272D4 /* AbsDownloader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsDownloader.swift; sourceTree = "<group>"; };
|
||||
4D66B955282EE951008272D4 /* AbsFileSystem.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AbsFileSystem.m; sourceTree = "<group>"; };
|
||||
4D66B957282EEA14008272D4 /* AbsFileSystem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbsFileSystem.swift; sourceTree = "<group>"; };
|
||||
4D8D412C26E187E400BA5F0D /* App-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "App-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
4DF74911287105C600AC7814 /* DeviceSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceSettings.swift; sourceTree = "<group>"; };
|
||||
50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
|
||||
504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
@@ -111,6 +121,10 @@
|
||||
3AD4FCE628043E72006DB301 /* AbsDatabase.m */,
|
||||
3AF1970D2806E3CA0096F747 /* AbsAudioPlayer.swift */,
|
||||
3AF1970F2806E3DC0096F747 /* AbsAudioPlayer.m */,
|
||||
4D66B951282EE822008272D4 /* AbsDownloader.m */,
|
||||
4D66B953282EE87C008272D4 /* AbsDownloader.swift */,
|
||||
4D66B955282EE951008272D4 /* AbsFileSystem.m */,
|
||||
4D66B957282EEA14008272D4 /* AbsFileSystem.swift */,
|
||||
);
|
||||
path = plugins;
|
||||
sourceTree = "<group>";
|
||||
@@ -122,6 +136,7 @@
|
||||
3ABF580828059BAE005DFBE5 /* PlaybackSession.swift */,
|
||||
C4D0677428106D0C00B8F875 /* DataClasses.swift */,
|
||||
3A90295E280968E700E1D427 /* PlaybackReport.swift */,
|
||||
4DF74911287105C600AC7814 /* DeviceSettings.swift */,
|
||||
);
|
||||
path = models;
|
||||
sourceTree = "<group>";
|
||||
@@ -303,16 +318,21 @@
|
||||
3ABF580928059BAE005DFBE5 /* PlaybackSession.swift in Sources */,
|
||||
3ABF618F2804325C0070250E /* PlayerHandler.swift in Sources */,
|
||||
3AD4FCED28044E6C006DB301 /* Store.swift in Sources */,
|
||||
4D66B958282EEA14008272D4 /* AbsFileSystem.swift in Sources */,
|
||||
3AF1970E2806E3CA0096F747 /* AbsAudioPlayer.swift in Sources */,
|
||||
3AD4FCE928043FD7006DB301 /* ServerConnectionConfig.swift in Sources */,
|
||||
3A200C1527D64D7E00CBF02E /* AudioPlayer.swift in Sources */,
|
||||
4D66B956282EE951008272D4 /* AbsFileSystem.m in Sources */,
|
||||
3AFCB5E827EA240D00ECCC05 /* NowPlayingInfo.swift in Sources */,
|
||||
3AB34053280829BF0039308B /* Extensions.swift in Sources */,
|
||||
3AD4FCEB280443DD006DB301 /* Database.swift in Sources */,
|
||||
3AD4FCE528043E50006DB301 /* AbsDatabase.swift in Sources */,
|
||||
4D66B952282EE822008272D4 /* AbsDownloader.m in Sources */,
|
||||
4DF74912287105C600AC7814 /* DeviceSettings.swift in Sources */,
|
||||
3AF197102806E3DC0096F747 /* AbsAudioPlayer.m in Sources */,
|
||||
3AF1970C2806E2590096F747 /* ApiClient.swift in Sources */,
|
||||
C4D0677528106D0C00B8F875 /* DataClasses.swift in Sources */,
|
||||
4D66B954282EE87C008272D4 /* AbsDownloader.swift in Sources */,
|
||||
3AB34055280832720039308B /* PlayerEvents.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -459,12 +479,12 @@
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = Icons;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
CURRENT_PROJECT_VERSION = 11;
|
||||
DEVELOPMENT_TEAM = 7UFJ7D8V6A;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
MARKETING_VERSION = 0.9.44;
|
||||
MARKETING_VERSION = 0.9.51;
|
||||
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.audiobookshelf.app.dev;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
@@ -483,12 +503,12 @@
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = Icons;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
CURRENT_PROJECT_VERSION = 11;
|
||||
DEVELOPMENT_TEAM = 7UFJ7D8V6A;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
MARKETING_VERSION = 0.9.44;
|
||||
MARKETING_VERSION = 0.9.51;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.audiobookshelf.app;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
|
||||
|
||||
@@ -23,8 +23,9 @@ public class AbsAudioPlayer: CAPPlugin {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(onPlaybackFailed), name: NSNotification.Name(PlayerEvents.failed.rawValue), object: nil)
|
||||
|
||||
self.bridge?.webView?.allowsBackForwardNavigationGestures = true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@objc func prepareLibraryItem(_ call: CAPPluginCall) {
|
||||
let libraryItemId = call.getString("libraryItemId")
|
||||
let episodeId = call.getString("episodeId")
|
||||
@@ -43,10 +44,10 @@ public class AbsAudioPlayer: CAPPlugin {
|
||||
initialPlayWhenReady = playWhenReady
|
||||
initialPlaybackRate = playbackRate
|
||||
|
||||
PlayerHandler.stopPlayback()
|
||||
|
||||
sendPrepareMetadataEvent(itemId: libraryItemId!, playWhenReady: playWhenReady)
|
||||
ApiClient.startPlaybackSession(libraryItemId: libraryItemId!, episodeId: episodeId, forceTranscode: false) { session in
|
||||
PlayerHandler.startPlayback(session: session, playWhenReady: playWhenReady, playbackRate: playbackRate)
|
||||
|
||||
do {
|
||||
self.sendPlaybackSession(session: try session.asDictionary())
|
||||
call.resolve(try session.asDictionary())
|
||||
@@ -56,6 +57,8 @@ public class AbsAudioPlayer: CAPPlugin {
|
||||
call.resolve([:])
|
||||
}
|
||||
|
||||
|
||||
PlayerHandler.startPlayback(session: session, playWhenReady: playWhenReady, playbackRate: playbackRate)
|
||||
self.sendMetadata()
|
||||
}
|
||||
}
|
||||
@@ -173,7 +176,7 @@ public class AbsAudioPlayer: CAPPlugin {
|
||||
let playbackSession = PlayerHandler.getPlaybackSession()
|
||||
let libraryItemId = playbackSession?.libraryItemId ?? ""
|
||||
let episodeId = playbackSession?.episodeId ?? nil
|
||||
NSLog("TEST: Forcing Transcode")
|
||||
NSLog("Forcing Transcode")
|
||||
|
||||
// If direct playing then fallback to transcode
|
||||
ApiClient.startPlaybackSession(libraryItemId: libraryItemId, episodeId: episodeId, forceTranscode: true) { session in
|
||||
|
||||
@@ -19,5 +19,6 @@ CAP_PLUGIN(AbsDatabase, "AbsDatabase",
|
||||
CAP_PLUGIN_METHOD(getLocalLibraryItem, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(getLocalLibraryItemByLLId, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(getLocalLibraryItemsInFolder, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(updateDeviceSettings, CAPPluginReturnPromise);
|
||||
)
|
||||
|
||||
|
||||
@@ -65,11 +65,12 @@ public class AbsDatabase: CAPPlugin {
|
||||
@objc func getDeviceData(_ call: CAPPluginCall) {
|
||||
let configs = Database.shared.getServerConnectionConfigs()
|
||||
let index = Database.shared.getLastActiveConfigIndex()
|
||||
let settings = Database.shared.getDeviceSettings()
|
||||
|
||||
call.resolve([
|
||||
"serverConnectionConfigs": configs.map { config in convertServerConnectionConfigToJSON(config: config) },
|
||||
"lastServerConnectionConfigId": configs.first { config in config.index == index }?.id as Any,
|
||||
// "currentLocalPlaybackSession": nil,
|
||||
"deviceSettings": deviceSettingsToJSON(settings: settings)
|
||||
])
|
||||
}
|
||||
|
||||
@@ -85,4 +86,18 @@ public class AbsDatabase: CAPPlugin {
|
||||
@objc func getLocalLibraryItemsInFolder(_ call: CAPPluginCall) {
|
||||
call.resolve([ "value": [] ])
|
||||
}
|
||||
@objc func updateDeviceSettings(_ call: CAPPluginCall) {
|
||||
let disableAutoRewind = call.getBool("disableAutoRewind") ?? false
|
||||
let jumpBackwardsTime = call.getInt("jumpBackwardsTime") ?? 10
|
||||
let jumpForwardTime = call.getInt("jumpForwardTime") ?? 10
|
||||
let settings = DeviceSettings()
|
||||
settings.disableAutoRewind = disableAutoRewind
|
||||
settings.jumpBackwardsTime = jumpBackwardsTime
|
||||
settings.jumpForwardTime = jumpForwardTime
|
||||
|
||||
Database.shared.setDeviceSettings(deviceSettings: settings)
|
||||
|
||||
// call.resolve([ "value": [] ])
|
||||
getDeviceData(call)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
//
|
||||
// AbsDownloader.m
|
||||
// App
|
||||
//
|
||||
// Created by advplyr on 5/13/22.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Capacitor/Capacitor.h>
|
||||
|
||||
CAP_PLUGIN(AbsDownloader, "AbsDownloader",
|
||||
CAP_PLUGIN_METHOD(downloadLibraryItem, CAPPluginReturnPromise);
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
//
|
||||
// AbsDownloader.swift
|
||||
// App
|
||||
//
|
||||
// Created by advplyr on 5/13/22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Capacitor
|
||||
|
||||
@objc(AbsDownloader)
|
||||
public class AbsDownloader: CAPPlugin {
|
||||
@objc func downloadLibraryItem(_ call: CAPPluginCall) {
|
||||
let libraryItemId = call.getString("libraryItemId")
|
||||
let episodeId = call.getString("episodeId")
|
||||
|
||||
NSLog("Download library item \(libraryItemId ?? "N/A") episode \(episodeId ?? "")")
|
||||
|
||||
ApiClient.getLibraryItemWithProgress(libraryItemId: libraryItemId!, episodeId: episodeId) { libraryItem in
|
||||
if (libraryItem == nil) {
|
||||
NSLog("Library item not found")
|
||||
call.resolve()
|
||||
} else {
|
||||
NSLog("Got library item \(libraryItem!)")
|
||||
|
||||
// TODO: break out in seperate functions
|
||||
libraryItem!.media.tracks?.forEach { track in
|
||||
NSLog("TRACK \(track.contentUrl!)")
|
||||
// filename needs to be encoded otherwise would just use contentUrl
|
||||
let filename = track.metadata?.filename ?? ""
|
||||
let filenameEncoded = filename.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
|
||||
let urlstr = "\(Store.serverConfig!.address)/s/item/\(libraryItemId!)/\(filenameEncoded ?? "")?token=\(Store.serverConfig!.token)"
|
||||
let url = URL(string: urlstr)!
|
||||
|
||||
|
||||
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
let itemDirectory = documentsDirectory.appendingPathComponent("\(libraryItemId!)")
|
||||
NSLog("ITEM DIR \(itemDirectory)")
|
||||
|
||||
// Create library item directory
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: itemDirectory, withIntermediateDirectories: false)
|
||||
} catch {
|
||||
NSLog("Failed to CREATE LI DIRECTORY \(error)")
|
||||
}
|
||||
|
||||
// Output filename
|
||||
let trackFilename = itemDirectory.appendingPathComponent("\(filename)")
|
||||
|
||||
let downloadTask = URLSession.shared.downloadTask(with: url) { urlOrNil, responseOrNil, errorOrNil in
|
||||
|
||||
guard let fileURL = urlOrNil else { return }
|
||||
|
||||
do {
|
||||
NSLog("Download TMP file URL \(fileURL)")
|
||||
let imageData = try Data(contentsOf:fileURL)
|
||||
try imageData.write(to: trackFilename)
|
||||
NSLog("Download written to \(trackFilename)")
|
||||
} catch {
|
||||
NSLog("FILE ERROR: \(error)")
|
||||
}
|
||||
}
|
||||
downloadTask.resume()
|
||||
}
|
||||
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// AbsFileSystem.m
|
||||
// App
|
||||
//
|
||||
// Created by advplyr on 5/13/22.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Capacitor/Capacitor.h>
|
||||
|
||||
CAP_PLUGIN(AbsFileSystem, "AbsFileSystem",
|
||||
CAP_PLUGIN_METHOD(selectFolder, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(checkFolderPermission, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(scanFolder, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(removeFolder, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(removeLocalLibraryItem, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(scanLocalLibraryItem, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(deleteItem, CAPPluginReturnPromise);
|
||||
CAP_PLUGIN_METHOD(deleteTrackFromItem, CAPPluginReturnPromise);
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// AbsFileSystem.swift
|
||||
// App
|
||||
//
|
||||
// Created by advplyr on 5/13/22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Capacitor
|
||||
|
||||
@objc(AbsFileSystem)
|
||||
public class AbsFileSystem: CAPPlugin {
|
||||
@objc func selectFolder(_ call: CAPPluginCall) {
|
||||
let mediaType = call.getString("mediaType")
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("Select Folder for media type \(mediaType ?? "UNSET")")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func checkFolderPermission(_ call: CAPPluginCall) {
|
||||
let folderUrl = call.getString("folderUrl")
|
||||
|
||||
// TODO: Is this even necessary on iOS?
|
||||
NSLog("checkFolderPermission for folder \(folderUrl ?? "UNSET")")
|
||||
|
||||
call.resolve([
|
||||
"value": true
|
||||
])
|
||||
}
|
||||
|
||||
@objc func scanFolder(_ call: CAPPluginCall) {
|
||||
let folderId = call.getString("folderId")
|
||||
let forceAudioProbe = call.getBool("forceAudioProbe", false)
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("scanFolder \(folderId ?? "UNSET") | Force Probe = \(forceAudioProbe)")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func removeFolder(_ call: CAPPluginCall) {
|
||||
let folderId = call.getString("folderId")
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("removeFolder \(folderId ?? "UNSET")")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func removeLocalLibraryItem(_ call: CAPPluginCall) {
|
||||
let localLibraryItemId = call.getString("localLibraryItemId")
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("removeLocalLibraryItem \(localLibraryItemId ?? "UNSET")")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func scanLocalLibraryItem(_ call: CAPPluginCall) {
|
||||
let localLibraryItemId = call.getString("localLibraryItemId")
|
||||
let forceAudioProbe = call.getBool("forceAudioProbe", false)
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("scanLocalLibraryItem \(localLibraryItemId ?? "UNSET") | Force Probe = \(forceAudioProbe)")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func deleteItem(_ call: CAPPluginCall) {
|
||||
let localLibraryItemId = call.getString("localLibraryItemId")
|
||||
let contentUrl = call.getString("contentUrl")
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("deleteItem \(localLibraryItemId ?? "UNSET") url \(contentUrl ?? "UNSET")")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
|
||||
@objc func deleteTrackFromItem(_ call: CAPPluginCall) {
|
||||
let localLibraryItemId = call.getString("localLibraryItemId")
|
||||
let trackLocalFileId = call.getString("trackLocalFileId")
|
||||
let contentUrl = call.getString("contentUrl")
|
||||
|
||||
// TODO: Implement
|
||||
NSLog("deleteTrackFromItem \(localLibraryItemId ?? "UNSET") track file \(trackLocalFileId ?? "UNSET") url \(contentUrl ?? "UNSET")")
|
||||
|
||||
call.resolve()
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ def capacitor_pods
|
||||
pod 'CapacitorNetwork', :path => '../../node_modules/@capacitor/network'
|
||||
pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar'
|
||||
pod 'CapacitorStorage', :path => '../../node_modules/@capacitor/storage'
|
||||
pod 'RobingenzCapacitorAppUpdate', :path => '../../node_modules/@robingenz/capacitor-app-update'
|
||||
end
|
||||
|
||||
target 'App' do
|
||||
|
||||
@@ -15,6 +15,7 @@ struct LibraryItem: Codable {
|
||||
var folderId: String
|
||||
var path: String
|
||||
var relPath: String
|
||||
var isFile: Bool
|
||||
var mtimeMs: Int64
|
||||
var ctimeMs: Int64
|
||||
var birthtimeMs: Int64
|
||||
@@ -27,6 +28,7 @@ struct LibraryItem: Codable {
|
||||
var mediaType: String
|
||||
var media: MediaType
|
||||
var libraryFiles: [LibraryFile]
|
||||
var userMediaProgress:MediaProgress?
|
||||
}
|
||||
struct MediaType: Codable {
|
||||
var libraryItemId: String?
|
||||
@@ -125,3 +127,15 @@ struct LibraryFile: Codable {
|
||||
var ino: String
|
||||
var metadata: FileMetadata
|
||||
}
|
||||
struct MediaProgress:Codable {
|
||||
var id:String
|
||||
var libraryItemId:String
|
||||
var episodeId:String?
|
||||
var duration:Double
|
||||
var progress:Double
|
||||
var currentTime:Double
|
||||
var isFinished:Bool
|
||||
var lastUpdate:Int64
|
||||
var startedAt:Int64
|
||||
var finishedAt:Int64?
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// DeviceSettings.swift
|
||||
// App
|
||||
//
|
||||
// Created by advplyr on 7/2/22.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import RealmSwift
|
||||
|
||||
class DeviceSettings: Object {
|
||||
@Persisted var disableAutoRewind: Bool
|
||||
@Persisted var jumpBackwardsTime: Int
|
||||
@Persisted var jumpForwardTime: Int
|
||||
}
|
||||
|
||||
func getDefaultDeviceSettings() -> DeviceSettings {
|
||||
let settings = DeviceSettings()
|
||||
settings.disableAutoRewind = false
|
||||
settings.jumpForwardTime = 10
|
||||
settings.jumpBackwardsTime = 10
|
||||
return settings
|
||||
}
|
||||
|
||||
func deviceSettingsToJSON(settings: DeviceSettings) -> Dictionary<String, Any> {
|
||||
return Database.realmQueue.sync {
|
||||
return [
|
||||
"disableAutoRewind": settings.disableAutoRewind,
|
||||
"jumpBackwardsTime": settings.jumpBackwardsTime,
|
||||
"jumpForwardTime": settings.jumpForwardTime
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ class AudioPlayer: NSObject {
|
||||
self.playWhenReady = playWhenReady
|
||||
self.initialPlaybackRate = playbackRate
|
||||
self.audioPlayer = AVQueuePlayer()
|
||||
self.audioPlayer.automaticallyWaitsToMinimizeStalling = false
|
||||
self.playbackSession = playbackSession
|
||||
self.status = -1
|
||||
self.rate = 0.0
|
||||
@@ -65,10 +66,10 @@ class AudioPlayer: NSObject {
|
||||
}
|
||||
|
||||
self.currentTrackIndex = getItemIndexForTime(time: playbackSession.currentTime)
|
||||
NSLog("TEST: Starting track index \(self.currentTrackIndex) for start time \(playbackSession.currentTime)")
|
||||
NSLog("Starting track index \(self.currentTrackIndex) for start time \(playbackSession.currentTime)")
|
||||
|
||||
let playerItems = self.allPlayerItems[self.currentTrackIndex..<self.allPlayerItems.count]
|
||||
NSLog("TEST: Setting player items \(playerItems.count)")
|
||||
NSLog("Setting player items \(playerItems.count)")
|
||||
|
||||
for item in Array(playerItems) {
|
||||
self.audioPlayer.insert(item, after:self.audioPlayer.items().last)
|
||||
@@ -122,7 +123,7 @@ class AudioPlayer: NSObject {
|
||||
self.audioPlayer.currentItem.map { item in
|
||||
self.currentTrackIndex = self.allPlayerItems.firstIndex(of:item) ?? 0
|
||||
if (self.currentTrackIndex != prevTrackIndex) {
|
||||
NSLog("TEST: New Current track index \(self.currentTrackIndex)")
|
||||
NSLog("New Current track index \(self.currentTrackIndex)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,7 +133,7 @@ class AudioPlayer: NSObject {
|
||||
self.queueItemStatusObserver?.invalidate()
|
||||
self.queueItemStatusObserver = self.audioPlayer.currentItem?.observe(\.status, options: [.new, .old], changeHandler: { (playerItem, change) in
|
||||
if (playerItem.status == .readyToPlay) {
|
||||
NSLog("TEST: queueStatusObserver: Current Item Ready to play. PlayWhenReady: \(self.playWhenReady)")
|
||||
NSLog("queueStatusObserver: Current Item Ready to play. PlayWhenReady: \(self.playWhenReady)")
|
||||
self.updateNowPlaying()
|
||||
|
||||
let firstReady = self.status < 0
|
||||
@@ -145,7 +146,7 @@ class AudioPlayer: NSObject {
|
||||
self.seek(self.playbackSession.currentTime, from: "queueItemStatusObserver")
|
||||
}
|
||||
} else if (playerItem.status == .failed) {
|
||||
NSLog("TEST: queueStatusObserver: FAILED \(playerItem.error?.localizedDescription ?? "")")
|
||||
NSLog("queueStatusObserver: FAILED \(playerItem.error?.localizedDescription ?? "")")
|
||||
|
||||
NotificationCenter.default.post(name: NSNotification.Name(PlayerEvents.failed.rawValue), object: nil)
|
||||
}
|
||||
@@ -202,16 +203,16 @@ class AudioPlayer: NSObject {
|
||||
|
||||
pause()
|
||||
|
||||
NSLog("TEST: Seek to \(to) from \(from)")
|
||||
NSLog("Seek to \(to) from \(from)")
|
||||
|
||||
let currentTrack = self.playbackSession.audioTracks[self.currentTrackIndex]
|
||||
let ctso = currentTrack.startOffset ?? 0.0
|
||||
let trackEnd = ctso + currentTrack.duration
|
||||
NSLog("TEST: Seek current track END = \(trackEnd)")
|
||||
NSLog("Seek current track END = \(trackEnd)")
|
||||
|
||||
|
||||
let indexOfSeek = getItemIndexForTime(time: to)
|
||||
NSLog("TEST: Seek to index \(indexOfSeek) | Current index \(self.currentTrackIndex)")
|
||||
NSLog("Seek to index \(indexOfSeek) | Current index \(self.currentTrackIndex)")
|
||||
|
||||
// Reconstruct queue if seeking to a different track
|
||||
if (self.currentTrackIndex != indexOfSeek) {
|
||||
@@ -230,7 +231,7 @@ class AudioPlayer: NSObject {
|
||||
|
||||
setupQueueItemStatusObserver()
|
||||
} else {
|
||||
NSLog("TEST: Seeking in current item \(to)")
|
||||
NSLog("Seeking in current item \(to)")
|
||||
let currentTrackStartOffset = self.playbackSession.audioTracks[self.currentTrackIndex].startOffset ?? 0.0
|
||||
let seekTime = to - currentTrackStartOffset
|
||||
|
||||
@@ -249,7 +250,7 @@ class AudioPlayer: NSObject {
|
||||
|
||||
public func setPlaybackRate(_ rate: Float, observed: Bool = false) {
|
||||
if self.audioPlayer.rate != rate {
|
||||
NSLog("TEST: setPlaybakRate rate changed from \(self.audioPlayer.rate) to \(rate)")
|
||||
NSLog("setPlaybakRate rate changed from \(self.audioPlayer.rate) to \(rate)")
|
||||
self.audioPlayer.rate = rate
|
||||
}
|
||||
if rate > 0.0 && !(observed && rate == 1) {
|
||||
@@ -372,7 +373,7 @@ class AudioPlayer: NSObject {
|
||||
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
|
||||
if context == &playerContext {
|
||||
if keyPath == #keyPath(AVPlayer.rate) {
|
||||
NSLog("TEST: playerContext observer player rate")
|
||||
NSLog("playerContext observer player rate")
|
||||
self.setPlaybackRate(change?[.newKey] as? Float ?? 1.0, observed: true)
|
||||
} else if keyPath == #keyPath(AVPlayer.currentItem) {
|
||||
NotificationCenter.default.post(name: NSNotification.Name(PlayerEvents.update.rawValue), object: nil)
|
||||
|
||||
@@ -17,7 +17,7 @@ class ApiClient {
|
||||
}).resume()
|
||||
}
|
||||
|
||||
public static func postResource<T: Decodable>(endpoint: String, parameters: [String: String], decodable: T.Type = T.self, callback: ((_ param: T) -> Void)?) {
|
||||
public static func postResource<T: Decodable>(endpoint: String, parameters: [String: Any], decodable: T.Type = T.self, callback: ((_ param: T) -> Void)?) {
|
||||
if (Store.serverConfig == nil) {
|
||||
NSLog("Server config not set")
|
||||
return
|
||||
@@ -27,7 +27,7 @@ class ApiClient {
|
||||
"Authorization": "Bearer \(Store.serverConfig!.token)"
|
||||
]
|
||||
|
||||
AF.request("\(Store.serverConfig!.address)/\(endpoint)", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default, headers: headers).responseDecodable(of: decodable) { response in
|
||||
AF.request("\(Store.serverConfig!.address)/\(endpoint)", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseDecodable(of: decodable) { response in
|
||||
switch response.result {
|
||||
case .success(let obj):
|
||||
callback?(obj)
|
||||
@@ -60,6 +60,27 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
public static func getResource<T: Decodable>(endpoint: String, decodable: T.Type = T.self, callback: ((_ param: T?) -> Void)?) {
|
||||
if (Store.serverConfig == nil) {
|
||||
NSLog("Server config not set")
|
||||
callback?(nil)
|
||||
return
|
||||
}
|
||||
|
||||
let headers: HTTPHeaders = [
|
||||
"Authorization": "Bearer \(Store.serverConfig!.token)"
|
||||
]
|
||||
|
||||
AF.request("\(Store.serverConfig!.address)/\(endpoint)", method: .get, encoding: JSONEncoding.default, headers: headers).responseDecodable(of: decodable) { response in
|
||||
switch response.result {
|
||||
case .success(let obj):
|
||||
callback?(obj)
|
||||
case .failure(let error):
|
||||
NSLog("api request to \(endpoint) failed")
|
||||
print(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static func startPlaybackSession(libraryItemId: String, episodeId: String?, forceTranscode:Bool, callback: @escaping (_ param: PlaybackSession) -> Void) {
|
||||
var endpoint = "api/items/\(libraryItemId)/play"
|
||||
@@ -67,10 +88,23 @@ class ApiClient {
|
||||
endpoint += "/\(episodeId!)"
|
||||
}
|
||||
|
||||
var systemInfo = utsname()
|
||||
uname(&systemInfo)
|
||||
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
|
||||
$0.withMemoryRebound(to: CChar.self, capacity: 1) {
|
||||
ptr in String.init(validatingUTF8: ptr)
|
||||
}
|
||||
}
|
||||
|
||||
ApiClient.postResource(endpoint: endpoint, parameters: [
|
||||
"forceDirectPlay": !forceTranscode ? "1" : "",
|
||||
"forceTranscode": forceTranscode ? "1" : "",
|
||||
"mediaPlayer": "AVPlayer",
|
||||
"deviceInfo": [
|
||||
"manufacturer": "Apple",
|
||||
"model": modelCode,
|
||||
"clientVersion": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
|
||||
]
|
||||
], decodable: PlaybackSession.self) { obj in
|
||||
var session = obj
|
||||
|
||||
@@ -83,4 +117,14 @@ class ApiClient {
|
||||
public static func reportPlaybackProgress(report: PlaybackReport, sessionId: String) {
|
||||
try? postResource(endpoint: "api/session/\(sessionId)/sync", parameters: report.asDictionary().mapValues({ value in "\(value)" }), callback: nil)
|
||||
}
|
||||
public static func getLibraryItemWithProgress(libraryItemId:String, episodeId:String?, callback: @escaping (_ param: LibraryItem?) -> Void) {
|
||||
var endpoint = "api/items/\(libraryItemId)?expanded=1&include=progress"
|
||||
if episodeId != nil {
|
||||
endpoint += "&episodeId=\(episodeId!)"
|
||||
}
|
||||
|
||||
ApiClient.getResource(endpoint: endpoint, decodable: LibraryItem.self) { obj in
|
||||
callback(obj)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,4 +128,24 @@ class Database {
|
||||
return instance.objects(ServerConnectionConfigActiveIndex.self).first?.index ?? nil
|
||||
}
|
||||
}
|
||||
public func setDeviceSettings(deviceSettings: DeviceSettings) {
|
||||
Database.realmQueue.sync {
|
||||
let existing = instance.objects(DeviceSettings.self)
|
||||
|
||||
do {
|
||||
try instance.write {
|
||||
instance.delete(existing)
|
||||
instance.add(deviceSettings)
|
||||
}
|
||||
} catch(let exception) {
|
||||
NSLog("failed to save device settings")
|
||||
debugPrint(exception)
|
||||
}
|
||||
}
|
||||
}
|
||||
public func getDeviceSettings() -> DeviceSettings {
|
||||
return Database.realmQueue.sync {
|
||||
return instance.objects(DeviceSettings.self).first ?? getDefaultDeviceSettings()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { AppUpdate } from '@robingenz/capacitor-app-update'
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
@@ -79,36 +77,6 @@ export default {
|
||||
this.$refs.streamContainer.streamOpen(stream)
|
||||
}
|
||||
},
|
||||
async clickUpdateToast() {
|
||||
var immediateUpdateAllowed = this.$store.state.appUpdateInfo.immediateUpdateAllowed
|
||||
if (immediateUpdateAllowed) {
|
||||
await AppUpdate.performImmediateUpdate()
|
||||
} else {
|
||||
await AppUpdate.openAppStore()
|
||||
}
|
||||
},
|
||||
async checkForUpdate() {
|
||||
if (this.$platform == 'web') return
|
||||
console.log('Checking for app update')
|
||||
const result = await AppUpdate.getAppUpdateInfo()
|
||||
if (!result) {
|
||||
console.error('Invalid version check')
|
||||
return
|
||||
}
|
||||
console.log('App Update Info', JSON.stringify(result))
|
||||
this.$store.commit('setAppUpdateInfo', result)
|
||||
if (result.updateAvailability === 2) {
|
||||
setTimeout(() => {
|
||||
this.$toast.info(`Update is available! Click to update.`, {
|
||||
draggable: false,
|
||||
hideProgressBar: false,
|
||||
timeout: 20000,
|
||||
closeButton: true,
|
||||
onClick: this.clickUpdateToast
|
||||
})
|
||||
}, 5000)
|
||||
}
|
||||
},
|
||||
async loadSavedSettings() {
|
||||
var userSavedServerSettings = await this.$localStore.getServerSettings()
|
||||
if (userSavedServerSettings) {
|
||||
@@ -202,8 +170,8 @@ export default {
|
||||
this.inittingLibraries = true
|
||||
await this.$store.dispatch('libraries/load')
|
||||
console.log(`[default] initLibraries loaded ${this.currentLibraryId}`)
|
||||
await this.$store.dispatch('libraries/fetch', this.currentLibraryId)
|
||||
this.$eventBus.$emit('library-changed')
|
||||
this.$store.dispatch('libraries/fetch', this.currentLibraryId)
|
||||
this.inittingLibraries = false
|
||||
},
|
||||
async syncLocalMediaProgress() {
|
||||
@@ -229,19 +197,73 @@ export default {
|
||||
console.log('[default] syncLocalMediaProgress No local media progress to sync')
|
||||
}
|
||||
},
|
||||
userUpdated(user) {
|
||||
async userUpdated(user) {
|
||||
if (this.user && this.user.id == user.id) {
|
||||
this.$store.commit('user/setUser', user)
|
||||
}
|
||||
},
|
||||
async userMediaProgressUpdated(prog) {
|
||||
console.log(`[default] userMediaProgressUpdate checking for local media progress ${prog.id}`)
|
||||
|
||||
// Update local media progress if exists
|
||||
var localProg = this.$store.getters['globals/getLocalMediaProgressByServerItemId'](prog.libraryItemId, prog.episodeId)
|
||||
var newLocalMediaProgress = null
|
||||
if (localProg && localProg.lastUpdate < prog.lastUpdate) {
|
||||
// Server progress is more up-to-date
|
||||
console.log(`[default] syncing progress from server with local item for "${prog.libraryItemId}" ${prog.episodeId ? `episode ${prog.episodeId}` : ''}`)
|
||||
const payload = {
|
||||
localMediaProgressId: localProg.id,
|
||||
mediaProgress: prog
|
||||
}
|
||||
newLocalMediaProgress = await this.$db.syncServerMediaProgressWithLocalMediaProgress(payload)
|
||||
} else {
|
||||
// Check if local library item exists
|
||||
var localLibraryItem = await this.$db.getLocalLibraryItemByLLId(prog.libraryItemId)
|
||||
if (localLibraryItem) {
|
||||
if (prog.episodeId) {
|
||||
// If episode check if local episode exists
|
||||
var lliEpisodes = localLibraryItem.media.episodes || []
|
||||
var localEpisode = lliEpisodes.find((ep) => ep.serverEpisodeId === prog.episodeId)
|
||||
if (localEpisode) {
|
||||
// Add new local media progress
|
||||
const payload = {
|
||||
localLibraryItemId: localLibraryItem.id,
|
||||
localEpisodeId: localEpisode.id,
|
||||
mediaProgress: prog
|
||||
}
|
||||
newLocalMediaProgress = await this.$db.syncServerMediaProgressWithLocalMediaProgress(payload)
|
||||
}
|
||||
} else {
|
||||
// Add new local media progress
|
||||
const payload = {
|
||||
localLibraryItemId: localLibraryItem.id,
|
||||
mediaProgress: prog
|
||||
}
|
||||
newLocalMediaProgress = await this.$db.syncServerMediaProgressWithLocalMediaProgress(payload)
|
||||
}
|
||||
} else {
|
||||
console.log(`[default] userMediaProgressUpdate no local media progress or lli found for this server item ${prog.id}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (newLocalMediaProgress && newLocalMediaProgress.id) {
|
||||
console.log(`[default] local media progress updated for ${newLocalMediaProgress.id}`)
|
||||
this.$store.commit('globals/updateLocalMediaProgress', newLocalMediaProgress)
|
||||
}
|
||||
}
|
||||
},
|
||||
async mounted() {
|
||||
this.$socket.on('connection-update', this.socketConnectionUpdate)
|
||||
this.$socket.on('initialized', this.socketInit)
|
||||
this.$socket.on('user_updated', this.userUpdated)
|
||||
this.$socket.on('user_media_progress_updated', this.userMediaProgressUpdated)
|
||||
|
||||
if (this.$store.state.isFirstLoad) {
|
||||
this.$store.commit('setIsFirstLoad', false)
|
||||
|
||||
const deviceData = await this.$db.getDeviceData()
|
||||
this.$store.commit('setDeviceData', deviceData)
|
||||
|
||||
await this.$store.dispatch('setupNetworkListener')
|
||||
|
||||
if (this.$store.state.user.serverConnectionConfig) {
|
||||
@@ -255,7 +277,6 @@ export default {
|
||||
console.log(`[default] finished connection attempt or already connected ${!!this.user}`)
|
||||
await this.syncLocalMediaProgress()
|
||||
this.$store.dispatch('globals/loadLocalMediaProgress')
|
||||
this.checkForUpdate()
|
||||
this.loadSavedSettings()
|
||||
this.hasMounted = true
|
||||
}
|
||||
@@ -264,6 +285,7 @@ export default {
|
||||
this.$socket.off('connection-update', this.socketConnectionUpdate)
|
||||
this.$socket.off('initialized', this.socketInit)
|
||||
this.$socket.off('user_updated', this.userUpdated)
|
||||
this.$socket.off('user_media_progress_updated', this.userMediaProgressUpdated)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "audiobookshelf-app",
|
||||
"version": "0.9.44-beta",
|
||||
"version": "0.9.51-beta",
|
||||
"author": "advplyr",
|
||||
"scripts": {
|
||||
"dev": "nuxt --hostname localhost --port 1337",
|
||||
"dev": "nuxt --hostname 0.0.0.0 --port 1337",
|
||||
"build": "nuxt build",
|
||||
"start": "nuxt start",
|
||||
"generate": "nuxt generate",
|
||||
@@ -23,7 +23,6 @@
|
||||
"@capacitor/status-bar": "^1.0.8",
|
||||
"@capacitor/storage": "^1.2.5",
|
||||
"@nuxtjs/axios": "^5.13.6",
|
||||
"@robingenz/capacitor-app-update": "^1.3.1",
|
||||
"core-js": "^3.15.1",
|
||||
"date-fns": "^2.25.0",
|
||||
"epubjs": "^0.3.88",
|
||||
|
||||
@@ -19,19 +19,10 @@
|
||||
</div>
|
||||
|
||||
<p class="font-mono pt-1 pb-4">{{ $config.version }}</p>
|
||||
|
||||
<ui-btn v-if="isUpdateAvailable" class="w-full my-4" color="success" @click="clickUpdate">Update is available</ui-btn>
|
||||
|
||||
<ui-btn v-if="!isUpdateAvailable || immediateUpdateAllowed" class="w-full my-4" color="primary" @click="openAppStore">Open app store</ui-btn>
|
||||
|
||||
<p class="text-xs text-gray-400">UA: {{ updateAvailability }} | Avail: {{ availableVersion }} | Curr: {{ currentVersion }} | ImmedAllowed: {{ immediateUpdateAllowed }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { AppUpdate } from '@robingenz/capacitor-app-update'
|
||||
import { AbsAudioPlayer } from '@/plugins/capacitor'
|
||||
|
||||
export default {
|
||||
asyncData({ redirect, store }) {
|
||||
if (!store.state.socketConnected) {
|
||||
@@ -58,43 +49,21 @@ export default {
|
||||
},
|
||||
serverAddress() {
|
||||
return this.serverConnectionConfig.address
|
||||
},
|
||||
appUpdateInfo() {
|
||||
return this.$store.state.appUpdateInfo
|
||||
},
|
||||
availableVersion() {
|
||||
return this.appUpdateInfo ? this.appUpdateInfo.availableVersion : null
|
||||
},
|
||||
currentVersion() {
|
||||
return this.appUpdateInfo ? this.appUpdateInfo.currentVersion : null
|
||||
},
|
||||
immediateUpdateAllowed() {
|
||||
return this.appUpdateInfo ? !!this.appUpdateInfo.immediateUpdateAllowed : false
|
||||
},
|
||||
updateAvailability() {
|
||||
return this.appUpdateInfo ? this.appUpdateInfo.updateAvailability : null
|
||||
},
|
||||
isUpdateAvailable() {
|
||||
return this.updateAvailability === 2
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async logout() {
|
||||
await this.$axios.$post('/logout').catch((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
this.$server.logout()
|
||||
this.$router.push('/connect')
|
||||
},
|
||||
openAppStore() {
|
||||
AppUpdate.openAppStore()
|
||||
},
|
||||
async clickUpdate() {
|
||||
if (this.immediateUpdateAllowed) {
|
||||
AppUpdate.performImmediateUpdate()
|
||||
} else {
|
||||
AppUpdate.openAppStore()
|
||||
if (this.user) {
|
||||
await this.$axios.$post('/logout').catch((error) => {
|
||||
console.error(error)
|
||||
})
|
||||
}
|
||||
|
||||
this.$socket.logout()
|
||||
await this.$db.logout()
|
||||
this.$localStore.removeLastLibraryId()
|
||||
this.$store.commit('user/logout')
|
||||
this.$router.push('/connect')
|
||||
}
|
||||
},
|
||||
mounted() {}
|
||||
|
||||
@@ -4,10 +4,6 @@
|
||||
<home-bookshelf-toolbar v-show="!isHome" />
|
||||
<div id="bookshelf-wrapper" class="main-content overflow-y-auto overflow-x-hidden relative" :class="isHome ? 'home-page' : ''">
|
||||
<nuxt-child />
|
||||
|
||||
<!-- <div v-if="isLoading" class="absolute top-0 left-0 w-full h-full flex items-center justify-center">
|
||||
<ui-loading-indicator />
|
||||
</div>-->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -135,7 +135,7 @@ export default {
|
||||
}
|
||||
this.loading = false
|
||||
},
|
||||
async libraryChanged(libid) {
|
||||
async libraryChanged() {
|
||||
if (this.currentLibraryId) {
|
||||
await this.fetchCategories()
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
<covers-collection-cover :book-items="bookItems" :width="240" :height="120 * bookCoverAspectRatio" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-grow px-2 py-6 md:py-0 md:px-10">
|
||||
<div class="flex items-center">
|
||||
<div class="flex-grow py-6">
|
||||
<div class="flex items-center px-2">
|
||||
<h1 class="text-xl font-sans">
|
||||
{{ collectionName }}
|
||||
</h1>
|
||||
@@ -18,7 +18,7 @@
|
||||
</ui-btn>
|
||||
</div>
|
||||
|
||||
<div class="my-8 max-w-2xl">
|
||||
<div class="my-8 max-w-2xl px-2">
|
||||
<p class="text-base text-gray-100">{{ description }}</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
<!-- <p class="absolute bottom-16 left-0 right-0 px-2 text-center text-error"><strong>Important!</strong> This app requires that you are running <u>your own server</u> and does not provide any content.</p> -->
|
||||
|
||||
<connection-server-connect-form />
|
||||
<connection-server-connect-form v-if="deviceData" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-center pt-4 fixed bottom-4 left-0 right-0">
|
||||
@@ -32,7 +32,9 @@
|
||||
export default {
|
||||
layout: 'blank',
|
||||
data() {
|
||||
return {}
|
||||
return {
|
||||
deviceData: null
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
networkConnected() {
|
||||
@@ -41,6 +43,8 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
async init() {
|
||||
this.deviceData = await this.$db.getDeviceData()
|
||||
this.$store.commit('setDeviceData', this.deviceData)
|
||||
await this.$store.dispatch('setupNetworkListener')
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,60 +1,100 @@
|
||||
<template>
|
||||
<div class="w-full h-full px-3 py-4 overflow-y-auto">
|
||||
<div class="flex">
|
||||
<div class="w-32">
|
||||
<div class="relative">
|
||||
<covers-book-cover :library-item="libraryItem" :width="128" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
<div v-if="!isPodcast" class="absolute bottom-0 left-0 h-1.5 shadow-sm z-10" :class="userIsFinished ? 'bg-success' : 'bg-yellow-400'" :style="{ width: 128 * progressPercent + 'px' }"></div>
|
||||
<div class="w-16">
|
||||
<div class="relative" @click="showFullscreenCover = true">
|
||||
<covers-book-cover :library-item="libraryItem" :width="64" :book-cover-aspect-ratio="bookCoverAspectRatio" />
|
||||
<div v-if="!isPodcast" class="absolute bottom-0 left-0 h-1 shadow-sm z-10" :class="userIsFinished ? 'bg-success' : 'bg-yellow-400'" :style="{ width: 64 * progressPercent + 'px' }"></div>
|
||||
</div>
|
||||
<!-- Show an indicator for local library items whether they are linked to a server item and if that server item is connected -->
|
||||
<p v-if="isLocal && serverLibraryItemId" style="font-size: 10px" class="text-success py-1 uppercase tracking-widest">connected</p>
|
||||
<p v-else-if="isLocal && libraryItem.serverAddress" style="font-size: 10px" class="text-gray-400 py-1">{{ libraryItem.serverAddress }}</p>
|
||||
</div>
|
||||
<div class="flex-grow px-3">
|
||||
<h1 class="text-lg">{{ title }}</h1>
|
||||
<h3 v-if="seriesName" class="text-gray-300 text-sm leading-6">{{ seriesName }}</h3>
|
||||
<p class="text-sm text-gray-400">by {{ author }}</p>
|
||||
<p v-if="numTracks" class="text-gray-300 text-sm my-1">
|
||||
{{ $elapsedPretty(duration) }}
|
||||
<span v-if="!isLocal" class="px-4">{{ $bytesPretty(size) }}</span>
|
||||
<div class="title-container flex-grow pl-2">
|
||||
<div class="flex relative pr-6">
|
||||
<h1 class="text-base">{{ title }}</h1>
|
||||
|
||||
<button class="absolute top-0 right-0 h-full px-1 outline-none" @click="moreButtonPress">
|
||||
<span class="material-icons text-xl">more_vert</span>
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="seriesList && seriesList.length" class="text-sm text-gray-300 py-0.5">
|
||||
<template v-for="(series, index) in seriesList"
|
||||
><nuxt-link :key="series.id" :to="`/bookshelf/series/${series.id}`">{{ series.text }}</nuxt-link
|
||||
><span :key="`${series.id}-comma`" v-if="index < seriesList.length - 1">, </span></template
|
||||
>
|
||||
</p>
|
||||
<p v-if="numTracks" class="text-gray-300 text-sm my-1">{{ numTracks }} Tracks</p>
|
||||
<p v-if="podcastAuthor" class="text-sm text-gray-400 py-0.5">By {{ podcastAuthor }}</p>
|
||||
<p v-else-if="bookAuthors && bookAuthors.length" class="text-sm text-gray-400 py-0.5">
|
||||
By
|
||||
<template v-for="(author, index) in bookAuthors"
|
||||
><nuxt-link :key="author.id" :to="`/bookshelf/library?filter=authors.${$encode(author.id)}`">{{ author.name }}</nuxt-link
|
||||
><span :key="`${author.id}-comma`" v-if="index < bookAuthors.length - 1">, </span></template
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!isPodcast && progressPercent > 0" class="px-4 py-2 bg-primary text-sm font-semibold rounded-md text-gray-200 mt-4 relative" :class="resettingProgress ? 'opacity-25' : ''">
|
||||
<p class="leading-6">Your Progress: {{ Math.round(progressPercent * 100) }}%</p>
|
||||
<p v-if="progressPercent < 1" class="text-gray-400 text-xs">{{ $elapsedPretty(userTimeRemaining) }} remaining</p>
|
||||
<p v-else class="text-gray-400 text-xs">Finished {{ $formatDate(userProgressFinishedAt) }}</p>
|
||||
<div v-if="!resettingProgress" class="absolute -top-1.5 -right-1.5 p-1 w-5 h-5 rounded-full bg-bg hover:bg-error border border-primary flex items-center justify-center cursor-pointer" @click.stop="clearProgressClick">
|
||||
<span class="material-icons text-sm">close</span>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="narrators && narrators.length" class="text-sm text-gray-400 py-0.5">
|
||||
Narrated By
|
||||
<template v-for="(narrator, index) in narrators"
|
||||
><nuxt-link :key="narrator" :to="`/bookshelf/library?filter=narrators.${$encode(narrator)}`">{{ narrator }}</nuxt-link
|
||||
><span :key="`${narrator}-comma`" v-if="index < narrators.length - 1">, </span></template
|
||||
>
|
||||
</p>
|
||||
|
||||
<div v-if="isLocal" class="flex mt-4">
|
||||
<ui-btn color="success" :disabled="isPlaying" class="flex items-center justify-center flex-grow mr-2" :padding-x="4" @click="playClick">
|
||||
<span v-show="!isPlaying" class="material-icons">play_arrow</span>
|
||||
<span class="px-1 text-sm">{{ isPlaying ? 'Playing' : 'Play' }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="showRead" color="info" class="flex items-center justify-center mr-2" :class="showPlay ? '' : 'flex-grow'" :padding-x="2" @click="readBook">
|
||||
<span class="material-icons">auto_stories</span>
|
||||
<span v-if="!showPlay" class="px-2 text-base">Read {{ ebookFormat }}</span>
|
||||
</ui-btn>
|
||||
<ui-read-icon-btn v-if="!isPodcast" :disabled="isProcessingReadUpdate" :is-read="userIsFinished" class="flex items-center justify-center" @click="toggleFinished" />
|
||||
</div>
|
||||
<div v-else-if="(user && (showPlay || showRead)) || hasLocal" class="flex mt-4">
|
||||
<ui-btn v-if="showPlay" color="success" :disabled="isPlaying" class="flex items-center justify-center flex-grow mr-2" :padding-x="4" @click="playClick">
|
||||
<span v-show="!isPlaying" class="material-icons">play_arrow</span>
|
||||
<span class="px-1 text-sm">{{ isPlaying ? (isStreaming ? 'Streaming' : 'Playing') : hasLocal ? 'Play' : 'Stream' }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="showRead && user" color="info" class="flex items-center justify-center mr-2" :class="showPlay ? '' : 'flex-grow'" :padding-x="2" @click="readBook">
|
||||
<span class="material-icons">auto_stories</span>
|
||||
<span v-if="!showPlay" class="px-2 text-base">Read {{ ebookFormat }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="user && showPlay && !isIos && !hasLocal" :color="downloadItem ? 'warning' : 'primary'" class="flex items-center justify-center mr-2" :padding-x="2" @click="downloadClick">
|
||||
<span class="material-icons" :class="downloadItem ? 'animate-pulse' : ''">{{ downloadItem ? 'downloading' : 'download' }}</span>
|
||||
</ui-btn>
|
||||
<ui-read-icon-btn v-if="!isPodcast" :disabled="isProcessingReadUpdate" :is-read="userIsFinished" class="flex items-center justify-center" @click="toggleFinished" />
|
||||
<!-- Show an indicator for local library items whether they are linked to a server item and if that server item is connected -->
|
||||
<p v-if="isLocal && serverLibraryItemId" style="font-size: 10px" class="text-success py-1 uppercase tracking-widest">connected</p>
|
||||
<p v-else-if="isLocal && libraryItem.serverAddress" style="font-size: 10px" class="text-gray-400 py-1">{{ libraryItem.serverAddress }}</p>
|
||||
|
||||
<div v-if="numTracks" class="flex text-gray-100 text-xs my-2 -mx-0.5">
|
||||
<div class="bg-primary bg-opacity-80 px-3 py-0.5 rounded-full mx-0.5">
|
||||
<p>{{ $elapsedPretty(duration) }}</p>
|
||||
</div>
|
||||
<!-- TODO: Local books dont save the size -->
|
||||
<div v-if="size" class="bg-primary bg-opacity-80 px-3 py-0.5 rounded-full mx-0.5">
|
||||
<p>{{ $bytesPretty(size) }}</p>
|
||||
</div>
|
||||
<div class="bg-primary bg-opacity-80 px-3 py-0.5 rounded-full mx-0.5">
|
||||
<p>{{ numTracks }} Track{{ numTracks > 1 ? 's' : '' }}</p>
|
||||
</div>
|
||||
<div v-if="numChapters" class="bg-primary bg-opacity-80 px-3 py-0.5 rounded-full mx-0.5">
|
||||
<p>{{ numChapters }} Chapter{{ numChapters > 1 ? 's' : '' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div v-if="!isPodcast && progressPercent > 0" class="px-4 py-2 bg-primary text-sm font-semibold rounded-md text-gray-200 mt-4 relative" :class="resettingProgress ? 'opacity-25' : ''">
|
||||
<p class="leading-6">Your Progress: {{ Math.round(progressPercent * 100) }}%</p>
|
||||
<p v-if="progressPercent < 1" class="text-gray-400 text-xs">{{ $elapsedPretty(userTimeRemaining) }} remaining</p>
|
||||
<p v-else class="text-gray-400 text-xs">Finished {{ $formatDate(userProgressFinishedAt) }}</p>
|
||||
<div v-if="!resettingProgress" class="absolute -top-1.5 -right-1.5 p-1 w-5 h-5 rounded-full bg-bg hover:bg-error border border-primary flex items-center justify-center cursor-pointer" @click.stop="clearProgressClick">
|
||||
<span class="material-icons text-sm">close</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isLocal" class="flex mt-4">
|
||||
<ui-btn v-if="showPlay" color="success" :disabled="isPlaying" class="flex items-center justify-center flex-grow mr-2" :padding-x="4" @click="playClick">
|
||||
<span v-show="!isPlaying" class="material-icons">play_arrow</span>
|
||||
<span class="px-1 text-sm">{{ isPlaying ? 'Playing' : 'Play' }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="showRead" color="info" class="flex items-center justify-center mr-2" :class="showPlay ? '' : 'flex-grow'" :padding-x="2" @click="readBook">
|
||||
<span class="material-icons">auto_stories</span>
|
||||
<span v-if="!showPlay" class="px-2 text-base">Read {{ ebookFormat }}</span>
|
||||
</ui-btn>
|
||||
<ui-read-icon-btn v-if="!isPodcast" :disabled="isProcessingReadUpdate" :is-read="userIsFinished" class="flex items-center justify-center" @click="toggleFinished" />
|
||||
</div>
|
||||
<div v-else-if="(user && (showPlay || showRead)) || hasLocal" class="flex mt-4">
|
||||
<ui-btn v-if="showPlay" color="success" :disabled="isPlaying" class="flex items-center justify-center flex-grow mr-2" :padding-x="4" @click="playClick">
|
||||
<span v-show="!isPlaying" class="material-icons">play_arrow</span>
|
||||
<span class="px-1 text-sm">{{ isPlaying ? (isStreaming ? 'Streaming' : 'Playing') : hasLocal ? 'Play' : 'Stream' }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="showRead && user" color="info" class="flex items-center justify-center mr-2" :class="showPlay ? '' : 'flex-grow'" :padding-x="2" @click="readBook">
|
||||
<span class="material-icons">auto_stories</span>
|
||||
<span v-if="!showPlay" class="px-2 text-base">Read {{ ebookFormat }}</span>
|
||||
</ui-btn>
|
||||
<ui-btn v-if="showDownload" :color="downloadItem ? 'warning' : 'primary'" class="flex items-center justify-center mr-2" :padding-x="2" @click="downloadClick">
|
||||
<span class="material-icons" :class="downloadItem ? 'animate-pulse' : ''">{{ downloadItem ? 'downloading' : 'download' }}</span>
|
||||
</ui-btn>
|
||||
<ui-read-icon-btn v-if="!isPodcast" :disabled="isProcessingReadUpdate" :is-read="userIsFinished" class="flex items-center justify-center" @click="toggleFinished" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="downloadItem" class="py-3">
|
||||
@@ -68,6 +108,12 @@
|
||||
<tables-podcast-episodes-table v-if="isPodcast" :library-item-id="libraryItemId" :local-library-item-id="localLibraryItemId" :episodes="episodes" :local-episodes="localLibraryItemEpisodes" :is-local="isLocal" />
|
||||
|
||||
<modals-select-local-folder-modal v-model="showSelectLocalFolder" :media-type="mediaType" @select="selectedLocalFolder" />
|
||||
|
||||
<modals-dialog v-model="showMoreMenu" title="" :items="moreMenuItems" @action="moreMenuAction" />
|
||||
|
||||
<modals-item-details-modal v-model="showDetailsModal" :library-item="libraryItem" />
|
||||
|
||||
<modals-fullscreen-cover v-model="showFullscreenCover" :library-item="libraryItem" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -82,7 +128,7 @@ export default {
|
||||
console.log(libraryItemId)
|
||||
if (libraryItemId.startsWith('local')) {
|
||||
libraryItem = await app.$db.getLocalLibraryItem(libraryItemId)
|
||||
console.log('Got lli', libraryItem)
|
||||
console.log('Got lli', libraryItemId)
|
||||
} else if (store.state.user.serverConnectionConfig) {
|
||||
libraryItem = await app.$axios.$get(`/api/items/${libraryItemId}?expanded=1`).catch((error) => {
|
||||
console.error('Failed', error)
|
||||
@@ -110,13 +156,19 @@ export default {
|
||||
return {
|
||||
resettingProgress: false,
|
||||
isProcessingReadUpdate: false,
|
||||
showSelectLocalFolder: false
|
||||
showSelectLocalFolder: false,
|
||||
showMoreMenu: false,
|
||||
showDetailsModal: false,
|
||||
showFullscreenCover: false
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
isIos() {
|
||||
return this.$platform === 'ios'
|
||||
},
|
||||
userCanDownload() {
|
||||
return this.$store.getters['user/getUserCanDownload']
|
||||
},
|
||||
isLocal() {
|
||||
return this.libraryItem.isLocal
|
||||
},
|
||||
@@ -166,9 +218,17 @@ export default {
|
||||
title() {
|
||||
return this.mediaMetadata.title
|
||||
},
|
||||
author() {
|
||||
if (this.isPodcast) return this.mediaMetadata.author
|
||||
return this.mediaMetadata.authorName
|
||||
podcastAuthor() {
|
||||
if (!this.isPodcast) return null
|
||||
return this.mediaMetadata.author || ''
|
||||
},
|
||||
bookAuthors() {
|
||||
if (this.isPodcast) return null
|
||||
return this.mediaMetadata.authors || []
|
||||
},
|
||||
narrators() {
|
||||
if (this.isPodcast) return null
|
||||
return this.mediaMetadata.narrators || []
|
||||
},
|
||||
description() {
|
||||
return this.mediaMetadata.description || ''
|
||||
@@ -176,9 +236,16 @@ export default {
|
||||
series() {
|
||||
return this.mediaMetadata.series || []
|
||||
},
|
||||
seriesName() {
|
||||
// For books only on toJSONExpanded
|
||||
return this.mediaMetadata.seriesName || ''
|
||||
seriesList() {
|
||||
if (this.isPodcast) return null
|
||||
return this.series.map((se) => {
|
||||
var text = se.name
|
||||
if (se.sequence) text += ` #${se.sequence}`
|
||||
return {
|
||||
...se,
|
||||
text
|
||||
}
|
||||
})
|
||||
},
|
||||
duration() {
|
||||
return this.media.duration
|
||||
@@ -223,6 +290,10 @@ export default {
|
||||
if (!this.media.tracks) return 0
|
||||
return this.media.tracks.length || 0
|
||||
},
|
||||
numChapters() {
|
||||
if (!this.media.chapters) return 0
|
||||
return this.media.chapters.length || 0
|
||||
},
|
||||
isMissing() {
|
||||
return this.libraryItem.isMissing
|
||||
},
|
||||
@@ -235,6 +306,10 @@ export default {
|
||||
showRead() {
|
||||
return this.ebookFile && this.ebookFormat !== 'pdf'
|
||||
},
|
||||
showDownload() {
|
||||
if (this.isIos) return false
|
||||
return this.user && this.userCanDownload && this.showPlay && !this.hasLocal
|
||||
},
|
||||
ebookFile() {
|
||||
return this.media.ebookFile
|
||||
},
|
||||
@@ -242,9 +317,6 @@ export default {
|
||||
if (!this.ebookFile) return null
|
||||
return this.ebookFile.ebookFormat
|
||||
},
|
||||
hasStoragePermission() {
|
||||
return this.$store.state.hasStoragePermission
|
||||
},
|
||||
downloadItem() {
|
||||
return this.$store.getters['globals/getDownloadItem'](this.libraryItemId)
|
||||
},
|
||||
@@ -253,9 +325,41 @@ export default {
|
||||
},
|
||||
isCasting() {
|
||||
return this.$store.state.isCasting
|
||||
},
|
||||
moreMenuItems() {
|
||||
if (this.isLocal) {
|
||||
return [
|
||||
{
|
||||
text: 'Manage Local Files',
|
||||
value: 'manageLocal'
|
||||
},
|
||||
{
|
||||
text: 'View Details',
|
||||
value: 'details'
|
||||
}
|
||||
]
|
||||
} else {
|
||||
return [
|
||||
{
|
||||
text: 'View Details',
|
||||
value: 'details'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
moreMenuAction(action) {
|
||||
this.showMoreMenu = false
|
||||
if (action === 'manageLocal') {
|
||||
this.$router.push(`/localMedia/item/${this.libraryItemId}`)
|
||||
} else if (action === 'details') {
|
||||
this.showDetailsModal = true
|
||||
}
|
||||
},
|
||||
moreButtonPress() {
|
||||
this.showMoreMenu = true
|
||||
},
|
||||
readBook() {
|
||||
this.$store.commit('openReader', this.libraryItem)
|
||||
},
|
||||
@@ -279,7 +383,7 @@ export default {
|
||||
if (this.isLocal) {
|
||||
// TODO: If connected to server also sync with server
|
||||
await this.$db.removeLocalMediaProgress(this.libraryItemId)
|
||||
this.$store.commit('globals/removeLocalMediaProgress', this.libraryItemId)
|
||||
this.$store.commit('globals/removeLocalMediaProgressForItem', this.libraryItemId)
|
||||
} else {
|
||||
var progressId = this.userItemProgress.id
|
||||
await this.$axios
|
||||
@@ -319,13 +423,17 @@ export default {
|
||||
if (this.downloadItem) {
|
||||
return
|
||||
}
|
||||
this.download()
|
||||
},
|
||||
async download(selectedLocalFolder = null) {
|
||||
if (!this.numTracks) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.isIos) {
|
||||
// no local folders on iOS
|
||||
this.startDownload()
|
||||
} else {
|
||||
this.download()
|
||||
}
|
||||
},
|
||||
async download(selectedLocalFolder = null) {
|
||||
// Get the local folder to download to
|
||||
var localFolder = selectedLocalFolder
|
||||
if (!localFolder) {
|
||||
@@ -363,9 +471,15 @@ export default {
|
||||
this.startDownload(localFolder)
|
||||
}
|
||||
},
|
||||
async startDownload(localFolder) {
|
||||
console.log('Starting download to local folder', localFolder.name)
|
||||
var downloadRes = await AbsDownloader.downloadLibraryItem({ libraryItemId: this.libraryItemId, localFolderId: localFolder.id })
|
||||
async startDownload(localFolder = null) {
|
||||
const payload = {
|
||||
libraryItemId: this.libraryItemId
|
||||
}
|
||||
if (localFolder) {
|
||||
console.log('Starting download to local folder', localFolder.name)
|
||||
payload.localFolderId = localFolder.id
|
||||
}
|
||||
var downloadRes = await AbsDownloader.downloadLibraryItem(payload)
|
||||
if (downloadRes && downloadRes.error) {
|
||||
var errorMsg = downloadRes.error || 'Unknown error'
|
||||
console.error('Download error', errorMsg)
|
||||
@@ -432,4 +546,11 @@ export default {
|
||||
this.$socket.off('item_updated', this.itemUpdated)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.title-container {
|
||||
width: calc(100% - 64px);
|
||||
max-width: calc(100% - 64px);
|
||||
}
|
||||
</style>
|
||||
@@ -189,7 +189,7 @@ export default {
|
||||
if (this.selectedAudioTrack || this.selectedEpisode) {
|
||||
return [
|
||||
{
|
||||
text: 'Hard Delete',
|
||||
text: 'Remove & Delete Files',
|
||||
value: 'track-delete'
|
||||
}
|
||||
]
|
||||
@@ -208,7 +208,7 @@ export default {
|
||||
value: 'remove'
|
||||
},
|
||||
{
|
||||
text: 'Hard Delete',
|
||||
text: 'Remove & Delete Files',
|
||||
value: 'delete'
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="w-full h-full p-8">
|
||||
<div class="flex items-center py-3" @click="toggleDisableAutoRewind">
|
||||
<div v-if="$platform !== 'ios'" class="flex items-center py-3" @click="toggleDisableAutoRewind">
|
||||
<div class="w-10 flex justify-center">
|
||||
<ui-toggle-switch v-model="settings.disableAutoRewind" @input="saveSettings" />
|
||||
</div>
|
||||
@@ -12,9 +12,9 @@
|
||||
</div>
|
||||
<p class="pl-4">Jump backwards time</p>
|
||||
</div>
|
||||
<div class="flex items-center py-3" @click="toggleJumpForwards">
|
||||
<div class="flex items-center py-3" @click="toggleJumpForward">
|
||||
<div class="w-10 flex justify-center">
|
||||
<span class="material-icons text-4xl">{{ currentJumpForwardsTimeIcon }}</span>
|
||||
<span class="material-icons text-4xl">{{ currentJumpForwardTimeIcon }}</span>
|
||||
</div>
|
||||
<p class="pl-4">Jump forwards time</p>
|
||||
</div>
|
||||
@@ -25,53 +25,34 @@
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
deviceData: null,
|
||||
settings: {
|
||||
disableAutoRewind: false,
|
||||
jumpForwardsTime: 10000,
|
||||
jumpBackwardsTime: 10000
|
||||
},
|
||||
jumpForwardsItems: [
|
||||
{
|
||||
icon: 'forward_5',
|
||||
value: 5000
|
||||
},
|
||||
{
|
||||
icon: 'forward_10',
|
||||
value: 10000
|
||||
},
|
||||
{
|
||||
icon: 'forward_30',
|
||||
value: 30000
|
||||
}
|
||||
],
|
||||
jumpBackwardsItems: [
|
||||
{
|
||||
icon: 'replay_5',
|
||||
value: 5000
|
||||
},
|
||||
{
|
||||
icon: 'replay_10',
|
||||
value: 10000
|
||||
},
|
||||
{
|
||||
icon: 'replay_30',
|
||||
value: 30000
|
||||
}
|
||||
]
|
||||
jumpForwardTime: 10,
|
||||
jumpBackwardsTime: 10
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
currentJumpForwardsTimeIcon() {
|
||||
return this.jumpForwardsItems[this.currentJumpForwardsTimeIndex].icon
|
||||
jumpForwardItems() {
|
||||
return this.$store.state.globals.jumpForwardItems || []
|
||||
},
|
||||
currentJumpForwardsTimeIndex() {
|
||||
return this.jumpForwardsItems.findIndex((jfi) => jfi.value === this.settings.jumpForwardsTime)
|
||||
jumpBackwardsItems() {
|
||||
return this.$store.state.globals.jumpBackwardsItems || []
|
||||
},
|
||||
currentJumpForwardTimeIcon() {
|
||||
return this.jumpForwardItems[this.currentJumpForwardTimeIndex].icon
|
||||
},
|
||||
currentJumpForwardTimeIndex() {
|
||||
var index = this.jumpForwardItems.findIndex((jfi) => jfi.value === this.settings.jumpForwardTime)
|
||||
return index >= 0 ? index : 1
|
||||
},
|
||||
currentJumpBackwardsTimeIcon() {
|
||||
return this.jumpBackwardsItems[this.currentJumpBackwardsTimeIndex].icon
|
||||
},
|
||||
currentJumpBackwardsTimeIndex() {
|
||||
return this.jumpBackwardsItems.findIndex((jfi) => jfi.value === this.settings.jumpBackwardsTime)
|
||||
var index = this.jumpBackwardsItems.findIndex((jfi) => jfi.value === this.settings.jumpBackwardsTime)
|
||||
return index >= 0 ? index : 1
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -79,24 +60,37 @@ export default {
|
||||
this.settings.disableAutoRewind = !this.settings.disableAutoRewind
|
||||
this.saveSettings()
|
||||
},
|
||||
toggleJumpForwards() {
|
||||
var next = (this.currentJumpForwardsTimeIndex + 1) % 3
|
||||
this.settings.jumpForwardsTime = this.jumpForwardsItems[next].value
|
||||
toggleJumpForward() {
|
||||
var next = (this.currentJumpForwardTimeIndex + 1) % 3
|
||||
this.settings.jumpForwardTime = this.jumpForwardItems[next].value
|
||||
this.saveSettings()
|
||||
},
|
||||
toggleJumpBackwards() {
|
||||
var next = (this.currentJumpBackwardsTimeIndex + 4) % 3
|
||||
console.log('next', next)
|
||||
if (next > 2) return
|
||||
this.settings.jumpBackwardsTime = this.jumpBackwardsItems[next].value
|
||||
this.saveSettings()
|
||||
},
|
||||
saveSettings() {
|
||||
// TODO: Save settings
|
||||
async saveSettings() {
|
||||
const updatedDeviceData = await this.$db.updateDeviceSettings({ ...this.settings })
|
||||
console.log('Saved device data', updatedDeviceData)
|
||||
if (updatedDeviceData) {
|
||||
this.$store.commit('setDeviceData', updatedDeviceData)
|
||||
this.init()
|
||||
}
|
||||
},
|
||||
async init() {
|
||||
this.deviceData = await this.$db.getDeviceData()
|
||||
this.$store.commit('setDeviceData', this.deviceData)
|
||||
|
||||
const deviceSettings = this.deviceData.deviceSettings || {}
|
||||
this.settings.disableAutoRewind = !!deviceSettings.disableAutoRewind
|
||||
this.settings.jumpForwardTime = deviceSettings.jumpForwardTime || 10
|
||||
this.settings.jumpBackwardsTime = deviceSettings.jumpBackwardsTime || 10
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
// TODO: Load settings
|
||||
this.init()
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -4,6 +4,14 @@ export default function ({ $axios, store }) {
|
||||
if (config.url.startsWith('http:') || config.url.startsWith('https:')) {
|
||||
return
|
||||
}
|
||||
|
||||
var customHeaders = store.getters['user/getCustomHeaders']
|
||||
if (customHeaders) {
|
||||
for (const key in customHeaders) {
|
||||
config.headers.common[key] = customHeaders[key]
|
||||
}
|
||||
}
|
||||
|
||||
var bearerToken = store.getters['user/getToken']
|
||||
if (bearerToken) {
|
||||
config.headers.common['Authorization'] = `Bearer ${bearerToken}`
|
||||
|
||||
@@ -131,6 +131,11 @@ class AbsAudioPlayerWeb extends WebPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
// PluginMethod
|
||||
async getIsCastAvailable() {
|
||||
return false
|
||||
}
|
||||
|
||||
initializePlayer() {
|
||||
if (document.getElementById('audio-player')) {
|
||||
document.getElementById('audio-player').remove()
|
||||
@@ -187,6 +192,7 @@ class AbsAudioPlayerWeb extends WebPlugin {
|
||||
return
|
||||
}
|
||||
this.player.currentTime = this.trackStartTime
|
||||
|
||||
this.sendPlaybackMetadata(PlayerState.READY)
|
||||
if (this.playWhenReady) {
|
||||
this.player.play()
|
||||
@@ -195,10 +201,9 @@ class AbsAudioPlayerWeb extends WebPlugin {
|
||||
evtTimeupdate() { }
|
||||
|
||||
sendPlaybackMetadata(playerState) {
|
||||
var currentTime = this.player ? this.player.currentTime || 0 : 0
|
||||
this.notifyListeners('onMetadata', {
|
||||
duration: this.totalDuration,
|
||||
currentTime,
|
||||
currentTime: this.overallCurrentTime,
|
||||
playerState
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,7 +13,8 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
const deviceData = {
|
||||
serverConnectionConfigs: [],
|
||||
lastServerConnectionConfigId: null,
|
||||
currentLocalPlaybackSession: null
|
||||
currentLocalPlaybackSession: null,
|
||||
deviceSettings: {}
|
||||
}
|
||||
return deviceData
|
||||
}
|
||||
@@ -28,6 +29,7 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
ssc.token = serverConnectionConfig.token
|
||||
ssc.userId = serverConnectionConfig.userId
|
||||
ssc.username = serverConnectionConfig.username
|
||||
ssc.customHeaders = serverConnectionConfig.customHeaders || {}
|
||||
localStorage.setItem('device', JSON.stringify(deviceData))
|
||||
} else {
|
||||
ssc = {
|
||||
@@ -37,7 +39,8 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
userId: serverConnectionConfig.userId,
|
||||
username: serverConnectionConfig.username,
|
||||
address: serverConnectionConfig.address,
|
||||
token: serverConnectionConfig.token
|
||||
token: serverConnectionConfig.token,
|
||||
customHeaders: serverConnectionConfig.customHeaders || {}
|
||||
}
|
||||
deviceData.serverConnectionConfigs.push(ssc)
|
||||
deviceData.lastServerConnectionConfigId = ssc.id
|
||||
@@ -49,7 +52,7 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
async removeServerConnectionConfig(serverConnectionConfigCallObject) {
|
||||
var serverConnectionConfigId = serverConnectionConfigCallObject.serverConnectionConfigId
|
||||
var deviceData = await this.getDeviceData()
|
||||
deviceData.serverConnectionConfigs = deviceData.serverConnectionConfigs.filter(ssc => ssc.id == serverConnectionConfigId)
|
||||
deviceData.serverConnectionConfigs = deviceData.serverConnectionConfigs.filter(ssc => ssc.id != serverConnectionConfigId)
|
||||
localStorage.setItem('device', JSON.stringify(deviceData))
|
||||
}
|
||||
|
||||
@@ -195,6 +198,10 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
return null
|
||||
}
|
||||
|
||||
async syncServerMediaProgressWithLocalMediaProgress(payload) {
|
||||
return null
|
||||
}
|
||||
|
||||
async updateLocalTrackOrder({ localLibraryItemId, tracks }) {
|
||||
return []
|
||||
}
|
||||
@@ -203,6 +210,13 @@ class AbsDatabaseWeb extends WebPlugin {
|
||||
// { localLibraryItemId, localEpisodeId, isFinished }
|
||||
return null
|
||||
}
|
||||
|
||||
async updateDeviceSettings(payload) {
|
||||
var deviceData = await this.getDeviceData()
|
||||
deviceData.deviceSettings = payload
|
||||
localStorage.setItem('device', JSON.stringify(deviceData))
|
||||
return deviceData
|
||||
}
|
||||
}
|
||||
|
||||
const AbsDatabase = registerPlugin('AbsDatabase', {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { AbsDatabase } from './capacitor/AbsDatabase'
|
||||
|
||||
const isWeb = Capacitor.getPlatform() == 'web'
|
||||
|
||||
class DbService {
|
||||
constructor() { }
|
||||
|
||||
@@ -73,6 +70,10 @@ class DbService {
|
||||
return AbsDatabase.syncLocalMediaProgressWithServer()
|
||||
}
|
||||
|
||||
syncServerMediaProgressWithLocalMediaProgress(payload) {
|
||||
return AbsDatabase.syncServerMediaProgressWithLocalMediaProgress(payload)
|
||||
}
|
||||
|
||||
updateLocalTrackOrder(payload) {
|
||||
return AbsDatabase.updateLocalTrackOrder(payload)
|
||||
}
|
||||
@@ -81,6 +82,10 @@ class DbService {
|
||||
updateLocalMediaProgressFinished(payload) {
|
||||
return AbsDatabase.updateLocalMediaProgressFinished(payload)
|
||||
}
|
||||
|
||||
updateDeviceSettings(payload) {
|
||||
return AbsDatabase.updateDeviceSettings(payload)
|
||||
}
|
||||
}
|
||||
|
||||
export default ({ app, store }, inject) => {
|
||||
|
||||
@@ -14,21 +14,6 @@ if (Capacitor.getPlatform() != 'web') {
|
||||
setStatusBarStyleDark()
|
||||
}
|
||||
|
||||
App.addListener('backButton', async ({ canGoBack }) => {
|
||||
if (!canGoBack) {
|
||||
const { value } = await Dialog.confirm({
|
||||
title: 'Confirm',
|
||||
message: `Did you want to exit the app?`,
|
||||
})
|
||||
if (value) {
|
||||
App.exitApp()
|
||||
}
|
||||
|
||||
} else {
|
||||
window.history.back()
|
||||
}
|
||||
})
|
||||
|
||||
Vue.prototype.$isDev = process.env.NODE_ENV !== 'production'
|
||||
|
||||
Vue.prototype.$dateDistanceFromNow = (unixms) => {
|
||||
@@ -52,17 +37,20 @@ Vue.prototype.$bytesPretty = (bytes, decimals = 2) => {
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
Vue.prototype.$elapsedPretty = (seconds) => {
|
||||
Vue.prototype.$elapsedPretty = (seconds, useFullNames = false) => {
|
||||
if (seconds < 60) {
|
||||
return `${Math.floor(seconds)} sec${useFullNames ? 'onds' : ''}`
|
||||
}
|
||||
var minutes = Math.floor(seconds / 60)
|
||||
if (minutes < 70) {
|
||||
return `${minutes} min`
|
||||
return `${minutes} min${useFullNames ? `ute${minutes === 1 ? '' : 's'}` : ''}`
|
||||
}
|
||||
var hours = Math.floor(minutes / 60)
|
||||
minutes -= hours * 60
|
||||
if (!minutes) {
|
||||
return `${hours} hr`
|
||||
return `${hours} ${useFullNames ? 'hours' : 'hr'}`
|
||||
}
|
||||
return `${hours} hr ${minutes} min`
|
||||
return `${hours} ${useFullNames ? `hour${hours === 1 ? '' : 's'}` : 'hr'} ${minutes} ${useFullNames ? `minute${minutes === 1 ? '' : 's'}` : 'min'}`
|
||||
}
|
||||
|
||||
Vue.prototype.$secondsToTimestamp = (seconds) => {
|
||||
@@ -132,6 +120,45 @@ Vue.prototype.$encode = encode
|
||||
const decode = (text) => Buffer.from(decodeURIComponent(text), 'base64').toString()
|
||||
Vue.prototype.$decode = decode
|
||||
|
||||
export default ({ store, app }) => {
|
||||
// iOS Only
|
||||
// backButton event does not work with iOS swipe navigation so use this workaround
|
||||
if (app.router && Capacitor.getPlatform() === 'ios') {
|
||||
app.router.beforeEach((to, from, next) => {
|
||||
if (store.state.globals.isModalOpen) {
|
||||
Vue.prototype.$eventBus.$emit('close-modal')
|
||||
}
|
||||
if (store.state.playerIsFullscreen) {
|
||||
Vue.prototype.$eventBus.$emit('minimize-player')
|
||||
}
|
||||
next()
|
||||
})
|
||||
}
|
||||
|
||||
// Android only
|
||||
App.addListener('backButton', async ({ canGoBack }) => {
|
||||
if (store.state.globals.isModalOpen) {
|
||||
Vue.prototype.$eventBus.$emit('close-modal')
|
||||
return
|
||||
}
|
||||
if (store.state.playerIsFullscreen) {
|
||||
Vue.prototype.$eventBus.$emit('minimize-player')
|
||||
return
|
||||
}
|
||||
if (!canGoBack) {
|
||||
const { value } = await Dialog.confirm({
|
||||
title: 'Confirm',
|
||||
message: `Did you want to exit the app?`,
|
||||
})
|
||||
if (value) {
|
||||
App.exitApp()
|
||||
}
|
||||
} else {
|
||||
window.history.back()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export {
|
||||
encode,
|
||||
decode
|
||||
|
||||
@@ -83,7 +83,16 @@ class LocalStorage {
|
||||
await Storage.set({ key: 'lastLibraryId', value: libraryId })
|
||||
console.log('[LocalStorage] Set Last Library Id', libraryId)
|
||||
} catch (error) {
|
||||
console.error('[LocalStorage] Failed to set current library', error)
|
||||
console.error('[LocalStorage] Failed to set last library id', error)
|
||||
}
|
||||
}
|
||||
|
||||
async removeLastLibraryId() {
|
||||
try {
|
||||
await Storage.remove({ key: 'lastLibraryId' })
|
||||
console.log('[LocalStorage] Remove Last Library Id')
|
||||
} catch (error) {
|
||||
console.error('[LocalStorage] Failed to remove last library id', error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ class ServerSocket extends EventEmitter {
|
||||
console.log('[SOCKET] User Item Progress Updated', JSON.stringify(data))
|
||||
var progress = data.data
|
||||
this.$store.commit('user/updateUserMediaProgress', progress)
|
||||
this.emit('user_media_progress_updated', progress)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Audiobookshelf Mobile App
|
||||
|
||||
AudioBookshelf is a self-hosted audiobook server for managing and playing your audiobooks.
|
||||
Audiobookshelf is a self-hosted audiobook and podcast server.
|
||||
|
||||
### Android (beta)
|
||||
Get the Android app on the [Google Play Store](https://play.google.com/store/apps/details?id=com.audiobookshelf.app)
|
||||
|
||||
@@ -1,9 +1,38 @@
|
||||
export const state = () => ({
|
||||
isModalOpen: false,
|
||||
itemDownloads: [],
|
||||
bookshelfListView: false,
|
||||
series: null,
|
||||
localMediaProgress: [],
|
||||
lastSearch: null
|
||||
lastSearch: null,
|
||||
jumpForwardItems: [
|
||||
{
|
||||
icon: 'forward_5',
|
||||
value: 5
|
||||
},
|
||||
{
|
||||
icon: 'forward_10',
|
||||
value: 10
|
||||
},
|
||||
{
|
||||
icon: 'forward_30',
|
||||
value: 30
|
||||
}
|
||||
],
|
||||
jumpBackwardsItems: [
|
||||
{
|
||||
icon: 'replay_5',
|
||||
value: 5
|
||||
},
|
||||
{
|
||||
icon: 'replay_10',
|
||||
value: 10
|
||||
},
|
||||
{
|
||||
icon: 'replay_30',
|
||||
value: 30
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
export const getters = {
|
||||
@@ -22,13 +51,16 @@ export const getters = {
|
||||
if (media.coverPath.startsWith('http:') || media.coverPath.startsWith('https:')) return media.coverPath
|
||||
|
||||
var userToken = rootGetters['user/getToken']
|
||||
var serverAddress = rootGetters['user/getServerAddress']
|
||||
if (!userToken || !serverAddress) return placeholder
|
||||
|
||||
var lastUpdate = libraryItem.updatedAt || Date.now()
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') { // Testing
|
||||
// return `http://localhost:3333/api/items/${libraryItem.id}/cover?token=${userToken}&ts=${lastUpdate}`
|
||||
}
|
||||
|
||||
var url = new URL(`/api/items/${libraryItem.id}/cover`, rootGetters['user/getServerAddress'])
|
||||
var url = new URL(`/api/items/${libraryItem.id}/cover`, serverAddress)
|
||||
return `${url}?token=${userToken}&ts=${lastUpdate}`
|
||||
},
|
||||
getLocalMediaProgressById: (state) => (localLibraryItemId, episodeId = null) => {
|
||||
@@ -36,6 +68,20 @@ export const getters = {
|
||||
if (episodeId != null && lmp.localEpisodeId != episodeId) return false
|
||||
return lmp.localLibraryItemId == localLibraryItemId
|
||||
})
|
||||
},
|
||||
getLocalMediaProgressByServerItemId: (state) => (libraryItemId, episodeId = null) => {
|
||||
return state.localMediaProgress.find(lmp => {
|
||||
if (episodeId != null && lmp.episodeId != episodeId) return false
|
||||
return lmp.libraryItemId == libraryItemId
|
||||
})
|
||||
},
|
||||
getJumpForwardIcon: state => (jumpForwardTime) => {
|
||||
const item = state.jumpForwardItems.find(i => i.value == jumpForwardTime)
|
||||
return item ? item.icon : 'forward_10'
|
||||
},
|
||||
getJumpBackwardsIcon: state => (jumpBackwardsTime) => {
|
||||
const item = state.jumpBackwardsItems.find(i => i.value == jumpBackwardsTime)
|
||||
return item ? item.icon : 'replay_10'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +94,9 @@ export const actions = {
|
||||
}
|
||||
|
||||
export const mutations = {
|
||||
setIsModalOpen(state, val) {
|
||||
state.isModalOpen = val
|
||||
},
|
||||
addUpdateItemDownload(state, downloadItem) {
|
||||
var index = state.itemDownloads.findIndex(i => i.id == downloadItem.id)
|
||||
if (index >= 0) {
|
||||
@@ -84,6 +133,9 @@ export const mutations = {
|
||||
removeLocalMediaProgress(state, id) {
|
||||
state.localMediaProgress = state.localMediaProgress.filter(lmp => lmp.id != id)
|
||||
},
|
||||
removeLocalMediaProgressForItem(state, llid) {
|
||||
state.localMediaProgress = state.localMediaProgress.filter(lmp => lmp.localLibraryItemId !== llid)
|
||||
},
|
||||
setLastSearch(state, val) {
|
||||
state.lastSearch = val
|
||||
}
|
||||
|
||||