]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/lyricli/sources/itunes_source.swift
92b99695d81f590bbf22c9f117bc6e8f9ff976cf
[rbdr/lyricli] / Sources / lyricli / sources / itunes_source.swift
1 import ScriptingBridge
2 import Foundation
3
4 // Protocol to obtain the track from iTunes
5 @objc protocol iTunesTrack {
6 @objc optional var name: String {get}
7 @objc optional var artist: String {get}
8 }
9
10 // Protocol to interact with iTunes
11 @objc protocol iTunesApplication {
12 @objc optional var currentTrack: iTunesTrack? {get}
13 @objc optional var currentStreamTitle: String? {get}
14 }
15
16 extension SBApplication: iTunesApplication {}
17
18 // Source that reads track artist and name from current itunes track
19 class ItunesSource: Source {
20
21 // Calls the spotify API and returns the current track
22 var currentTrack: Track? {
23
24 if let iTunes: iTunesApplication = SBApplication(bundleIdentifier: bundleIdentifier) {
25 if let application = iTunes as? SBApplication {
26 if !application.isRunning {
27 return nil
28 }
29 }
30
31 // Attempt to fetch the title from a stream
32 if let currentStreamTitle = iTunes.currentStreamTitle {
33 if let track = currentStreamTitle {
34
35 let trackComponents = track.split(separator: "-").map(String.init)
36
37 if trackComponents.count == 2 {
38 let artist = trackComponents[0].trimmingCharacters(in: .whitespaces)
39 let name = trackComponents[1].trimmingCharacters(in: .whitespaces)
40
41 return Track(withName: name, andArtist: artist)
42 }
43
44 }
45 }
46
47 // Attempt to fetch the title from a song
48 if let currentTrack = iTunes.currentTrack {
49 if let track = currentTrack {
50 if let name = track.name {
51 if let artist = track.artist {
52
53 // track properties are empty strings if itunes is closed
54 if name == "" || artist == "" {
55 return nil
56 }
57 return Track(withName: name, andArtist: artist)
58 }
59 }
60 }
61 }
62 }
63
64 return nil
65 }
66
67 private var bundleIdentifier: String {
68 if ProcessInfo().isOperatingSystemAtLeast(
69 OperatingSystemVersion(majorVersion: 10, minorVersion: 15, patchVersion: 0)
70 ) {
71 return "com.apple.Music"
72 }
73
74 return "com.apple.iTunes"
75 }
76
77 }