This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathPlaylistItem.swift
430 lines (367 loc) · 16.6 KB
/
PlaylistItem.swift
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Copyright 2021 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
import CoreData
import Shared
import os.log
@objc(PlaylistItem)
final public class PlaylistItem: NSManagedObject, CRUD, Identifiable {
@NSManaged public var cachedData: Data?
@NSManaged public var dateAdded: Date
@NSManaged public var duration: TimeInterval
@NSManaged public var lastPlayedOffset: TimeInterval
@NSManaged public var mediaSrc: String
@NSManaged public var mimeType: String
@NSManaged public var name: String
@NSManaged public var order: Int32
@NSManaged public var pageSrc: String
@NSManaged public var pageTitle: String?
@NSManaged public var uuid: String?
@NSManaged public var playlistFolder: PlaylistFolder?
@available(*, unavailable)
public init() {
fatalError("No Such Initializer: init()")
}
@available(*, unavailable)
public init(context: NSManagedObjectContext) {
fatalError("No Such Initializer: init(context:)")
}
@objc
private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
public init(context: NSManagedObjectContext, name: String, pageTitle: String?, pageSrc: String, cachedData: Data, duration: TimeInterval, mimeType: String, mediaSrc: String) {
let entity = Self.entity(context)
super.init(entity: entity, insertInto: context)
self.name = name
self.pageTitle = pageTitle
self.pageSrc = pageSrc
self.dateAdded = Date()
self.cachedData = cachedData
self.duration = duration
self.lastPlayedOffset = 0.0
self.mimeType = mimeType
self.mediaSrc = mediaSrc
self.order = .min
self.uuid = UUID().uuidString
}
public var id: String {
objectID.uriRepresentation().absoluteString
}
public class func frc() -> NSFetchedResultsController<PlaylistItem> {
let context = DataController.viewContext
let fetchRequest = NSFetchRequest<PlaylistItem>()
fetchRequest.entity = PlaylistItem.entity(context)
fetchRequest.fetchBatchSize = 20
let orderSort = NSSortDescriptor(key: "order", ascending: true)
let createdSort = NSSortDescriptor(key: "dateAdded", ascending: false)
fetchRequest.sortDescriptors = [orderSort, createdSort]
return NSFetchedResultsController(
fetchRequest: fetchRequest, managedObjectContext: context,
sectionNameKeyPath: nil, cacheName: nil)
}
public class func frc(parentFolder: PlaylistFolder?) -> NSFetchedResultsController<PlaylistItem> {
let context = parentFolder?.managedObjectContext ?? DataController.viewContext
let fetchRequest = NSFetchRequest<PlaylistItem>()
fetchRequest.entity = PlaylistItem.entity(context)
fetchRequest.fetchBatchSize = 20
if let parentFolder = parentFolder {
fetchRequest.predicate = NSPredicate(format: "playlistFolder.uuid == %@", parentFolder.uuid!)
} else {
fetchRequest.predicate = NSPredicate(format: "playlistFolder == nil")
}
let orderSort = NSSortDescriptor(key: "order", ascending: true)
let createdSort = NSSortDescriptor(key: "dateAdded", ascending: false)
fetchRequest.sortDescriptors = [orderSort, createdSort]
return NSFetchedResultsController(
fetchRequest: fetchRequest, managedObjectContext: context,
sectionNameKeyPath: nil, cacheName: nil)
}
public class func allFoldersFRC() -> NSFetchedResultsController<PlaylistItem> {
let context = DataController.viewContext
let fetchRequest = NSFetchRequest<PlaylistItem>()
fetchRequest.entity = PlaylistItem.entity(context)
fetchRequest.fetchBatchSize = 20
let orderSort = NSSortDescriptor(key: "order", ascending: true)
let createdSort = NSSortDescriptor(key: "dateAdded", ascending: false)
fetchRequest.sortDescriptors = [orderSort, createdSort]
return NSFetchedResultsController(
fetchRequest: fetchRequest, managedObjectContext: context,
sectionNameKeyPath: nil, cacheName: nil)
}
public static func addItem(_ item: PlaylistInfo, folderUUID: String? = nil, cachedData: Data?, completion: (() -> Void)? = nil) {
DataController.perform(context: .new(inMemory: false), save: false) { context in
let playlistItem = PlaylistItem(context: context,
name: item.name,
pageTitle: item.pageTitle,
pageSrc: item.pageSrc,
cachedData: cachedData ?? Data(),
duration: item.duration,
mimeType: item.mimeType,
mediaSrc: item.src)
playlistItem.order = item.order
playlistItem.uuid = item.tagId
playlistItem.playlistFolder = PlaylistFolder.getFolder(uuid: folderUUID ?? PlaylistFolder.savedFolderUUID, context: context)
PlaylistItem.reorderItems(context: context)
PlaylistItem.saveContext(context)
DispatchQueue.main.async {
completion?()
}
}
}
public static func addInMemoryItems(_ items: [PlaylistInfo], folderUUID: String, completion: (() -> Void)? = nil) {
DataController.perform(context: .existing(DataController.viewContextInMemory), save: false) { context in
context.perform {
let folder = PlaylistFolder.getFolder(uuid: folderUUID, context: context)
items.forEach({ item in
let playlistItem = PlaylistItem(context: context,
name: item.name,
pageTitle: item.pageTitle,
pageSrc: item.pageSrc,
cachedData: Data(),
duration: item.duration,
mimeType: item.mimeType,
mediaSrc: item.src)
playlistItem.order = item.order
playlistItem.uuid = item.tagId
playlistItem.playlistFolder = folder
})
PlaylistItem.reorderItems(context: context)
PlaylistItem.saveContext(context)
DispatchQueue.main.async {
completion?()
}
}
}
}
public static func saveInMemoryItemsToDisk(items: [PlaylistItem], folderUUID: String, completion: (() -> Void)? = nil) {
DataController.perform(context: .existing(DataController.viewContext), save: false) { context in
let folder = PlaylistFolder.getFolder(uuid: folderUUID, context: context)
items.forEach({ item in
let playlistItem = PlaylistItem(context: context,
name: item.name,
pageTitle: item.pageTitle,
pageSrc: item.pageSrc,
cachedData: item.cachedData ?? Data(),
duration: item.duration,
mimeType: item.mimeType,
mediaSrc: item.mediaSrc)
playlistItem.order = item.order
playlistItem.uuid = item.uuid
playlistItem.playlistFolder = folder
})
PlaylistItem.reorderItems(context: context)
// Issue #6243 The policy change is added to prevent merge conflicts
// Occasionally saving context will give error
// Fatal error: Error saving DB: Error Domain=NSCocoaErrorDomain Code=133020 "Could not merge changes."
// Merge policy should change be changed to mergeByPropertyObjectTrumpMergePolicyType to prevent this
let policy = context.mergePolicy
context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
PlaylistItem.saveContext(context)
context.mergePolicy = policy
DispatchQueue.main.async {
completion?()
}
}
}
public static func getItems(parentFolder: PlaylistFolder?) -> [PlaylistItem] {
let predicate: NSPredicate
if let parentFolder = parentFolder {
predicate = NSPredicate(format: "playlistFolder.uuid == %@", parentFolder.uuid!)
} else {
predicate = NSPredicate(format: "playlistFolder == nil")
}
let orderSort = NSSortDescriptor(key: "order", ascending: true)
let createdSort = NSSortDescriptor(key: "dateAdded", ascending: false)
return PlaylistItem.all(
where: predicate,
sortDescriptors: [orderSort, createdSort],
fetchBatchSize: 20) ?? []
}
public static func getItems(pageSrc: String) -> [PlaylistItem] {
return PlaylistItem.all(where: NSPredicate(format: "pageSrc == %@", pageSrc)) ?? []
}
public static func getItem(uuid: String) -> PlaylistItem? {
return PlaylistItem.first(where: NSPredicate(format: "uuid == %@", uuid))
}
public class func all() -> [PlaylistItem] {
all() ?? []
}
public static func itemExists(pageSrc: String) -> Bool {
if let count = PlaylistItem.count(predicate: NSPredicate(format: "pageSrc == %@", pageSrc)), count > 0 {
return true
}
return false
}
public static func itemExists(uuid: String) -> Bool {
if let count = PlaylistItem.count(predicate: NSPredicate(format: "uuid == %@", uuid)), count > 0 {
return true
}
return false
}
public static func cachedItem(cacheURL: URL) -> PlaylistItem? {
return PlaylistItem.all()?.first(where: {
var isStale = false
if let cacheData = $0.cachedData,
let url = try? URL(resolvingBookmarkData: cacheData, bookmarkDataIsStale: &isStale) {
return url.path == cacheURL.path
}
return false
})
}
public static func updateLastPlayed(itemId: String, pageSrc: String, lastPlayedOffset: TimeInterval) {
if itemExists(pageSrc: pageSrc) || itemExists(uuid: itemId) {
DataController.perform(context: .new(inMemory: false), save: false) { context in
if let existingItem = PlaylistItem.first(where: NSPredicate(format: "pageSrc == %@ OR uuid == %@", pageSrc, itemId), context: context) {
existingItem.lastPlayedOffset = lastPlayedOffset
}
PlaylistItem.saveContext(context)
}
}
}
public static func updateItem(_ item: PlaylistInfo, completion: (() -> Void)? = nil) {
if itemExists(pageSrc: item.pageSrc) || itemExists(uuid: item.tagId) {
DataController.perform(context: .new(inMemory: false), save: false) { context in
if let existingItem = PlaylistItem.first(where: NSPredicate(format: "pageSrc == %@ OR uuid == %@", item.pageSrc, item.tagId), context: context) {
existingItem.name = item.name
existingItem.pageTitle = item.pageTitle
existingItem.pageSrc = item.pageSrc
existingItem.duration = item.duration
existingItem.lastPlayedOffset = item.lastPlayedOffset
existingItem.mimeType = item.mimeType
existingItem.mediaSrc = item.src
existingItem.uuid = item.tagId
}
PlaylistItem.saveContext(context)
DispatchQueue.main.async {
completion?()
}
}
} else {
addItem(item, cachedData: nil, completion: completion)
}
}
public static func updateItems(_ items: [PlaylistInfo], folderUUID: String? = nil, newETag: String? = nil, completion: (() -> Void)? = nil) {
DataController.perform(context: .new(inMemory: false), save: false) { context in
let uuids = items.compactMap({ $0.tagId })
let existingItems = PlaylistItem.all(where: NSPredicate(format: "uuid IN %@", uuids), context: context) ?? []
let existingUUIDs = existingItems.compactMap({ $0.uuid })
let newItems = items.filter({ !existingUUIDs.contains($0.tagId) })
let folder = PlaylistFolder.getFolder(uuid: folderUUID ?? PlaylistFolder.savedFolderUUID,
context: context)
if let eTag = newETag {
folder?.sharedFolderETag = eTag
}
existingItems.forEach { existingItem in
items.forEach { item in
if existingItem.uuid == item.tagId {
existingItem.name = item.name
existingItem.pageTitle = item.pageTitle
existingItem.pageSrc = item.pageSrc
existingItem.duration = item.duration
existingItem.mimeType = item.mimeType
existingItem.mediaSrc = item.src
existingItem.playlistFolder = folder
}
}
}
newItems.forEach { item in
let playlistItem = PlaylistItem(context: context,
name: item.name,
pageTitle: item.pageTitle,
pageSrc: item.pageSrc,
cachedData: Data(),
duration: item.duration,
mimeType: item.mimeType,
mediaSrc: item.src)
playlistItem.order = item.order
playlistItem.uuid = item.tagId
playlistItem.playlistFolder = folder
}
PlaylistItem.reorderItems(context: context)
PlaylistItem.saveContext(context)
DispatchQueue.main.async {
completion?()
}
}
}
public static func updateCache(uuid: String, pageSrc: String, cachedData: Data?) {
DataController.perform(context: .new(inMemory: false), save: true) { context in
if let item = PlaylistItem.first(where: NSPredicate(format: "uuid == %@ OR pageSrc == %@", uuid, pageSrc), context: context) {
if let cachedData = cachedData, !cachedData.isEmpty {
item.cachedData = cachedData
} else {
item.cachedData = nil
}
}
}
}
public static func removeItem(uuid: String) {
PlaylistItem.deleteAll(predicate: NSPredicate(format: "uuid == %@", uuid), context: .new(inMemory: false), includesPropertyValues: false)
}
public static func removeItems(_ items: [PlaylistInfo], completion: (() -> Void)? = nil) {
var uuids = [String]()
var mediaSrcs = [String]()
items.forEach({
if $0.tagId.isEmpty {
mediaSrcs.append($0.src)
} else {
uuids.append($0.tagId)
}
})
PlaylistItem.deleteAll(predicate: NSPredicate(format: "uuid IN %@", uuids), context: .new(inMemory: false), includesPropertyValues: false, completion: completion)
if !mediaSrcs.isEmpty {
// As a backup, we delete by media source (not page source)
// This is more unique than pageSrc.
// This is because you can add multiple items per page but they'd each have a different media source.
PlaylistItem.deleteAll(predicate: NSPredicate(format: "mediaSrc IN %@", mediaSrcs), context: .new(inMemory: false), includesPropertyValues: false, completion: completion)
}
}
public static func moveItems(items: [NSManagedObjectID], to folderUUID: String?) {
DataController.perform { context in
var folder: PlaylistFolder?
if let folderUUID = folderUUID {
folder = PlaylistFolder.getFolder(uuid: folderUUID, context: context)
}
let playlistItems = items.compactMap { try? context.existingObject(with: $0) as? PlaylistItem }
playlistItems.forEach {
$0.playlistFolder = folder
folder?.playlistItems?.insert($0)
}
}
}
// MARK: - Internal
private static func reorderItems(context: NSManagedObjectContext) {
DataController.perform(context: .existing(context), save: true) { context in
let request = NSFetchRequest<PlaylistItem>()
request.entity = PlaylistItem.entity(context)
request.fetchBatchSize = 20
let orderSort = NSSortDescriptor(key: "order", ascending: true)
let items = PlaylistItem.all(sortDescriptors: [orderSort], context: context) ?? []
for (order, item) in items.enumerated() {
item.order = Int32(order)
}
}
}
@nonobjc
private class func fetchRequest() -> NSFetchRequest<PlaylistItem> {
NSFetchRequest<PlaylistItem>(entityName: "PlaylistItem")
}
private static func entity(_ context: NSManagedObjectContext) -> NSEntityDescription {
NSEntityDescription.entity(forEntityName: "PlaylistItem", in: context)!
}
private static func saveContext(_ context: NSManagedObjectContext) {
if context.concurrencyType == .mainQueueConcurrencyType {
Logger.module.warning("Writing to view context, this should be avoided.")
}
if context.hasChanges {
do {
try context.save()
} catch {
assertionFailure("Error saving DB: \(error.localizedDescription)")
}
}
}
}