-
Notifications
You must be signed in to change notification settings - Fork 6
/
SongObject+CoreDataClass.swift
63 lines (56 loc) · 2.66 KB
/
SongObject+CoreDataClass.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
//
// SongObject+CoreDataClass.swift
// SpotifyLyricsInMenubar
//
// Created by Avi Wadhwa on 06/08/23.
//
//
import Foundation
import CoreData
@objc(SongObject)
public class SongObject: NSManagedObject, Decodable {
enum CodingKeys: String, CodingKey {
case lines, language, syncType
}
convenience init(from LRCLyrics: LRCLyrics, with context: NSManagedObjectContext, trackID: String, trackName: String, duration: TimeInterval) {
self.init(context: context)
self.id = trackID
self.title = trackName
self.downloadDate = Date.now
self.language = ""
// self.duration = duration
if !LRCLyrics.lyrics.isEmpty {
var newLyrics = LRCLyrics.lyrics
newLyrics.append(LyricLine(startTime: duration-1400, words: "Now Playing: \(title)"))
self.lyricsTimestamps = newLyrics.map {$0.startTimeMS}
self.lyricsWords = newLyrics.map {$0.words}
} else {
self.lyricsTimestamps = []
self.lyricsWords = []
}
}
public required convenience init(from decoder: Decoder) throws {
guard let context = decoder.userInfo[CodingUserInfoKey.managedObjectContext] as? NSManagedObjectContext, let trackID = decoder.userInfo[CodingUserInfoKey.trackID] as? String, let trackName = decoder.userInfo[CodingUserInfoKey.trackName] as? String, let duration = decoder.userInfo[CodingUserInfoKey.duration] as? TimeInterval else {
fatalError()
}
self.init(context: context)
self.id = trackID
self.title = trackName
self.downloadDate = Date.now
let container = try decoder.container(keyedBy: CodingKeys.self)
self.language = (try? container.decode(String.self, forKey: .language)) ?? ""
if let syncType = try? container.decode(String.self, forKey: .syncType), syncType == "LINE_SYNCED", var lyrics = try? container.decode([LyricLine].self, forKey: .lines) {
// Dummy lyric at the end to keep the timer going past the last lyric, necessary for someone playing a single song on repeat
// Spotify doesn't give playback notifications when it's the same song on repeat
// Apple Music does, but unfortunately has every song slightly longer than it's spotify counterpart so this doesn't help us
if !lyrics.isEmpty {
lyrics.append(LyricLine(startTime: duration-1400, words: "Now Playing: \(title)"))
}
self.lyricsTimestamps = lyrics.map {$0.startTimeMS}
self.lyricsWords = lyrics.map {$0.words}
} else {
self.lyricsWords = []
self.lyricsTimestamps = []
}
}
}