]> git.r.bdr.sh - rbdr/lyricli/blame - Sources/itunes_source.swift
Merge branch 'release/0.3.0'
[rbdr/lyricli] / Sources / itunes_source.swift
CommitLineData
893a0a9b
BB
1import 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
15extension SBApplication : iTunesApplication {}
16
17// Source that reads track artist and name from current itunes track
18class 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
d1a147d4
ER
47 // track properties are empty strings if itunes is closed
48 if (!(name != "" && artist != "")) {
49 return nil
50 }
893a0a9b
BB
51 return Track(withName: name, andArtist: artist)
52 }
53 }
54 }
55 }
56 }
57
58 return nil
59 }
60
61}