Repository navigation
Expand file tree
/
Copy pathTranscriptSearchService.swift
More file actions
400 lines (367 loc) · 16.1 KB
/
Copy pathTranscriptSearchService.swift
File metadata and controls
400 lines (367 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import Foundation
import SwiftData
enum TranscriptSearchScope: Hashable, Sendable {
case episode(String)
case podcast(String)
case library
}
struct TranscriptSearchQuery: Sendable {
let text: String
let scope: TranscriptSearchScope
let limit: Int
let offset: Int
init(text: String, scope: TranscriptSearchScope, limit: Int = 80, offset: Int = 0) {
self.text = text
self.scope = scope
self.limit = max(1, min(limit, 250))
self.offset = max(0, offset)
}
}
enum TranscriptSearchText {
static func matches(_ text: String, query: String) -> Bool {
let normalizedText = text
.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
.replacingOccurrences(of: "ß", with: "ss")
let normalizedQuery = query
.trimmingCharacters(in: .whitespacesAndNewlines)
.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: .current)
.replacingOccurrences(of: "ß", with: "ss")
guard normalizedQuery.isEmpty == false else { return false }
return normalizedText.range(of: normalizedQuery) != nil
}
}
struct TranscriptSearchPassage: Identifiable, Hashable, Sendable {
let id: String
let podcastID: String
let podcastTitle: String
let podcastImageURL: URL?
let episodeID: String
let episodeTitle: String
let episodeURL: URL?
let episodeImageURL: URL?
let publishDate: Date?
let text: String
let snippet: String
let speaker: String?
let startTime: TimeInterval
let endTime: TimeInterval?
let matchedTerms: [String]
}
struct TranscriptSearchEpisodeGroup: Identifiable, Hashable, Sendable {
let episodeID: String
let episodeTitle: String
let episodeURL: URL?
let episodeImageURL: URL?
let publishDate: Date?
let passages: [TranscriptSearchPassage]
var id: String { episodeID }
}
struct TranscriptSearchPodcastGroup: Identifiable, Hashable, Sendable {
let podcastID: String
let podcastTitle: String
let podcastImageURL: URL?
let episodes: [TranscriptSearchEpisodeGroup]
var id: String { podcastID }
var passageCount: Int { episodes.reduce(0) { $0 + $1.passages.count } }
}
struct TranscriptSearchSnapshot: Sendable {
let groups: [TranscriptSearchPodcastGroup]
let totalMatches: Int
}
enum TranscriptSearchError: LocalizedError {
case invalidQuery
var errorDescription: String? {
switch self {
case .invalidQuery:
return "Enter a word or phrase to search transcripts."
}
}
}
protocol TranscriptSearching: Sendable {
func search(_ request: TranscriptSearchQuery) async throws -> TranscriptSearchSnapshot
func hasSearchableTranscripts(in scope: TranscriptSearchScope) async throws -> Bool
}
/// Queries canonical SwiftData transcript lines directly. This actor returns
/// immutable snapshots and never creates a second persisted copy of transcript
/// text for search.
@ModelActor
actor TranscriptSearchActor: TranscriptSearching {
func search(_ request: TranscriptSearchQuery) async throws -> TranscriptSearchSnapshot {
let query = request.text.trimmingCharacters(in: .whitespacesAndNewlines)
guard query.isEmpty == false else { throw TranscriptSearchError.invalidQuery }
try Task.checkCancellation()
let predicate = try transcriptPredicate(query: query, scope: request.scope)
let totalMatches = try modelContext.fetchCount(
FetchDescriptor<TranscriptLineAndTime>(predicate: predicate)
)
try Task.checkCancellation()
var descriptor = FetchDescriptor<TranscriptLineAndTime>(
predicate: predicate,
sortBy: [SortDescriptor(\.startTime)]
)
descriptor.fetchLimit = request.limit
descriptor.fetchOffset = request.offset
let lines = try modelContext.fetch(descriptor)
var passages: [TranscriptSearchPassage] = []
passages.reserveCapacity(lines.count)
for line in lines {
try Task.checkCancellation()
guard let episode = line.episode, let podcast = episode.podcast else { continue }
passages.append(makePassage(line: line, episode: episode, podcast: podcast, query: query))
}
return TranscriptSearchSnapshot(
groups: Self.group(passages),
totalMatches: totalMatches
)
}
func hasSearchableTranscripts(in scope: TranscriptSearchScope) async throws -> Bool {
let predicate = try scopePredicate(scope)
var descriptor = FetchDescriptor<TranscriptLineAndTime>(predicate: predicate)
descriptor.fetchLimit = 1
let signpostID = PodcastDetailFetchSignposts.begin(
"Podcast detail transcript availability fetch"
)
var resultCount = -1
defer {
PodcastDetailFetchSignposts.end(
"Podcast detail transcript availability fetch",
id: signpostID,
count: resultCount
)
}
let hasLines = try modelContext.fetch(descriptor).isEmpty == false
resultCount = hasLines ? 1 : 0
return hasLines
}
private func transcriptPredicate(
query: String,
scope: TranscriptSearchScope
) throws -> Predicate<TranscriptLineAndTime> {
switch scope {
case .library:
return #Predicate<TranscriptLineAndTime> { line in
line.text.localizedStandardContains(query)
|| line.speaker?.localizedStandardContains(query) == true
}
case .podcast(let podcastID):
let (feed, title) = podcastScopeValues(for: podcastID)
if let feed {
return #Predicate<TranscriptLineAndTime> { line in
(line.text.localizedStandardContains(query)
|| line.speaker?.localizedStandardContains(query) == true)
&& line.episode?.podcast?.feed == feed
}
}
guard let title else {
return #Predicate<TranscriptLineAndTime> { _ in false }
}
return #Predicate<TranscriptLineAndTime> { line in
(line.text.localizedStandardContains(query)
|| line.speaker?.localizedStandardContains(query) == true)
&& line.episode?.podcast?.title == title
}
case .episode(let episodeID):
guard let episodePersistentID = try resolveEpisodePersistentID(for: episodeID) else {
return #Predicate<TranscriptLineAndTime> { _ in false }
}
return #Predicate<TranscriptLineAndTime> { line in
(line.text.localizedStandardContains(query)
|| line.speaker?.localizedStandardContains(query) == true)
&& line.episode?.persistentModelID == episodePersistentID
}
}
}
private func scopePredicate(_ scope: TranscriptSearchScope) throws -> Predicate<TranscriptLineAndTime> {
switch scope {
case .library:
return #Predicate<TranscriptLineAndTime> { _ in true }
case .podcast(let podcastID):
let (feed, title) = podcastScopeValues(for: podcastID)
if let feed {
return #Predicate<TranscriptLineAndTime> { line in
line.episode?.podcast?.feed == feed
}
}
guard let title else {
return #Predicate<TranscriptLineAndTime> { _ in false }
}
return #Predicate<TranscriptLineAndTime> { line in
line.episode?.podcast?.title == title
}
case .episode(let episodeID):
guard let episodePersistentID = try resolveEpisodePersistentID(for: episodeID) else {
return #Predicate<TranscriptLineAndTime> { _ in false }
}
return #Predicate<TranscriptLineAndTime> { line in
line.episode?.persistentModelID == episodePersistentID
}
}
}
private func resolveEpisodePersistentID(for identityKey: String) throws -> PersistentIdentifier? {
guard let components = StableIdentityKey.components(from: identityKey),
components.count >= 2,
let feed = URL(string: components[0]) else {
return nil
}
let episodeIdentity = components[1]
let descriptor: FetchDescriptor<Episode>
if episodeIdentity.hasPrefix("guid:") {
let guid = String(episodeIdentity.dropFirst("guid:".count))
descriptor = FetchDescriptor<Episode>(predicate: #Predicate { episode in
episode.podcast?.feed == feed && episode.guid == guid
})
} else if episodeIdentity.hasPrefix("enclosure:") {
let url = URL(string: String(episodeIdentity.dropFirst("enclosure:".count)))
descriptor = FetchDescriptor<Episode>(predicate: #Predicate { episode in
episode.podcast?.feed == feed && episode.url == url
})
} else if episodeIdentity.hasPrefix("episode:") {
let url = URL(string: String(episodeIdentity.dropFirst("episode:".count)))
descriptor = FetchDescriptor<Episode>(predicate: #Predicate { episode in
episode.podcast?.feed == feed && episode.url == url
})
} else if episodeIdentity.hasPrefix("link:") {
let url = URL(string: String(episodeIdentity.dropFirst("link:".count)))
descriptor = FetchDescriptor<Episode>(predicate: #Predicate { episode in
episode.podcast?.feed == feed && episode.link == url
})
} else {
var fallback = FetchDescriptor<Episode>(predicate: #Predicate { episode in
episode.podcast?.feed == feed
})
fallback.fetchLimit = 500
return try modelContext.fetch(fallback).first {
$0.stableEpisodeIdentity.key == identityKey
}?.persistentModelID
}
var bounded = descriptor
bounded.fetchLimit = 1
return try modelContext.fetch(bounded).first?.persistentModelID
}
private func podcastScopeValues(for identity: String) -> (URL?, String?) {
if let feed = URL(string: identity), feed.scheme != nil {
return (feed, nil)
}
if let components = StableIdentityKey.components(from: identity),
components.first == "title",
components.count > 1 {
return (nil, components[1])
}
return (URL(string: identity), nil)
}
private func makePassage(
line: TranscriptLineAndTime,
episode: Episode,
podcast: Podcast,
query: String
) -> TranscriptSearchPassage {
TranscriptSearchPassage(
id: line.id.uuidString,
podcastID: podcast.stablePodcastIdentityKey,
podcastTitle: podcast.title,
podcastImageURL: podcast.imageURL,
episodeID: episode.stableEpisodeIdentity.key,
episodeTitle: episode.title,
episodeURL: episode.url,
episodeImageURL: episode.imageURL,
publishDate: episode.publishDate,
text: line.text,
snippet: makeSnippet(from: line.text, query: query),
speaker: line.speaker,
startTime: line.startTime,
endTime: line.endTime,
matchedTerms: queryTerms(from: query)
)
}
private func makeSnippet(from text: String, query: String, maxLength: Int = 180) -> String {
let cleaned = text.replacingOccurrences(of: "\n", with: " ")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard cleaned.count > maxLength else { return markDirectMatch(in: cleaned, query: query) }
guard let range = cleaned.range(
of: query,
options: [.caseInsensitive, .diacriticInsensitive],
range: nil,
locale: .current
) else {
return String(cleaned.prefix(maxLength))
}
let offset = cleaned.distance(from: cleaned.startIndex, to: range.lowerBound)
let startOffset = max(0, offset - maxLength / 2)
let startIndex = cleaned.index(cleaned.startIndex, offsetBy: startOffset)
let length = min(maxLength, cleaned.distance(from: startIndex, to: cleaned.endIndex))
let endIndex = cleaned.index(startIndex, offsetBy: length)
let clipped = String(cleaned[startIndex..<endIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
return (startOffset == 0 ? "" : "…") + markDirectMatch(in: clipped, query: query)
}
private func markDirectMatch(in text: String, query: String) -> String {
guard let range = text.range(
of: query,
options: [.caseInsensitive, .diacriticInsensitive],
range: nil,
locale: .current
) else { return text }
return String(text[..<range.lowerBound])
+ "[" + String(text[range]) + "]" + String(text[range.upperBound...])
}
private func queryTerms(from query: String) -> [String] {
query.split(whereSeparator: { $0.isWhitespace || $0.isPunctuation })
.map { String($0) }
}
private static func group(_ results: [TranscriptSearchPassage]) -> [TranscriptSearchPodcastGroup] {
var episodesByPodcast: [String: [String: [TranscriptSearchPassage]]] = [:]
var podcastMetadata: [String: (String, URL?)] = [:]
var episodeMetadata: [String: (String, URL?, URL?, Date?)] = [:]
for result in results {
episodesByPodcast[result.podcastID, default: [:]][result.episodeID, default: []].append(result)
podcastMetadata[result.podcastID] = (result.podcastTitle, result.podcastImageURL)
episodeMetadata[result.episodeID] = (
result.episodeTitle,
result.episodeURL,
result.episodeImageURL,
result.publishDate
)
}
return episodesByPodcast.keys.sorted { lhs, rhs in
(podcastMetadata[lhs]?.0 ?? "").localizedCaseInsensitiveCompare(podcastMetadata[rhs]?.0 ?? "") == .orderedAscending
}.compactMap { podcastID in
guard let metadata = podcastMetadata[podcastID] else { return nil }
let episodes = episodesByPodcast[podcastID, default: [:]].keys.sorted { lhs, rhs in
let left = episodeMetadata[lhs]?.3 ?? .distantPast
let right = episodeMetadata[rhs]?.3 ?? .distantPast
if left != right { return left > right }
return (episodeMetadata[lhs]?.0 ?? "").localizedCaseInsensitiveCompare(episodeMetadata[rhs]?.0 ?? "") == .orderedAscending
}.compactMap { episodeID -> TranscriptSearchEpisodeGroup? in
guard let episode = episodeMetadata[episodeID] else { return nil }
return TranscriptSearchEpisodeGroup(
episodeID: episodeID,
episodeTitle: episode.0,
episodeURL: episode.1,
episodeImageURL: episode.2,
publishDate: episode.3,
passages: episodesByPodcast[podcastID]?[episodeID] ?? []
)
}
return TranscriptSearchPodcastGroup(
podcastID: podcastID,
podcastTitle: metadata.0,
podcastImageURL: metadata.1,
episodes: episodes
)
}
}
}
enum TranscriptSearchLegacyStoreCleanup {
/// Removes only the old derived search database and its SQLite sidecars.
/// Canonical SwiftData stores are deliberately outside this path.
static func removeObsoleteStore() {
let baseURL = ModelContainerManager.sharedContainerURL
?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first
?? FileManager.default.temporaryDirectory
let storeURL = baseURL
.appendingPathComponent("TranscriptSearch", isDirectory: true)
.appendingPathComponent("TranscriptSearch.sqlite")
for suffix in ["", "-wal", "-shm", "-journal"] {
try? FileManager.default.removeItem(at: URL(fileURLWithPath: storeURL.path + suffix))
}
}
}