-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInternetRadio.py
342 lines (284 loc) · 10.2 KB
/
InternetRadio.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
import json
import re
import urllib
from core.base.model.AliceSkill import AliceSkill
from core.dialog.model.DialogSession import DialogSession
from core.util.Decorators import IntentHandler
from pathlib import Path
from urllib.request import urlopen
class InternetRadio(AliceSkill):
"""
Author: lazzaAU
Description: Listen to internet radio stations
"""
_CONFIGTEMPLATE = 'config.json.template'
_BACKUPCONFIGTEMPLATE = 'Backup/config.json.template'
def __init__(self):
self._templatePath = f'/InternetRadio/{self._CONFIGTEMPLATE}'
self._selectedStation = ""
self._data = dict()
self._backupPath = ""
self.playlist = list()
super().__init__()
@IntentHandler('StopPlayingRadio')
def StopRadio(self, session: DialogSession):
"""
Used for stopping music playing. In general this may not work due to alice's
speaker running already. However, still triggers from dialog view in the GUI
:param session: the dialog session
:return:
"""
self.Commons.runSystemCommand(f'mpc stop '.split())
self.Commons.runSystemCommand(f'mpc clear '.split())
if self.getConfig('startPlaying'):
self.updateConfig(key='startPlaying', value=False)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="StopPlaying"),
deviceUid=session.deviceUid
)
@IntentHandler("ListenToRadio")
def setupTheStation(self, session: DialogSession, **_kwargs):
# Read the config.json.template file to get the list of values
self._data = self.readTemplateData(configPath=self.getResource(self._CONFIGTEMPLATE))
# If user has not specified a station, just play the default station
if not 'RadioStation' in session.slotsAsObjects and not 'number' in session.slotsAsObjects:
self.stationSelected(station=self.getConfig(key='radioStations'))
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="StartPlaying"),
deviceUid=session.deviceUid
)
return
# If user specified the station, match it up to the url
# if user specified a number, select that line from the list if available
if session.slotValue('number'):
listLength = len(self._data)
number: int = session.slotValue('number')
# if user asks for list number that doesn't exist
if number > listLength:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="NrOutOfRange", replace=[number, listLength +1]),
deviceUid=session.deviceUid
)
return
else:
counter = 1
for item in self._data:
# update the config with selected url via number selection
if counter == number:
self._selectedStation = self._data.get(item)
self.updateConfig(key='radioStations', value=self._selectedStation)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="StartPlaying"),
deviceUid=session.deviceUid
)
self.stationSelected(station=self._selectedStation)
return
counter += 1
choosenStation = session.slotValue('RadioStation')
for key in self._data:
# update the config with choosen station via station name
if key in choosenStation:
# Find the requested station
self._selectedStation = self._data.get(key)
self.updateConfig(key='radioStations', value=self._selectedStation)
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="StartPlaying"),
deviceUid=session.deviceUid
)
self.stationSelected(station=self._selectedStation)
return
else:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="StationNotFound"),
deviceUid=session.deviceUid
)
def stopPlaying(self, value):
if value:
self.Commons.runSystemCommand(f'mpc stop '.split())
self.Commons.runSystemCommand(f'mpc clear '.split())
self.ThreadManager.doLater(
interval=4,
func=self.delayedConfigUpdate,
args=[
'stopPlaying',
False
]
)
if self.getConfig('startPlaying'):
self.ThreadManager.doLater(
interval=5,
func=self.delayedConfigUpdate,
args=[
'startPlaying',
False
]
)
self.say(
text=self.randomTalk(text="StopPlaying")
)
return True
def delayedConfigUpdate(self, key :str, value : bool):
"""
Required function to update the config on a timer after a onUpdate event
"""
self.updateConfig(key=key, value=value)
def startPlaying(self, value):
if value:
self.stationSelected(station=self.getConfig('radioStations'))
self.ThreadManager.doLater(
interval=5,
func=self.delayedConfigUpdate,
args=[
'stopPlaying',
False
]
)
return True
def stationSelected(self, station: str, session = None):
"""
When the user clicks the "confirm" button on the skill settings after selecting a station, or by verbally
Then parse the Url and play the selected Station, or stop the player if that toggle is enabled
:return:
"""
self.parsePlaylists(stationUrl=station)
if self.playlist or self._selectedStation:
self.runThePlayer()
if session:
self.endDialog(
sessionId=session.sessionId,
text=self.randomTalk(text="Confirmation")
)
return True
@staticmethod
def readTemplateData(configPath : Path):
"""
Read and store the template list
:return: dictionary of just the radio station list
"""
data = json.loads(configPath.read_text())
tempData = dict()
# Trim the original json to just the relevant values
for key in data['radioStations']['values']:
tempData[key] = data['radioStations']['values'][key]
return tempData
def runThePlayer(self):
"""
Commands to run the actual player
:return:
"""
self.Commons.runSystemCommand(f'mpc stop '.split())
self.Commons.runSystemCommand(f'mpc clear '.split())
if self.playlist:
urlPlaying = self.playlist[0]
for item in self.playlist:
self.Commons.runSystemCommand(f'mpc add {item}'.split())
else:
urlPlaying = self._selectedStation
self.Commons.runSystemCommand(f'mpc add {self._selectedStation}'.split())
result = self.Commons.runSystemCommand(f'mpc play'.split())
if self.getConfig(key='debugMode'):
status = self.Commons.runSystemCommand(f'mpc status'.split())
currentPlaylist = self.Commons.runSystemCommand(f'mpc playlist'.split())
self.logDebug(f"MPC status is {status}")
self.logWarning("--")
self.logDebug(f"Current playlist is {currentPlaylist}")
self.logWarning("--")
if not result.returncode:
self.logInfo(f'Playing Radio Station from *** {urlPlaying} ***')
else:
self.logWarning(f"Failed to play due to {result.stderr}")
self._selectedStation = ""
self.playlist = list()
def addSlotValues(self) -> bool:
"""
Update the dialogTemplate file with new slotvalues based on config.json.template
Then copy that file to the backup folder
:return:
"""
file = self.getResource(f'dialogTemplate/{self.activeLanguage()}.json')
if not file:
return False
# load the dialogTemplate file data
data = json.loads(file.read_text())
slotValue = list()
# Set up the slot values
for item in self._data:
tempData = {'value': item, 'synonyms': []}
slotValue.append(tempData)
# Add slot values to the dialogTemplate slotType
for i, suggestedSlot in enumerate(data['slotTypes']):
if "radiostation" in suggestedSlot['name'].lower():
data['slotTypes'][i]['values'] = slotValue
file.write_text(json.dumps(data, ensure_ascii=False, indent=4))
self.logInfo(f"Radio files have been backed up, please retrain or restart Alice")
# Make a backup of the file , so user can back up settings if needed
self.Commons.runSystemCommand(['cp', file, self.getResource(f'Backup/dialogTemplate/{self.activeLanguage()}.json') ])
return True
def BackupPathRoutines(self):
"""
Make backup directories if they don't exist. Then Backup the config.template file
if it's not the same as existing backup
:return:
"""
self._data = self.readTemplateData(configPath=self.getResource(self._CONFIGTEMPLATE))
if not self.getResource('Backup').exists():
self.logWarning(f'No BackUp directory found, so I\'m making one')
self.getResource("Backup").mkdir()
self.getResource("Backup/dialogTemplate").mkdir()
if self.getResource(self._BACKUPCONFIGTEMPLATE).exists():
self.logInfo("Retreiving Backup Data")
templateData = self.readTemplateData(self.getResource(self._CONFIGTEMPLATE))
backupTemplateData = self.readTemplateData(self.getResource(self._BACKUPCONFIGTEMPLATE))
# Check if config template file is not the same as the backup version
if not templateData == backupTemplateData:
self.Commons.runSystemCommand(["rm", "-f", self.getResource(self._BACKUPCONFIGTEMPLATE)])
self.Commons.runSystemCommand(["cp", self.getResource(self._CONFIGTEMPLATE), self.getResource(self._BACKUPCONFIGTEMPLATE)])
self.addSlotValues()
else:
self.Commons.runSystemCommand(["cp", self.getResource(self._CONFIGTEMPLATE), self.getResource(self._BACKUPCONFIGTEMPLATE)])
self.Commons.runSystemCommand(['cp', self.getResource(f'dialogTemplate/{self.activeLanguage()}.json'), self.getResource(f'Backup/dialogTemplate/{self.activeLanguage()}.json') ])
self.logDebug(f"Just backed up your Radio configuration")
def onBooted(self) -> bool:
self.BackupPathRoutines()
super().onBooted()
return True
def parsePlaylists(self, stationUrl):
"""
Parse .pls playlists and .m3u playlists and direct streaming links
:param stationUrl: The selected URL to play
:return:
"""
urlFormat = ""
urlType = ""
self.playlist = list()
if "tuneIn" in stationUrl and ".pls" in stationUrl:
urlFormat = "http.+(?=\r)"
urlType = "tuneIn .pls"
elif not "tuneIn" in stationUrl and ".pls" in stationUrl:
urlFormat = "http.+"
urlType = "General .pls"
if ".m3u" in stationUrl and not ".m3u8" in stationUrl:
urlFormat = "ht.+"
urlType = "m3u"
if not urlFormat:
self._selectedStation = stationUrl
return
try:
if self.getConfig(key='debugMode'):
self.logInfo(f" {urlType} detected")
req = urllib.request.urlopen(stationUrl)
file = req.read()
decodedFile = file.decode() # From bytes to str
if self.getConfig(key='debugMode'):
self.logDebug(f"Pre-parsed URL: {decodedFile}")
pattern = re.compile(urlFormat)
for item in pattern.findall(decodedFile):
self.playlist.append(item)
except Exception as msg:
self.logWarning(f"{msg}")