forked from colla69/plexmusic-skill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
executable file
·416 lines (370 loc) · 15 KB
/
__init__.py
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# MIT LICENSE
# Mycroft Skill: Application Launcher, opens/closes Linux desktop applications
# Copyright © 2019 Philip Mayer [email protected]
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<<<<<<< Updated upstream
=======
>>>>>>> Stashed changes
import os
import random
import re
import sys
import time
from collections import defaultdict
from json import load, dump
from adapt.intent import IntentBuilder
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from mycroft.audio.services.vlc import VlcService
from mycroft.skills.common_play_skill import CommonPlaySkill, CPSMatchLevel
from mycroft.skills.core import intent_handler
from mycroft.util.log import LOG
from .plex_backend import PlexBackend
__author__ = 'colla69'
class PlexMusicSkill(CommonPlaySkill):
def CPS_match_query_phrase(self, phrase):
if self.refreshing_lib:
self.speak_dialog("refresh.library")
return None
else:
phrase = re.sub(self.translate_regex('on_plex'), '', phrase)
title = ""
artist = ""
album = ""
playlist = ""
t_prob = 0
a_prob = 0
al_prob = 0
p_prob = 0
if "random" in phrase and "music" in phrase:
data = {
"title": "random",
"file": self.titles
}
return phrase, CPSMatchLevel.TITLE, data
elif phrase.startswith("artist"):
artist, a_prob = self.artist_search(phrase[7:])
elif phrase.startswith("album"):
album, al_prob = self.album_search(phrase[6:])
elif phrase.startswith("playlist"):
playlist, p_prob = self.playlist_search(phrase[9:])
else:
title, t_prob = self.title_search(phrase)
artist, a_prob = self.artist_search(phrase)
album, al_prob = self.album_search(phrase)
playlist, p_prob = self.playlist_search(phrase)
by_title, by_prob = self.by_search(phrase)
print(""" Plex Music skill
Title %s %f
Artist %s %d
Album %s %d
Playlist %s %d
by Search %s %d
""" % (title, t_prob, artist, a_prob, album, al_prob, playlist, p_prob, by_title, by_prob))
if t_prob > al_prob and t_prob > a_prob:
data = {
"title": title,
"file": self.titles[title]
}
return phrase, CPSMatchLevel.TITLE, data
elif a_prob >= al_prob and a_prob != 0:
data = {
"title": artist,
"file": self.artists[artist]
}
return phrase, CPSMatchLevel.MULTI_KEY, data
elif al_prob >= a_prob and al_prob != 0:
data = {
"title": album,
"file": self.albums[album]
}
return phrase, CPSMatchLevel.MULTI_KEY, data
elif p_prob > al_prob:
data = {
"title": playlist,
"file": self.playlists[playlist]
}
return phrase, CPSMatchLevel.MULTI_KEY, data
elif by_prob > p_prob:
data = {
"title": by_title,
"file": self.tracksByArtist[by_title]
}
return phrase, CPSMatchLevel.MULTI_KEY, data
else:
return None
def CPS_start(self, phrase, data):
if data is None:
return None
if self.get_running():
self.vlc_player.stop()
self.vlc_player.clear_list()
title = data["title"]
link = data["file"]
if title == "random":
link = list(link.values())
random.shuffle(link)
try:
self.vlc_player.add_list(link)
self.vlc_player.play()
"""
if len(link) >= 1:
self.vlc_player = self.vlcI.media_list_player_new()
m = self.vlcI.media_list_new(link)
self.vlc_player.set_media_list(m)
self.vlc_player.play()
elif len(link) > 0:
self.vlc_player = self.vlcI.media_player_new()
m = self.vlcI.media_new(link[0])
self.vlc_player.set_media(m)
self.vlc_player.play() """
except Exception as e:
LOG.info(type(e))
LOG.info("Unexpected error:", sys.exc_info()[0])
raise
finally:
time.sleep(2)
if not self.get_running():
self.speak_dialog("playback.problem")
self.speak_dialog("excuses")
def __init__(self):
super().__init__(name="TemplateSkill")
self.uri = ""
self.token = ""
self.lib_name = ""
self.ducking = "True"
self.regexes = {}
self.refreshing_lib = False
self.p_uri = self.uri
self.p_token = "?X-Plex-Token=" + self.token
self.data_path = os.path.expanduser("~/.config/plexSkill/")
if not os.path.exists(self.data_path):
os.mkdir(self.data_path)
self.data_path += "data.json"
self.plex = None
self.artists = defaultdict(list)
self.albums = defaultdict(list)
self.titles = defaultdict(list)
self.playlists = defaultdict(list)
self.tracksByArtist = defaultdict(list)
self.tracks = {}
self.vlc_player = None
def initialize(self):
self.uri = self.settings.get("musicsource", "")
self.token = self.settings.get("plextoken", "")
self.lib_name = self.settings.get("plexlib", "")
self.ducking = self.settings.get("ducking", "True")
self.p_uri = self.uri
if self.load_plex_backend():
if not os.path.exists(self.data_path):
self.speak_dialog("library.unknown")
self.load_data()
self.vlc_player = VlcService(config={'duck': self.ducking})
self.vlc_player.normal_volume = 85
self.vlc_player.low_volume = 20
if self.ducking:
self.add_event('recognizer_loop:record_begin', self.handle_listener_started)
self.add_event('recognizer_loop:record_end', self.handle_listener_stopped)
self.add_event('recognizer_loop:audio_output_start', self.handle_audio_start)
self.add_event('recognizer_loop:audio_output_end', self.handle_audio_stop)
def get_running(self):
return self.vlc_player.player.is_playing()
def load_data(self):
LOG.info("loading " + self.data_path)
try:
if not os.path.isfile(self.data_path):
LOG.info("making new JsonData")
if self.load_plex_backend():
self.plex.down_plex_lib()
self.speak_dialog("done")
data = self.json_load(self.data_path)
for artist in data:
if artist == "playlist":
for playlist in data[artist]:
for song in data[artist][playlist]:
p_artist = song[0]
album = song[1]
title = song[2]
file = song[3]
self.playlists[playlist].append(file)
self.tracks[file] = (p_artist, album, title)
for album in data[artist]:
for song in data[artist][album]:
title = song[0]
file = song[1] # link
self.albums[album].append(file)
self.artists[artist].append(file)
self.titles[title].append(file)
self.tracks[file] = (artist, album, title)
# todo make separator translatable
bySearchValue = title + " by " + artist
self.tracksByArtist[bySearchValue].append(file)
finally:
self.refreshing_lib = False
def load_plex_backend(self):
if self.plex is None:
LOG.info("""\n\n\t connecting to:
{} {}
{}
""".format(self.p_uri, self.lib_name, self.token))
if self.token and self.p_uri and self.lib_name:
self.plex = PlexBackend(self.p_uri, self.token, self.lib_name, self.data_path)
return True
else:
self.speak_dialog("config.missing")
return False
else:
return True
def title_search(self, phrase):
return self.search(phrase, self.titles)
def artist_search(self, phrase):
return self.search(phrase, self.artists)
def album_search(self, phrase):
return self.search(phrase, self.albums)
def playlist_search(self, phrase):
<<<<<<< Updated upstream
if self.playlists :
probabilities = process.extractOne(phrase, self.playlists.keys(), scorer=fuzz.ratio)
playlist = probabilities[0]
confidence = probabilities[1]
return playlist, confidence
else:
return "", 0
=======
return self.search(phrase, self.playlists)
def by_search(self, phrase):
return self.search(phrase, self.tracksByArtist)
def search(self, phrase, searching_list):
if searching_list:
probabilities = process.extractOne(phrase, searching_list.keys(), scorer=fuzz.ratio)
result = probabilities[0]
confidence = probabilities[1]
return result, confidence
else:
return "", 0
def get_active_track_info(self):
meta = self.vlc_player.track_info()
artist, album, title = meta["artists"], meta["album"], meta["name"]
if title.startswith("file"):
media = self.vlc_player.player.get_media()
link = media.get_mrl()
artist, album, title = self.tracks[link]
if isinstance(artist, list):
artist = artist[0]
return album, artist, title
>>>>>>> Stashed changes
######################################################################
# utils
def json_save(self, data, fname):
with open(fname, 'w') as fp:
dump(data, fp)
def json_load(self, fname):
with open(fname, 'r') as fp:
return load(fp)
def get_tokenized_uri(self, uri):
return self.p_uri + uri + self.token
# thanks to forslund
def translate_regex(self, regex):
if regex not in self.regexes:
path = self.find_resource(regex + '.regex')
if path:
with open(path) as f:
string = f.read().strip()
self.regexes[regex] = string
return self.regexes[regex]
######################################################################
# audio ducking
def handle_listener_started(self, message):
if self.ducking:
self.vlc_player.lower_volume()
def handle_listener_stopped(self, message):
if self.ducking:
self.vlc_player.restore_volume()
def handle_audio_start(self, event):
if self.ducking:
self.vlc_player.lower_volume()
def handle_audio_stop(self, event):
if self.ducking:
self.vlc_player.restore_volume()
##################################################################
# intents
@intent_handler(IntentBuilder("ResumeMusicIntent").require("resume.music"))
def handle_resume_music_intent(self, message):
if self.refreshing_lib:
self.speak_dialog("refresh.library")
return None
else:
self.vlc_player.play()
@intent_handler(IntentBuilder("PauseMusicIntent").require("pause.music"))
def handle_pause_music_intent(self, message):
if self.refreshing_lib:
self.speak_dialog("refresh.library")
return None
else:
self.vlc_player.pause()
@intent_handler(IntentBuilder("NextMusicIntent").require("next.music"))
def handle_next_music_intent(self, message):
if self.refreshing_lib:
self.speak_dialog("refresh.library")
return None
else:
self.vlc_player.next()
<<<<<<< Updated upstream
=======
>>>>>>> Stashed changes
@intent_handler(IntentBuilder("PrevMusicIntent").require("prev.music"))
def handle_prev_music_intent(self, message):
if self.refreshing_lib:
self.speak_dialog("refresh.library")
return None
else:
self.vlc_player.previous()
@intent_handler(IntentBuilder("InfoMusicIntent").require("information"))
def handle_music_information_intent(self, message):
if self.get_running():
meta = self.vlc_player.track_info()
artist, album, title = meta["artists"], meta["album"], meta["name"]
if title.startswith("file"):
media = self.vlc_player.player.get_media()
link = media.get_mrl()
artist, album, title = self.tracks[link]
if isinstance(artist, list):
artist = artist[0]
LOG.info("""\nPlex skill is playing:
{} by {}
Album: {}
""".format(title, artist, album))
self.speak_dialog('information', data={'title': title, "artist": artist})
@intent_handler(IntentBuilder("ReloadLibraryIntent").require("reload.library"))
def handle_reload_library_intent(self, message):
if self.refreshing_lib:
self.speak_dialog("already.refresh.library")
return None
else:
self.refreshing_lib = True
self.speak_dialog("refresh.library")
try:
os.remove(self.data_path)
except FileNotFoundError:
pass
self.load_data()
def converse(self, utterances, lang="en-us"):
return False
def stop(self):
self.vlc_player.stop()
def create_skill():
return PlexMusicSkill()