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 @@ -63,6 +63,8 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
let count: Int
let totalDuration: Double
let latestImport: Date
/// 表紙に使う動画(アルバムの最初の動画)。動画が1本もなければ nil。
var coverVideoID: UUID? = nil

/// 写真だけのアルバムを除いた一覧を作る。表示名(`Album.displayTitle`)がメインアクター上なので,こちらもそうする。
@MainActor
Expand All @@ -74,11 +76,13 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
var count = 0
var total = 0.0
var latest = Date.distantPast
var cover: UUID?
for id in album.videoIDs {
guard let item = byID[id], item.mediaType == .video, !item.isInTrash else { continue }
count += 1
total += item.duration
latest = max(latest, item.importDate)
if cover == nil { cover = item.id }
}
let components = album.name.components(separatedBy: "/")
return MusicVideoAlbumEntry(
Expand All @@ -88,7 +92,8 @@ nonisolated struct MusicVideoAlbumEntry: Identifiable, Equatable, Sendable {
parent: components.count > 1 ? components.dropLast().joined(separator: " / ") : "",
count: count,
totalDuration: total,
latestImport: latest
latestImport: latest,
coverVideoID: cover
)
}
}
Expand Down
121 changes: 121 additions & 0 deletions ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// ArkServer/Features/MusicVideo/Models/MusicVideoMusicBrowser.swift

import Foundation
import UniformTypeIdentifiers

// 曲を選ぶ画面の、フォルダの走査と、一覧の絞り込み・並べ替え。画面から切り離して、テストできるようにしてある。

/// 曲のファイル1つぶん。
nonisolated struct MusicVideoMusicFile: Identifiable, Hashable, Sendable {
let url: URL
let size: Int64
let modified: Date
/// 選んだフォルダからの相対の場所("/" 区切り)。選んだフォルダの直下なら空。
let folder: String

var id: URL { url }
var title: String { url.deletingPathExtension().lastPathComponent }
}

/// 曲一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.musicPicker.order`)と同じにしてある。
nonisolated enum MusicVideoMusicOrder: String, CaseIterable, Identifiable, Sendable {
case name = "名前"
case recent = "新しい順"
var id: String { rawValue }
}

/// 左に並べるフォルダ1つぶん。階層の途中のフォルダも含み、数は、その下(サブフォルダ)の曲も合わせた数。
nonisolated struct MusicVideoMusicFolder: Identifiable, Hashable, Sendable {
/// 選んだフォルダからの相対の場所("/" 区切り)。
let path: String
let count: Int

var id: String { path }
var components: [String] { path.split(separator: "/").map(String.init) }
/// 表示名(階層の最後)。
var name: String { components.last ?? path }
/// 階層の深さ(直下のフォルダが 0)。
var depth: Int { max(0, components.count - 1) }
}

nonisolated enum MusicVideoMusicBrowser {
/// これを超える曲は、先頭からここまでだけ集める(巨大なフォルダで固まらないように)。
static let fileLimit = 2000

/// フォルダの中(サブフォルダも含む)の音声ファイルを集める。隠しファイルとパッケージの中は除く。
static func scan(folder: URL, limit: Int = fileLimit) -> (files: [MusicVideoMusicFile], hitLimit: Bool) {
let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey]
guard let enumerator = FileManager.default.enumerator(
at: folder,
includingPropertiesForKeys: keys,
options: [.skipsHiddenFiles, .skipsPackageDescendants]
) else { return ([], false) }

let rootComponents = folder.standardizedFileURL.pathComponents
var found: [MusicVideoMusicFile] = []
for case let url as URL in enumerator {
guard let type = UTType(filenameExtension: url.pathExtension), type.conforms(to: .audio) else { continue }
let values = try? url.resourceValues(forKeys: Set(keys))
guard values?.isRegularFile == true else { continue }
found.append(MusicVideoMusicFile(
url: url,
size: Int64(values?.fileSize ?? 0),
modified: values?.contentModificationDate ?? .distantPast,
folder: relativeFolder(of: url, root: rootComponents)
))
if found.count >= limit { return (found, true) }
}
return (found, false)
}

/// `url` のあるフォルダの、選んだフォルダからの相対の場所。選んだフォルダの外にあるように見えるとき(別名の道筋など)は空にする。
static func relativeFolder(of url: URL, root: [String]) -> String {
let parent = url.deletingLastPathComponent().standardizedFileURL.pathComponents
guard parent.count >= root.count, Array(parent.prefix(root.count)) == root else { return "" }
return parent.dropFirst(root.count).joined(separator: "/")
}

/// その場所(`folder`)とその下のフォルダにある曲か。`folder` が nil なら、すべて。
static func isIn(_ file: MusicVideoMusicFile, folder: String?) -> Bool {
guard let folder, !folder.isEmpty else { return true }
return file.folder == folder || file.folder.hasPrefix(folder + "/")
}

/// 曲一覧。`folder` はその場所とその下に絞る。`query` は曲名に含まれる語(大文字小文字は区別しない)。
static func visible(
_ files: [MusicVideoMusicFile],
folder: String?,
order: MusicVideoMusicOrder,
query: String
) -> [MusicVideoMusicFile] {
var result = files.filter { isIn($0, folder: folder) }
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { result = result.filter { $0.title.localizedCaseInsensitiveContains(trimmed) } }
switch order {
case .name: result.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
case .recent: result.sort { $0.modified > $1.modified }
}
return result
}

/// 曲のあるフォルダの一覧(階層の途中も含む)。階層の順に並ぶ。選んだフォルダの直下の曲は、どのフォルダにも入らない。
static func folders(in files: [MusicVideoMusicFile]) -> [MusicVideoMusicFolder] {
var counts: [String: Int] = [:]
for file in files where !file.folder.isEmpty {
var path = ""
for part in file.folder.split(separator: "/") {
path = path.isEmpty ? String(part) : path + "/" + part
counts[path, default: 0] += 1
}
}
return counts
.map { MusicVideoMusicFolder(path: $0.key, count: $0.value) }
.sorted { lhs, rhs in
// 親の次にその子が来るよう、階層の部品ごとに自然順で比べる。
for (left, right) in zip(lhs.components, rhs.components) where left != right {
return left.localizedStandardCompare(right) == .orderedAscending
}
return lhs.components.count < rhs.components.count
}
}
}
102 changes: 102 additions & 0 deletions ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// ArkServer/Features/MusicVideo/Models/MusicVideoSourceBrowser.swift

import Foundation

// 素材を選ぶ画面の、一覧の絞り込みと並べ替え。画面から切り離して、テストできるようにしてある。

/// アルバム一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.picker.albumOrder`)と同じにしてある。
nonisolated enum MusicVideoAlbumOrder: String, CaseIterable, Identifiable, Sendable {
case name = "名前"
case count = "件数の多い順"
case recent = "最近追加した順"
var id: String { rawValue }
}

/// 動画一覧の並べ替え。値の文字列は、保存済みの設定(`musicVideo.picker.videoOrder`)と同じにしてある。
nonisolated enum MusicVideoVideoOrder: String, CaseIterable, Identifiable, Sendable {
case recent = "追加が新しい順"
case longest = "長い順"
case name = "名前"
var id: String { rawValue }
}

nonisolated enum MusicVideoSourceBrowser {
/// アルバム一覧。
/// - Parameters:
/// - hidesEmpty: 動画が1本もないアルバムを隠す。
/// - onlyIDs: 指定すると、そのアルバムだけに絞る(「選択中のみ」)。nil なら絞らない。
/// - query: 名前か階層に含まれる語。空なら絞らない。
static func albums(
_ rows: [MusicVideoAlbumEntry],
order: MusicVideoAlbumOrder,
hidesEmpty: Bool,
onlyIDs: Set<UUID>?,
query: String
) -> [MusicVideoAlbumEntry] {
var result = rows
if hidesEmpty { result = result.filter { $0.count > 0 } }
if let onlyIDs { result = result.filter { onlyIDs.contains($0.id) } }
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { result = result.filter { $0.matches(query: trimmed) } }
switch order {
case .name:
func key(_ entry: MusicVideoAlbumEntry) -> String { entry.parent + "/" + entry.title }
result.sort { key($0).localizedStandardCompare(key($1)) == .orderedAscending }
case .count:
result.sort { $0.count > $1.count }
case .recent:
result.sort { $0.latestImport > $1.latestImport }
}
return result
}

/// 動画一覧。
/// - Parameters:
/// - minimumLength: これより短い動画は出さない(秒)。
/// - onlyIDs: 指定すると、その動画だけに絞る(「選択中のみ」)。nil なら絞らない。
static func videos(
_ items: [VideoItem],
order: MusicVideoVideoOrder,
minimumLength: Double,
favoritesOnly: Bool,
onlyIDs: Set<UUID>?,
query: String
) -> [VideoItem] {
var result = items.filter { $0.duration >= minimumLength }
if favoritesOnly { result = result.filter(\.isFavorite) }
if let onlyIDs { result = result.filter { onlyIDs.contains($0.id) } }
let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { result = result.filter { $0.originalFilename.localizedCaseInsensitiveContains(trimmed) } }
switch order {
case .recent:
result.sort { $0.importDate > $1.importDate }
case .longest:
result.sort { $0.duration > $1.duration }
case .name:
result.sort { $0.originalFilename.localizedStandardCompare($1.originalFilename) == .orderedAscending }
}
return result
}

/// 素材にできる動画(動画で、ゴミ箱の外)。
static func usableVideos(_ videos: [VideoItem]) -> [VideoItem] {
videos.filter { $0.mediaType == .video && !$0.isInTrash }
}

/// アルバムに入っている動画(動画で、ゴミ箱の外)。アルバムの並びのまま。
static func videos(in album: Album, from videosByID: [UUID: VideoItem]) -> [VideoItem] {
album.videoIDs.compactMap { id in
guard let item = videosByID[id], item.mediaType == .video, !item.isInTrash else { return nil }
return item
}
}

/// 選んだアルバムに入っている動画の ID。「アルバムで選択済み」の印に使う。
static func videoIDs(inAlbums albums: [Album], selected: Set<UUID>, from videosByID: [UUID: VideoItem]) -> Set<UUID> {
var ids = Set<UUID>()
for album in albums where selected.contains(album.id) {
for item in videos(in: album, from: videosByID) { ids.insert(item.id) }
}
return ids
}
}
Loading