Add: Sleep Timers #24

This commit is contained in:
advplyr 2021-10-30 13:31:21 -05:00
parent bff99f292b
commit 3b462b27b5
8 changed files with 219 additions and 17 deletions

View file

@ -13,8 +13,8 @@ android {
applicationId "com.audiobookshelf.app" applicationId "com.audiobookshelf.app"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 29 versionCode 30
versionName "0.9.13-beta" versionName "0.9.14-beta"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions { aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.

View file

@ -122,4 +122,9 @@ class MainActivity : BridgeActivity() {
// Mandatory for Activity, but not for Fragment & ComponentActivity // Mandatory for Activity, but not for Fragment & ComponentActivity
storageHelper.onRequestPermissionsResult(requestCode, permissions, grantResults) storageHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)
} }
override fun onUserInteraction() {
super.onUserInteraction()
Log.d(tag, "USER INTERACTION")
}
} }

View file

@ -8,6 +8,8 @@ import androidx.core.content.ContextCompat
import com.getcapacitor.* import com.getcapacitor.*
import com.getcapacitor.annotation.CapacitorPlugin import com.getcapacitor.annotation.CapacitorPlugin
import org.json.JSONObject import org.json.JSONObject
import java.util.*
import kotlin.concurrent.schedule
@CapacitorPlugin(name = "MyNativeAudio") @CapacitorPlugin(name = "MyNativeAudio")
class MyNativeAudio : Plugin() { class MyNativeAudio : Plugin() {
@ -35,6 +37,9 @@ class MyNativeAudio : Plugin() {
jsobj.put("playWhenReady", playWhenReady) jsobj.put("playWhenReady", playWhenReady)
notifyListeners("onPrepareMedia", jsobj) notifyListeners("onPrepareMedia", jsobj)
} }
override fun onSleepTimerEnded() {
emit("onSleepTimerEnded", true)
}
}) })
} }
mainActivity.pluginCallback = foregroundServiceReady mainActivity.pluginCallback = foregroundServiceReady
@ -201,4 +206,26 @@ class MyNativeAudio : Plugin() {
Log.d(tag, "Setting Audiobooks ${audiobookObjs.size}") Log.d(tag, "Setting Audiobooks ${audiobookObjs.size}")
playerNotificationService.setAudiobooks(audiobookObjs) playerNotificationService.setAudiobooks(audiobookObjs)
} }
@PluginMethod
fun setSleepTimer(call: PluginCall) {
var sleepTimeout:Long = call.getString("timeout", "360000")!!.toLong()
playerNotificationService.setSleepTimer(sleepTimeout)
call.resolve()
}
@PluginMethod
fun getSleepTimerTime(call: PluginCall) {
var time = playerNotificationService.getSleepTimerTime()
val ret = JSObject()
ret.put("value", time)
call.resolve(ret)
}
@PluginMethod
fun cancelSleepTimer(call: PluginCall) {
playerNotificationService.cancelSleepTimer()
call.resolve()
}
} }

View file

@ -51,6 +51,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
fun onPlayingUpdate(isPlaying: Boolean) fun onPlayingUpdate(isPlaying: Boolean)
fun onMetadata(metadata: JSObject) fun onMetadata(metadata: JSObject)
fun onPrepare(audiobookId:String, playWhenReady:Boolean) fun onPrepare(audiobookId:String, playWhenReady:Boolean)
fun onSleepTimerEnded()
} }
private val tag = "PlayerService" private val tag = "PlayerService"
@ -84,6 +85,8 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
private var lastPauseTime: Long = 0 //ms private var lastPauseTime: Long = 0 //ms
private var onSeekBack: Boolean = false private var onSeekBack: Boolean = false
private var sleepTimerTask:TimerTask? = null
fun setCustomObjectListener(mylistener: MyCustomObjectListener) { fun setCustomObjectListener(mylistener: MyCustomObjectListener) {
listener = mylistener listener = mylistener
} }
@ -124,7 +127,7 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
} }
@RequiresApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{ private fun createNotificationChannel(channelId: String, channelName: String): String {
val chan = NotificationChannel(channelId, val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_HIGH) channelName, NotificationManager.IMPORTANCE_HIGH)
chan.lightColor = Color.DKGRAY chan.lightColor = Color.DKGRAY
@ -718,5 +721,33 @@ class PlayerNotificationService : MediaBrowserServiceCompat() {
} }
} }
} }
fun setSleepTimer(timeout:Long) {
Log.d(tag, "Setting Sleep Timer for $timeout")
sleepTimerTask?.cancel()
sleepTimerTask = Timer("SleepTimer",false).schedule(timeout) {
Log.d(tag, "Sleep Timer Done")
Handler(Looper.getMainLooper()).post() {
if (mPlayer.isPlaying) {
Log.d(tag, "Sleep Timer Pausing Player")
mPlayer.pause()
}
if (listener != null) listener.onSleepTimerEnded()
}
}
}
fun getSleepTimerTime():Long? {
var time = sleepTimerTask?.scheduledExecutionTime()
Log.d(tag, "Sleep Timer execution time $time")
return time
}
fun cancelSleepTimer() {
Log.d(tag, "Canceling Sleep Timer")
sleepTimerTask?.cancel()
sleepTimerTask = null
}
} }

View file

@ -27,6 +27,16 @@
</template> </template>
<div class="flex-grow" /> <div class="flex-grow" />
</div> </div>
<div class="absolute top-2 right-3 text-white text-opacity-75" @click="showSleepTimerModal">
<svg v-if="!sleepTimerRunning" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
</svg>
<div v-else class="h-5 w-5 flex items-center justify-around">
<p class="text-sm font-mono text-warning">{{ Math.ceil(sleepTimeoutCurrentTime / 1000 / 60) }}m</p>
</div>
</div>
<!-- Track --> <!-- Track -->
<div ref="track" class="w-full h-2 bg-gray-700 relative cursor-pointer transform duration-100 hover:scale-y-125" :class="loading ? 'animate-pulse' : ''" @click.stop="clickTrack"> <div ref="track" class="w-full h-2 bg-gray-700 relative cursor-pointer transform duration-100 hover:scale-y-125" :class="loading ? 'animate-pulse' : ''" @click.stop="clickTrack">
<div ref="readyTrack" class="h-full bg-gray-600 absolute top-0 left-0 pointer-events-none" /> <div ref="readyTrack" class="h-full bg-gray-600 absolute top-0 left-0 pointer-events-none" />
@ -53,7 +63,9 @@ import MyNativeAudio from '@/plugins/my-native-audio'
export default { export default {
props: { props: {
loading: Boolean loading: Boolean,
sleepTimerRunning: Boolean,
sleepTimeoutCurrentTime: Number
}, },
data() { data() {
return { return {
@ -87,6 +99,9 @@ export default {
} }
}, },
methods: { methods: {
showSleepTimerModal() {
this.$emit('showSleepTimer')
},
updatePlaybackRate() { updatePlaybackRate() {
this.currentPlaybackRate = this.playbackRate this.currentPlaybackRate = this.playbackRate
MyNativeAudio.setPlaybackSpeed({ speed: this.playbackRate }) MyNativeAudio.setPlaybackSpeed({ speed: this.playbackRate })
@ -333,8 +348,8 @@ export default {
this.setFromObj() this.setFromObj()
} }
if ((this.stateName === 'ready_no_sync') || (this.stateName === 'buffering_no_sync')) this.noSyncUpdateTime = true if (this.stateName === 'ready_no_sync' || this.stateName === 'buffering_no_sync') this.noSyncUpdateTime = true
this.timeupdate() this.timeupdate()
}, },
init() { init() {

View file

@ -15,15 +15,17 @@
<div class="absolute left-2 -top-10 bookCoverWrapper"> <div class="absolute left-2 -top-10 bookCoverWrapper">
<cards-book-cover :audiobook="audiobook" :download-cover="downloadedCover" :width="64" /> <cards-book-cover :audiobook="audiobook" :download-cover="downloadedCover" :width="64" />
</div> </div>
<audio-player-mini ref="audioPlayerMini" :loading="isLoading" @updateTime="updateTime" @selectPlaybackSpeed="showPlaybackSpeedModal = true" @hook:mounted="audioPlayerMounted" /> <audio-player-mini ref="audioPlayerMini" :loading="isLoading" :sleep-timer-running="isSleepTimerRunning" :sleep-timeout-current-time="sleepTimeoutCurrentTime" @updateTime="updateTime" @selectPlaybackSpeed="showPlaybackSpeedModal = true" @showSleepTimer="showSleepTimer" @hook:mounted="audioPlayerMounted" />
</div> </div>
<modals-playback-speed-modal v-model="showPlaybackSpeedModal" :playback-speed.sync="playbackSpeed" @change="changePlaybackSpeed" /> <modals-playback-speed-modal v-model="showPlaybackSpeedModal" :playback-speed.sync="playbackSpeed" @change="changePlaybackSpeed" />
<modals-chapters-modal v-model="showChapterModal" :current-chapter="currentChapter" :chapters="chapters" @select="selectChapter" /> <modals-chapters-modal v-model="showChapterModal" :current-chapter="currentChapter" :chapters="chapters" @select="selectChapter" />
<modals-sleep-timer-modal v-model="showSleepTimerModal" :current-time="sleepTimeoutCurrentTime" :sleep-timer-running="isSleepTimerRunning" @change="selectSleepTimeout" @cancel="cancelSleepTimer" />
</div> </div>
</template> </template>
<script> <script>
import { Dialog } from '@capacitor/dialog' import { Dialog } from '@capacitor/dialog'
import MyNativeAudio from '@/plugins/my-native-audio'
export default { export default {
data() { data() {
@ -33,9 +35,14 @@ export default {
download: null, download: null,
lastProgressTimeUpdate: 0, lastProgressTimeUpdate: 0,
showPlaybackSpeedModal: false, showPlaybackSpeedModal: false,
showSleepTimerModal: false,
playbackSpeed: 1, playbackSpeed: 1,
showChapterModal: false, showChapterModal: false,
currentTime: 0 currentTime: 0,
sleepTimeoutCurrentTime: 0,
isSleepTimerRunning: false,
onSleepTimerEndedListener: null,
sleepInterval: null
} }
}, },
watch: { watch: {
@ -114,17 +121,62 @@ export default {
if (this.cover.startsWith('http')) return this.cover if (this.cover.startsWith('http')) return this.cover
var coverSrc = this.$store.getters['audiobooks/getBookCoverSrc'](this.audiobook) var coverSrc = this.$store.getters['audiobooks/getBookCoverSrc'](this.audiobook)
return coverSrc return coverSrc
// var _clean = this.cover.replace(/\\/g, '/')
// if (_clean.startsWith('/local')) {
// var _cover = process.env.NODE_ENV !== 'production' && process.env.PROD !== '1' ? _clean.replace('/local', '') : _clean
// return `${this.$store.state.serverUrl}${_cover}?token=${this.userToken}&ts=${Date.now()}`
// } else if (_clean.startsWith('/metadata')) {
// return `${this.$store.state.serverUrl}${_clean}?token=${this.userToken}&ts=${Date.now()}`
// }
// return _clean
} }
}, },
methods: { methods: {
onSleepTimerEnded() {
this.isSleepTimerRunning = false
if (this.sleepInterval) clearInterval(this.sleepInterval)
},
showSleepTimer() {
this.getSleepTimerTime()
this.showSleepTimerModal = true
},
async getSleepTimerTime() {
var res = await MyNativeAudio.getSleepTimerTime()
if (res && res.value) {
var time = Number(res.value)
return time - Date.now()
}
return 0
},
async selectSleepTimeout(timeout) {
console.log('Setting sleep timer', timeout)
await MyNativeAudio.setSleepTimer({ timeout: String(timeout) })
this.setSleepTimeoutTimer(timeout)
},
async cancelSleepTimer() {
console.log('Canceling sleep timer')
await MyNativeAudio.cancelSleepTimer()
this.isSleepTimerRunning = false
if (this.sleepInterval) clearInterval(this.sleepInterval)
},
async syncSleepTimer() {
var time = await this.getSleepTimerTime()
this.setSleepTimeoutTimer(time)
},
setSleepTimeoutTimer(startTime) {
if (this.sleepInterval) clearInterval(this.sleepInterval)
this.sleepTimeoutCurrentTime = startTime
this.isSleepTimerRunning = true
var elapsed = 0
this.sleepInterval = setInterval(() => {
this.sleepTimeoutCurrentTime = Math.max(0, this.sleepTimeoutCurrentTime - 1000)
if (this.sleepTimeoutCurrentTime <= 0) {
clearInterval(this.sleepInterval)
return
}
// Sync with the actual time from android Timer
elapsed++
if (elapsed > 5) {
clearInterval(this.sleepInterval)
this.syncSleepTimer()
}
}, 1000)
},
clickChapterBtn() { clickChapterBtn() {
if (!this.chapters.length) return if (!this.chapters.length) return
this.showChapterModal = true this.showChapterModal = true
@ -362,6 +414,8 @@ export default {
} }
}, },
mounted() { mounted() {
this.onSleepTimerEndedListener = MyNativeAudio.addListener('onSleepTimerEnded', this.onSleepTimerEnded)
this.playbackSpeed = this.$store.getters['user/getUserSetting']('playbackRate') this.playbackSpeed = this.$store.getters['user/getUserSetting']('playbackRate')
this.setListeners() this.setListeners()
@ -369,6 +423,8 @@ export default {
this.$store.commit('setStreamListener', this.streamUpdated) this.$store.commit('setStreamListener', this.streamUpdated)
}, },
beforeDestroy() { beforeDestroy() {
if (this.onSleepTimerEndedListener) this.onSleepTimerEndedListener.remove()
if (this.$server.socket) { if (this.$server.socket) {
this.$server.socket.off('stream_open', this.streamOpen) this.$server.socket.off('stream_open', this.streamOpen)
this.$server.socket.off('stream_closed', this.streamClosed) this.$server.socket.off('stream_closed', this.streamClosed)

View file

@ -0,0 +1,68 @@
<template>
<modals-modal v-model="show" :width="200" height="100%">
<template #outer>
<div class="absolute top-4 left-4 z-40">
<p class="text-white text-2xl truncate">Sleep Timer</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" style="max-height: 75%" @click.stop>
<ul v-if="!sleepTimerRunning" class="h-full w-full" role="listbox" aria-labelledby="listbox-label">
<template v-for="timeout in timeouts">
<li :key="timeout" class="text-gray-50 select-none relative py-4 pr-9 cursor-pointer hover:bg-black-400" role="option" @click="clickedOption(timeout)">
<div class="flex items-center justify-center">
<span class="font-normal ml-3 block truncate text-lg">{{ timeout }} min</span>
</div>
</li>
</template>
</ul>
<div v-else class="px-2 py-4">
<p class="mb-4 text-2xl font-mono text-center">{{ timeRemainingPretty }}</p>
<ui-btn @click="cancelSleepTimer" class="w-full">Cancel Timer</ui-btn>
</div>
</div>
</div>
</modals-modal>
</template>
<script>
export default {
props: {
value: Boolean,
currentTime: Number,
sleepTimerRunning: Boolean
},
data() {
return {}
},
computed: {
show: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
},
timeouts() {
return [1, 15, 30, 45, 60, 75, 90, 120]
},
timeRemainingPretty() {
return this.$secondsToTimestamp(this.currentTime / 1000)
}
},
methods: {
clickedOption(timeoutMin) {
var timeout = timeoutMin * 1000 * 60
this.show = false
this.$nextTick(() => this.$emit('change', timeout))
},
cancelSleepTimer() {
this.$emit('cancel')
this.show = false
}
},
mounted() {}
}
</script>

View file

@ -1,6 +1,6 @@
{ {
"name": "audiobookshelf-app", "name": "audiobookshelf-app",
"version": "v0.9.13-beta", "version": "v0.9.14-beta",
"author": "advplyr", "author": "advplyr",
"scripts": { "scripts": {
"dev": "nuxt --hostname localhost --port 1337", "dev": "nuxt --hostname localhost --port 1337",