]> git.r.bdr.sh - rbdr/lyricli/blame - Sources/lyricli/sources/itunes_source.swift
Merge branch 'release/1.0.0'
[rbdr/lyricli] / Sources / lyricli / sources / itunes_source.swift
CommitLineData
893a0a9b 1import ScriptingBridge
9cf995f0 2import Foundation
893a0a9b
BB
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
fdafe0d4 16extension SBApplication: iTunesApplication {}
893a0a9b
BB
17
18// Source that reads track artist and name from current itunes track
19class ItunesSource: Source {
20
21 // Calls the spotify API and returns the current track
22 var currentTrack: Track? {
23
9cf995f0
BB
24 if let iTunes: iTunesApplication = SBApplication(bundleIdentifier: bundleIdentifier) {
25 if let application = iTunes as? SBApplication {
26 if !application.isRunning {
27 return nil
28 }
29 }
893a0a9b
BB
30
31 // Attempt to fetch the title from a stream
32 if let currentStreamTitle = iTunes.currentStreamTitle {
33 if let track = currentStreamTitle {
34
fdafe0d4 35 let trackComponents = track.split(separator: "-").map(String.init)
893a0a9b
BB
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
d1a147d4 53 // track properties are empty strings if itunes is closed
fdafe0d4 54 if name == "" || artist == "" {
d1a147d4
ER
55 return nil
56 }
893a0a9b
BB
57 return Track(withName: name, andArtist: artist)
58 }
59 }
60 }
61 }
62 }
63
64 return nil
65 }
66
9cf995f0
BB
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
893a0a9b 77}