Skip to content
Open
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 @@ -132,9 +132,11 @@ public actor LibraryStore {
""", [match])
return SearchSections(query: text, songs: rows.map { row in
let values = row.map { $0 ?? "" }
// Keep Clementine's percent-encoded filename verbatim; decoding %23 or %3F breaks
// server-side QUrl parsing when tracks with #, ?, or % are queued or downloaded.
return SearchCandidate(
item: BrowseItem(
level: 2, selection: Array(values[0...2]), kind: .song, url: SongQuery.decode(values[4]),
level: 2, selection: Array(values[0...2]), kind: .song, url: values[4],
artist: values[3], album: values[1]),
artist: values[3])
})
Expand Down Expand Up @@ -188,14 +190,24 @@ public actor LibraryStore {
if let database {
return database
}
Self.excludeFromBackup(fileURL)
let database = try Database(path: fileURL.path, readOnly: true)
self.database = database
return database
}

/// Excludes the large, re-downloadable library database from iCloud backup.
private static func excludeFromBackup(_ url: URL) {
var target = url
var values = URLResourceValues()
values.isExcludedFromBackup = true
try? target.setResourceValues(values)
}

/// Downloads the library from Clementine, replacing the one on the phone.
public func download(
from endpoint: Endpoint, authCode: Int32, progress: @escaping @Sendable (Progress) -> Void
from endpoint: Endpoint, authCode: Int32, receiveTimeout: Duration = .seconds(30),
progress: @escaping @Sendable (Progress) -> Void
) async throws(DownloadFailure) {
let partial = fileURL.deletingLastPathComponent().appending(path: "library.db.part")
try? FileManager.default.createDirectory(at: partial.deletingLastPathComponent(), withIntermediateDirectories: true)
Expand All @@ -209,7 +221,7 @@ public actor LibraryStore {
try await channel.send(RemoteMessage(.getLibrary))
} catch {
channel.cancel()
throw .connection
throw Task.isCancelled ? .cancelled : .connection
}
defer { channel.cancel() }

Expand All @@ -219,7 +231,7 @@ public actor LibraryStore {
while true {
let message: RemoteMessage
do {
message = try await channel.receive()
message = try await channel.receive(timeout: receiveTimeout)
} catch {
throw Task.isCancelled ? .cancelled : .connection
}
Expand Down Expand Up @@ -253,10 +265,25 @@ public actor LibraryStore {
try? await channel.send(RemoteMessage(.disconnect))

progress(.optimizing)
do {
if Task.isCancelled {
throw .cancelled
}
// Run synchronous SQLite integrity check and FTS indexing off the actor so callers
// aren't blocked and cancellation stops the build before swapping the live file.
let optimizeTask = Task.detached(priority: .userInitiated) {
try Self.optimize(partial)
}
do {
try await withTaskCancellationHandler {
try await optimizeTask.value
} onCancel: {
optimizeTask.cancel()
}
} catch {
throw .corrupt
throw Task.isCancelled ? .cancelled : .corrupt
}
if Task.isCancelled {
throw .cancelled
}
database = nil
columns = nil
Expand All @@ -270,6 +297,7 @@ public actor LibraryStore {
throw .cantSave
}
}
Self.excludeFromBackup(fileURL)
}

/// Drops unavailable songs, and adds the full-text index and the indices browsing uses.
Expand All @@ -291,8 +319,15 @@ public actor LibraryStore {
}

public static func freeSpace(at url: URL) -> Int64? {
let values = try? url.deletingLastPathComponent()
.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
// URL.resourceValues fails on paths that don't exist yet (e.g. before the first
// download creates its folder), so walk up to the nearest existing ancestor.
var probe = url
while !FileManager.default.fileExists(atPath: probe.path) {
let parent = probe.deletingLastPathComponent()
if parent.path == probe.path { break }
probe = parent
}
let values = try? probe.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
return values?.volumeAvailableCapacityForImportantUsage
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,21 @@ import Foundation
/// sections by what matched (see [SearchSections]); an artist or album opens to the level below,
/// by where the results came from, then album artist, album and song.
public actor SearchStore {
private struct SongKey: Hashable {
let provider: String
let url: String
}

private let database: Database
/// The search whose results are kept.
public private(set) var searchID: Int32?
/// What was searched for.
private var query = ""
/// The results, as they came.
private var results: [BrowseItem] = []
/// Each result's full description, by URL, for adding it to a playlist.
private var songs: [String: SongMetadata] = [:]
/// Each result's full description, keyed by `(provider, url)`, so duplicate URLs across
/// providers never overwrite each other.
private var songs: [SongKey: SongMetadata] = [:]
/// Each provider's icon (image data), by name.
public private(set) var icons: [String: Data] = [:]

Expand Down Expand Up @@ -79,36 +85,50 @@ public actor SearchStore {
if !result.searchProviderIcon.isEmpty {
icons[result.searchProvider] = result.searchProviderIcon
}
// Buffer inserted items and commit atomically so a failed SQLite insert rolls back
// both the database and in-memory maps instead of leaving partial results behind.
try database.execute("BEGIN")
defer { try? database.execute("COMMIT") }
for song in result.songMetadata {
let groupArtist = song.albumartist.isEmpty ? song.artist : song.albumartist
try database.run("""
INSERT INTO results (global_search_id, search_query, search_provider, title, album, artist,
albumartist, group_artist, track, disc, pretty_year, year, genre, pretty_length, filename,
is_local, filesize, rating)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", [
.integer(Int64(result.id)), .text(result.query), .text(result.searchProvider),
.text(song.title), .text(song.album), .text(song.artist), .text(song.albumartist),
.text(groupArtist), .integer(Int64(song.track)), .integer(Int64(song.disc)),
.text(song.prettyYear), .integer(Int64(song.prettyYear) ?? -1), .text(song.genre),
.text(song.prettyLength),
// The URL goes where the library keeps it.
.text(song.url), .integer(song.isLocal ? 1 : 0), .integer(Int64(song.fileSize)),
.real(Double(song.rating)),
])
results.append(BrowseItem(
level: Self.fields.count - 1, selection: [result.searchProvider, groupArtist, song.album, song.title],
kind: .song, url: song.url, artist: song.artist, album: song.album))
songs[song.url] = song
var inserted: [(item: BrowseItem, key: SongKey, song: SongMetadata)] = []
do {
for song in result.songMetadata {
let groupArtist = song.albumartist.isEmpty ? song.artist : song.albumartist
try database.run("""
INSERT INTO results (global_search_id, search_query, search_provider, title, album, artist,
albumartist, group_artist, track, disc, pretty_year, year, genre, pretty_length, filename,
is_local, filesize, rating)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", [
.integer(Int64(result.id)), .text(result.query), .text(result.searchProvider),
.text(song.title), .text(song.album), .text(song.artist), .text(song.albumartist),
.text(groupArtist), .integer(Int64(song.track)), .integer(Int64(song.disc)),
.text(song.prettyYear), .integer(Int64(song.prettyYear) ?? -1), .text(song.genre),
.text(song.prettyLength),
// The URL goes where the library keeps it.
.text(song.url), .integer(song.isLocal ? 1 : 0), .integer(Int64(song.fileSize)),
.real(Double(song.rating)),
])
let item = BrowseItem(
level: Self.fields.count - 1, selection: [result.searchProvider, groupArtist, song.album, song.title],
kind: .song, url: song.url, artist: song.artist, album: song.album)
inserted.append((item, SongKey(provider: result.searchProvider, url: song.url), song))
}
try database.execute("COMMIT")
} catch {
try? database.execute("ROLLBACK")
throw error
}
for entry in inserted {
results.append(entry.item)
songs[entry.key] = entry.song
}
}

/// The results so far, in sections.
public func sections() -> SearchSections {
SearchSections(query: query, songs: results.compactMap { item in
songs[item.url].map { SearchCandidate(item: item, artist: $0.artist, isLocal: $0.isLocal) }
songs[SongKey(provider: item.selection.first ?? "", url: item.url)].map {
SearchCandidate(item: item, artist: $0.artist, isLocal: $0.isLocal)
}
})
}

Expand All @@ -120,14 +140,15 @@ public actor SearchStore {
/// The songs [items] are or group, described in full.
public func songs(of items: [BrowseItem], sorting: LibrarySorting) throws -> [SongMetadata] {
guard let browser = browser(sorting) else { return [] }
return try browser.songs(items, in: database).compactMap { songs[$0.url] }
return try browser.songs(items, in: database).compactMap {
songs[SongKey(provider: $0.selection.first ?? "", url: $0.url)]
}
}

private func browser(_ sorting: LibrarySorting) -> SongBrowser? {
guard let searchID else { return nil }
var query = SongQuery(fields: Self.fields, sorting: sorting, table: "results")
query.hiddenWhere = "global_search_id = \(searchID)"
query.decodesURLs = false
return SongBrowser(query: query)
}
}
32 changes: 21 additions & 11 deletions Packages/ClementineKit/Sources/ClementineKit/Browse/SongQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,6 @@ struct SongQuery {
let table: String
/// A condition every row must meet, if any.
var hiddenWhere = ""
/// Whether the table's URLs are encoded, as the library's are.
var decodesURLs = true
/// The SQL a field stands for, when it isn't the column of that name.
var expressions: [String: String] = [:]

Expand All @@ -71,6 +69,7 @@ struct SongQuery {
var songLevel: Int { fields.count - 1 }

func kind(ofLevel level: Int) -> ItemKind {
guard level >= 0, level < fields.count else { return .song }
if level == songLevel {
return .song
}
Expand All @@ -85,19 +84,29 @@ struct SongQuery {

/// The items of [level] within [selection].
func items(in database: Database, level: Int, selection: [String]) throws -> [BrowseItem] {
// Switching library groupings while drilled into a child level can temporarily pass an
// out-of-bounds level or selection; return empty instead of trapping on fields[level].
guard level >= 0, level < fields.count, selection.count <= fields.count else { return [] }
let isSongLevel = level == songLevel
var sql = "SELECT 0 AS _id"
for field in fields {
sql += ", \(self.sql(field))"
}
sql += ", CAST(filename AS TEXT), artist, album FROM \(table)"
sql += ", CAST(filename AS TEXT), artist, album"
// Fold child counts into the main query to avoid an N+1 query per artist/album row.
if !isSongLevel {
sql += ", COUNT(DISTINCT(\(self.sql(fields[level + 1]))))"
}
sql += " FROM \(table)"
sql += whereClause(selection)
// Names in order for the phone's language, whatever their case or accents (Database), then
// by their bytes, so names differing only in case are always in the same order.
// Various artists first, as Clementine lists them.
let field = self.sql(fields[level])
if isSongLevel {
sql += " ORDER BY album COLLATE LOCALIZED, album, disc, track \(sorting.rawValue)"
// Apply sorting.rawValue to every term; otherwise SQLite keeps album/disc ASC.
sql += " ORDER BY album COLLATE LOCALIZED \(sorting.rawValue), album \(sorting.rawValue), "
+ "disc \(sorting.rawValue), track \(sorting.rawValue)"
} else {
sql += " GROUP BY \(field) ORDER BY (\(field)) IS char(1) DESC, "
+ "\(field) COLLATE LOCALIZED \(sorting.rawValue), \(field) \(sorting.rawValue)"
Expand All @@ -110,18 +119,21 @@ struct SongQuery {
level: level,
selection: itemSelection,
kind: kind(ofLevel: level),
url: decodesURLs ? Self.decode(row[fields.count + 1] ?? "") : row[fields.count + 1] ?? "",
// Keep Clementine's QUrl::toEncoded() string verbatim so %23/#, %3F/?, and %
// round-trip safely when sent back to the server.
url: row[fields.count + 1] ?? "",
artist: row[fields.count + 2] ?? "",
album: row[fields.count + 3] ?? "")
if !isSongLevel {
item.itemCount = try count(in: database, selection: itemSelection)
item.itemCount = row[fields.count + 4].flatMap { Int($0) } ?? 0
}
return item
}
}

/// How many distinct items are below [selection].
func count(in database: Database, selection: [String]) throws -> Int {
guard selection.count < fields.count else { return 0 }
let sql = "SELECT COUNT(DISTINCT(\(self.sql(fields[selection.count])))) FROM \(table)" + whereClause(selection)
let value = try database.query(sql, selection).first?.first ?? nil
return value.flatMap { Int($0) } ?? 0
Expand All @@ -134,11 +146,6 @@ struct SongQuery {
}
return conditions.isEmpty ? "" : " WHERE " + conditions.joined(separator: " AND ")
}

/// Clementine stores URLs encoded; the app sends them back decoded, keeping any "+".
static func decode(_ url: String) -> String {
url.replacingOccurrences(of: "+", with: "%2B").removingPercentEncoding ?? url
}
}

/// Opens levels of a [SongQuery] and finds the songs below items.
Expand All @@ -148,6 +155,9 @@ struct SongBrowser {
/// The level below [opened], or the top level for nil.
func level(below opened: BrowseItem?, in database: Database) throws -> BrowseLevel {
let level = opened.map { $0.level + 1 } ?? 0
guard level >= 0, level < query.fields.count else {
return BrowseLevel(opened: opened, kind: .song, items: [])
}
let items = try query.items(in: database, level: level, selection: opened?.selection ?? [])
return BrowseLevel(opened: opened, kind: query.kind(ofLevel: level), items: items)
}
Expand Down
Loading