summaryrefslogtreecommitdiff
path: root/Sources/itunes_source.swift
blob: 449dd8a2e8dc83a1d98ad8a3385a610524712c83 (plain)
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
import ScriptingBridge

// Protocol to obtain the track from iTunes
@objc protocol iTunesTrack {
    @objc optional var name: String {get}
    @objc optional var artist: String {get}
}

// Protocol to interact with iTunes
@objc protocol iTunesApplication {
    @objc optional var currentTrack: iTunesTrack? {get}
    @objc optional var currentStreamTitle: String? {get}
}

extension SBApplication : iTunesApplication {}

// Source that reads track artist and name from current itunes track
class ItunesSource: Source {

    // Calls the spotify API and returns the current track
    var currentTrack: Track? {

        if let iTunes: iTunesApplication = SBApplication(bundleIdentifier: "com.apple.iTunes") {

            // Attempt to fetch the title from a stream
            if let currentStreamTitle = iTunes.currentStreamTitle {
                if let track = currentStreamTitle {

                    let trackComponents = track.characters.split(separator: "-").map(String.init)

                    if trackComponents.count == 2 {
                        let artist = trackComponents[0].trimmingCharacters(in: .whitespaces)
                        let name = trackComponents[1].trimmingCharacters(in: .whitespaces)

                        return Track(withName: name, andArtist: artist)
                    }

                }
            }

            // Attempt to fetch the title from a song
            if let currentTrack = iTunes.currentTrack {
                if let track = currentTrack {
                    if let name = track.name {
                        if let artist = track.artist {

                            return Track(withName: name, andArtist: artist)
                        }
                    }
                }
            }
        }

        return nil
    }

}