Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,26 @@ package de.qspool.clementineremote.backend.sync
import android.net.Uri
import com.google.protobuf.InvalidProtocolBufferException
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SongMetadata
import java.io.File

/** A song kept on this phone, to show and play. */
data class KeptSong(
data class KeptSong @JvmOverloads constructor(
val itemKey: String,
val title: String,
val artist: String,
val album: String,
/** As Clementine writes it, such as "5:36"; empty if it didn't say. */
val length: String,
val uri: Uri,
/** The cover Clementine sent with the song, if it did; otherwise the one in its file shows. */
val art: Uri? = null,
) {
companion object {
/** [item] as its tags have it; a song without a title is named after its file. */
fun of(item: SyncedItem): KeptSong {
/**
* [item] as its tags have it, with its cover in [covers]; a song without a title is named
* after its file.
*/
fun of(item: SyncedItem, covers: File): KeptSong {
val song = try {
SongMetadata.parseFrom(item.metadata)
} catch (e: InvalidProtocolBufferException) {
Expand All @@ -30,6 +36,7 @@ data class KeptSong(
album = song.album,
length = song.prettyLength,
uri = uri,
art = item.artKey?.let { SyncFiles.artFile(covers, it) }?.let(Uri::fromFile),
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package de.qspool.clementineremote.backend.sync

import android.content.ComponentName
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import androidx.core.content.ContextCompat
Expand All @@ -21,6 +22,8 @@ import de.qspool.clementineremote.backend.RemoteRepository.NowPlaying
import de.qspool.clementineremote.backend.pb.ClementineMessage
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.MsgType
import de.qspool.clementineremote.backend.player.MySong
import java.io.File
import java.io.IOException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
Expand Down Expand Up @@ -56,6 +59,10 @@ object PhonePlayer {
/** The songs being played, by item key, for what the player shows of them. */
private var songs: Map<String, KeptSong> = emptyMap()

/** The last cover read, so it isn't read again on every update. */
private var coverUri: Uri? = null
private var coverData: ByteArray? = null

private val _playFrom = MutableStateFlow(PlayFrom.CLEMENTINE)

/**
Expand Down Expand Up @@ -185,13 +192,13 @@ object PhonePlayer {

private fun nowPlaying(player: Player, itemKey: String): NowPlaying {
// What the song was kept as, with what that doesn't say from the file's tags, which come
// in once the file is read; and the cover in the file, if it has one.
// in once the file is read; and the cover Clementine sent, or else the one in the file.
val metadata = player.mediaMetadata
val kept = songs[itemKey]
val title = metadata.title?.toString() ?: kept?.title.orEmpty()
val artist = metadata.artist?.toString() ?: kept?.artist.orEmpty()
val album = metadata.albumTitle?.toString() ?: kept?.album.orEmpty()
val art = metadata.artworkData
val art = kept?.art?.let(::cover) ?: metadata.artworkData
val known = song?.takeIf {
it.filename == itemKey && it.title == title && it.artist == artist && it.album == album &&
(art == null || it.artData != null)
Expand Down Expand Up @@ -229,6 +236,19 @@ object PhonePlayer {
)
}

/** The cover at [uri], a file of the app's; read once for each song played. */
private fun cover(uri: Uri): ByteArray? {
if (uri != coverUri) {
coverUri = uri
coverData = try {
uri.path?.let { File(it).readBytes() }
} catch (e: IOException) {
null
}
}
return coverData
}

private fun withController(context: Context, use: (MediaController) -> Unit) {
// The controller is used on the main thread, where it was made.
val main = ContextCompat.getMainExecutor(context)
Expand Down Expand Up @@ -266,6 +286,8 @@ object PhonePlayer {
.setTitle(song.title.ifEmpty { null })
.setArtist(song.artist.ifEmpty { null })
.setAlbumTitle(song.album.ifEmpty { null })
// For the notification and lock screen.
.setArtworkUri(song.art)
.setIsPlayable(true)
.setIsBrowsable(false)
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.Requ
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.ResponseSyncManifest
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SyncItem
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SyncManifestState
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.UUID

/** How the engine talks to the Clementine it syncs with, while connected to it. */
@WorkerThread
Expand All @@ -24,7 +26,7 @@ interface SyncConnection {
@Throws(IOException::class)
fun manifest(request: RequestSyncManifest): ResponseSyncManifest

/** Opens a path Clementine gave, such as a song's /d/ URL, on its HTTP server. */
/** Opens a path Clementine gave, such as a song's /d/ or cover's /a/ URL, on its HTTP server. */
@Throws(IOException::class)
fun open(path: String): InputStream
}
Expand Down Expand Up @@ -52,9 +54,9 @@ sealed interface RuleResult {

/**
* Brings what's on the phone in line with the rules for one Clementine: asks for each rule's
* manifest, downloads the songs that are new or changed into [storage] (Music/Clementine/Synced/),
* and deletes the songs that no rule wants any more. A song in several rules is downloaded once.
* Covers and conversions come later.
* manifest, downloads the songs that are new or changed into [storage] (Music/Clementine/Synced/)
* with their covers into [covers], and deletes the songs that no rule wants any more. A song in
* several rules is downloaded once, and a cover many songs share is too. Conversions come later.
*
* [supportedFormats] are what the phone plays, as for streaming, and [delete] removes a song
* [storage] saved, by its URI. [onProgress] hears how many of a rule's songs to download have
Expand All @@ -66,6 +68,7 @@ sealed interface RuleResult {
class SyncEngine(
private val store: SyncStore,
private val storage: DownloadStorage,
private val covers: File,
private val delete: (Uri) -> Unit,
private val supportedFormats: List<AudioFormat>,
private val now: () -> Long = System::currentTimeMillis,
Expand Down Expand Up @@ -119,6 +122,9 @@ class SyncEngine(
download(connection, rule.serverId, item, have)
downloaded++
onProgress(rule.id, downloaded, total)
} else if (have != null && have.artKey != item.artKey()) {
// The same song with another cover, or one kept before covers were.
store.putItem(have.copy(artKey = art(connection, item)))
}
keys += item.itemKey
}
Expand Down Expand Up @@ -187,15 +193,45 @@ class SyncEngine(
mimeType = item.mimeType,
sizeBytes = item.sizeBytes,
delivery = item.delivery,
artKey = null,
artKey = art(connection, item),
metadata = song.toByteArray(),
pinned = have?.pinned ?: false,
addedAt = have?.addedAt ?: now(),
)
)
}

/**
* The key of [item]'s cover, downloading it if the phone doesn't have it yet; null if it has
* none, or it couldn't be downloaded, so it's tried again next time. A song without a cover of
* its own from Clementine shows the one in its file, if any.
*/
private fun art(connection: SyncConnection, item: SyncItem): String? {
val key = item.artKey() ?: return null
val file = SyncFiles.artFile(covers, key) ?: return null
if (store.art(key) != null) return key

// Downloaded beside it first, so a download cut short leaves no half a cover.
val partial = File(covers, ".${UUID.randomUUID()}.part")
return try {
covers.mkdirs()
connection.open(item.art.url).use { input ->
partial.outputStream().use { input.copyTo(it) }
}
if (!partial.renameTo(file)) throw IOException("Couldn't save the cover $key")
store.putArt(SyncedArt(key, Uri.fromFile(file).toString(), file.length()))
key
} catch (e: IOException) {
Log.w(TAG, "Couldn't download the cover of ${item.itemKey}", e)
partial.delete()
null
}
}
}

/** The key of the cover Clementine sent with the song, or null if it sent none. */
private fun SyncItem.artKey(): String? = if (hasArt() && art.key.isNotEmpty()) art.key else null

/** Copies [input] to [output], timing the reads (the network) and the writes (MediaStore). */
private fun copy(input: InputStream, output: OutputStream, timing: DownloadTiming) {
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
Expand Down Expand Up @@ -275,5 +311,9 @@ fun removeUnwanted(store: SyncStore, serverId: String, delete: (Uri) -> Unit): I
store.removeItem(serverId, item.itemKey)
removed++
}
for (art in store.unusedArt()) {
Uri.parse(art.uri).path?.let { File(it).delete() }
store.removeArt(art.artKey)
}
return removed
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package de.qspool.clementineremote.backend.sync

import android.content.Context
import de.qspool.clementineremote.backend.downloader.DownloadStorage
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SongMetadata
import java.io.File

/** Where synced songs go, under the download location: Synced/<artist>/<album>/<track> <title>. */
object SyncFiles {
Expand All @@ -18,6 +20,20 @@ object SyncFiles {
return DIR + part(artist, "Unknown artist") + "/" + part(song.album, "Unknown album") + "/"
}

/** The app's own folder of synced covers, apart from the songs: they aren't music. */
fun coversDir(context: Context) = File(context.filesDir, "covers")

/**
* Where the cover with [key] goes in [covers]; null for a key that isn't a hash, so it can't
* name a file somewhere else.
*/
fun artFile(covers: File, key: String): File? {
if (key.isEmpty() || key.length > 128 || !key.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) {
return null
}
return File(covers, key.lowercase())
}

fun fileName(song: SongMetadata, mimeType: String): String {
val title = part(song.title, "Untitled")
val name = if (song.track > 0) "%02d %s".format(song.track, title) else title
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ object Syncer {
/** The songs of [ruleId] on this phone, in its order. Reads the disk. */
@JvmStatic
@WorkerThread
fun songs(ruleId: Long): List<KeptSong> = store(context).ruleItems(ruleId).map(KeptSong::of)
fun songs(ruleId: Long): List<KeptSong> {
val covers = SyncFiles.coversDir(context)
return store(context).ruleItems(ruleId).map { KeptSong.of(it, covers) }
}

/**
* Keeps [rules] on the phone, for the Clementine connected, and syncs them. A rule for a
Expand Down Expand Up @@ -218,7 +221,7 @@ object Syncer {
}
_status.value = _status.value.copy(running = true, unavailable = false, networkNotAllowed = false)
val engine = SyncEngine(
store(context), storage,
store(context), storage, SyncFiles.coversDir(context),
delete = { uri: Uri -> context.contentResolver.delete(uri, null, null) },
supportedFormats = ThisRenderer.capabilities(context).formatsList,
onProgress = { ruleId, done, total ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package de.qspool.clementineremote.backend.sync
import android.net.Uri
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SongMetadata
import de.qspool.clementineremote.backend.pb.ClementineRemoteProtocolBuffer.SyncDelivery
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
Expand All @@ -12,9 +14,15 @@ import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class KeptSongTest {

private fun item(song: SongMetadata, uri: String = "content://media/external/audio/media/7") = SyncedItem(
private val covers = File("/covers")

private fun item(
song: SongMetadata,
uri: String = "content://media/external/audio/media/7",
artKey: String? = null,
) = SyncedItem(
serverId = "studio", itemKey = "k", version = "1", uri = uri, mimeType = "audio/flac",
sizeBytes = 1, delivery = SyncDelivery.SYNC_DELIVERY_UNSPECIFIED, artKey = null, metadata = song.toByteArray(), addedAt = 0,
sizeBytes = 1, delivery = SyncDelivery.SYNC_DELIVERY_UNSPECIFIED, artKey = artKey, metadata = song.toByteArray(), addedAt = 0,
)

@Test
Expand All @@ -24,16 +32,25 @@ class KeptSongTest {
.build()
assertEquals(
KeptSong("k", "So What", "Miles Davis", "Kind of Blue", "9:22", Uri.parse("content://media/external/audio/media/7")),
KeptSong.of(item(song)),
KeptSong.of(item(song), covers),
)
}

@Test
fun withoutTagsUsesTheAlbumArtistAndTheFileName() {
val song = SongMetadata.newBuilder().setAlbumartist("Various Artists").build()
val kept = KeptSong.of(item(song, "file:///music/01%20Intro.flac"))
val kept = KeptSong.of(item(song, "file:///music/01%20Intro.flac"), covers)
assertEquals("01 Intro", kept.title)
assertEquals("Various Artists", kept.artist)
assertEquals("", kept.length)
}

@Test
fun hasTheCoverClementineSent() {
val song = SongMetadata.newBuilder().setTitle("So What").build()
assertEquals(Uri.fromFile(File("/covers/c0ffee")), KeptSong.of(item(song, artKey = "C0FFEE"), covers).art)
assertNull(KeptSong.of(item(song), covers).art)
// A key that isn't a hash can't name a file elsewhere.
assertNull(KeptSong.of(item(song, artKey = "../songs"), covers).art)
}
}
Loading
Loading