-
Notifications
You must be signed in to change notification settings - Fork 4
/
SongObject+CoreDataClass.swift
43 lines (38 loc) · 1.82 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
//
// 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, syncType
}
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)
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 = []
}
}
}