-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathspotify.rb
More file actions
130 lines (105 loc) · 2.71 KB
/
spotify.rb
File metadata and controls
130 lines (105 loc) · 2.71 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class Spotify
APP_PATH = "/Applications/Spotify.app".freeze # TODO: Make this configurable
VALID_TOGGLES = %w(shuffle repeat).freeze
VALID_SHARES = %w(url uri).freeze
NAME_REGEX = /\A[a-z0-9\.\-_\s]*\z/i
URI_REGEX = %r{
\A
uri\s
spotify:(track|album|artist|user):
([a-z0-9]+(:playlist:))*
(spotify:playlist:)?
[a-z0-9]{22}
\z
}ix
class << self
def play(play_args = "")
return invalid_command unless valid_play?(play_args)
send_command("play #{play_args}")
end
def pause
send_command("pause")
end
def stop
send_command("stop")
end
def next
send_command("next")
end
alias_method :skip, :next
def prev
send_command("prev")
end
def replay
send_command("replay")
end
def restart
quit
sleep(5) # Give Spotify a few seconds to shut down
`open #{APP_PATH}`
output = $?.success? ? "Spotify has been restarted" : "I had some trouble restarting Spotify"
[output, $?.success?]
end
def pos(time)
return invalid_command unless time == time.to_i
send_command("pos #{time.to_i}")
end
def quit
send_command("quit")
end
def status
send_command("status")
end
def share(share_item)
return invalid_command unless valid_share?(share_item)
send_command("share #{share_item}")
end
def toggle(toggle_item)
return invalid_command unless valid_toggle?(toggle_item)
send_command("toggle #{toggle_item}")
end
def vol(change = "")
return invalid_command unless valid_volume_change?(change)
send_command("vol #{change}")
end
private
def send_command(command)
output = `./spotify.sh #{command.rstrip}`
output = HELP_TEXT unless $?.success?
[output, $?.success?]
end
def invalid_command
[HELP_TEXT, false]
end
def valid_volume_change?(vol_arg)
if vol_arg == vol_arg.to_i.to_s
vol_arg.to_i.between?(0, 100)
else
["", "up", "down", "fadeout"].include?(vol_arg)
end
end
def valid_toggle?(toggle_item)
VALID_TOGGLES.include?(toggle_item)
end
def valid_share?(share_item)
VALID_SHARES.include?(share_item) || share_item.empty?
end
def valid_play?(play_args)
return true if play_args.empty?
return validate_uri(play_args) if uri_provided?(play_args)
validate_name(play_args)
end
def validate_uri(uri)
URI_REGEX.match(uri)
end
def validate_name(name)
NAME_REGEX.match(name)
end
def play_command(play_args)
play_args.split(" ").first
end
def uri_provided?(play_args)
play_command(play_args) == "uri"
end
end
end