]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/itunes_source.swift
Add iTunes source manager
[rbdr/lyricli] / Sources / itunes_source.swift
1 import ScriptingBridge
2
3 // Protocol to obtain the track from iTunes
4 @objc protocol iTunesTrack {
5 @objc optional var name: String {get}
6 @objc optional var artist: String {get}
7 }
8
9 // Protocol to interact with iTunes
10 @objc protocol iTunesApplication {
11 @objc optional var currentTrack: iTunesTrack? {get}
12 @objc optional var currentStreamTitle: String? {get}
13 }
14
15 extension SBApplication : iTunesApplication {}
16
17 // Source that reads track artist and name from current itunes track
18 class ItunesSource: Source {
19
20 // Calls the spotify API and returns the current track
21 var currentTrack: Track? {
22
23 if let iTunes: iTunesApplication = SBApplication(bundleIdentifier: "com.apple.iTunes") {
24
25 // Attempt to fetch the title from a stream
26 if let currentStreamTitle = iTunes.currentStreamTitle {
27 if let track = currentStreamTitle {
28
29 let trackComponents = track.characters.split(separator: "-").map(String.init)
30
31 if trackComponents.count == 2 {
32 let artist = trackComponents[0].trimmingCharacters(in: .whitespaces)
33 let name = trackComponents[1].trimmingCharacters(in: .whitespaces)
34
35 return Track(withName: name, andArtist: artist)
36 }
37
38 }
39 }
40
41 // Attempt to fetch the title from a song
42 if let currentTrack = iTunes.currentTrack {
43 if let track = currentTrack {
44 if let name = track.name {
45 if let artist = track.artist {
46
47 return Track(withName: name, andArtist: artist)
48 }
49 }
50 }
51 }
52 }
53
54 return nil
55 }
56
57 }