]> git.0d.be Git - botaradio.git/blob - command.py
REFACTOR: DIFFERENT PLAYLIST #91
[botaradio.git] / command.py
1 # coding=utf-8
2 import logging
3 import os.path
4 import pymumble.pymumble_py3 as pymumble
5 import re
6
7 import constants
8 import media.system
9 import util
10 import variables as var
11 from librb import radiobrowser
12 from database import Database
13 from media.playlist import PlaylistItemWrapper
14 from media.file import FileItem
15 from media.url_from_playlist import PlaylistURLItem, get_playlist_info
16 from media.url import URLItem
17 from media.radio import RadioItem
18
19 log = logging.getLogger("bot")
20
21 def register_all_commands(bot):
22     bot.register_command(constants.commands('joinme'), cmd_joinme)
23     bot.register_command(constants.commands('user_ban'), cmd_user_ban)
24     bot.register_command(constants.commands('user_unban'), cmd_user_unban)
25     bot.register_command(constants.commands('url_ban'), cmd_url_ban)
26     bot.register_command(constants.commands('url_unban'), cmd_url_unban)
27     bot.register_command(constants.commands('play'), cmd_play)
28     bot.register_command(constants.commands('pause'), cmd_pause)
29     bot.register_command(constants.commands('play_file'), cmd_play_file)
30     bot.register_command(constants.commands('play_file_match'), cmd_play_file_match)
31     bot.register_command(constants.commands('play_url'), cmd_play_url)
32     bot.register_command(constants.commands('play_playlist'), cmd_play_playlist)
33     bot.register_command(constants.commands('play_radio'), cmd_play_radio)
34     bot.register_command(constants.commands('rb_query'), cmd_rb_query)
35     bot.register_command(constants.commands('rb_play'), cmd_rb_play)
36     bot.register_command(constants.commands('yt_search'), cmd_yt_search)
37     bot.register_command(constants.commands('yt_play'), cmd_yt_play)
38     bot.register_command(constants.commands('help'), cmd_help)
39     bot.register_command(constants.commands('stop'), cmd_stop)
40     bot.register_command(constants.commands('clear'), cmd_clear)
41     bot.register_command(constants.commands('kill'), cmd_kill)
42     bot.register_command(constants.commands('update'), cmd_update)
43     bot.register_command(constants.commands('stop_and_getout'), cmd_stop_and_getout)
44     bot.register_command(constants.commands('volume'), cmd_volume)
45     bot.register_command(constants.commands('ducking'), cmd_ducking)
46     bot.register_command(constants.commands('ducking_threshold'), cmd_ducking_threshold)
47     bot.register_command(constants.commands('ducking_volume'), cmd_ducking_volume)
48     bot.register_command(constants.commands('current_music'), cmd_current_music)
49     bot.register_command(constants.commands('skip'), cmd_skip)
50     bot.register_command(constants.commands('last'), cmd_last)
51     bot.register_command(constants.commands('remove'), cmd_remove)
52     bot.register_command(constants.commands('list_file'), cmd_list_file)
53     bot.register_command(constants.commands('queue'), cmd_queue)
54     bot.register_command(constants.commands('random'), cmd_random)
55     bot.register_command(constants.commands('repeat'), cmd_repeat)
56     bot.register_command(constants.commands('mode'), cmd_mode)
57     bot.register_command(constants.commands('drop_database'), cmd_drop_database)
58
59     # Just for debug use
60     bot.register_command('rtrms', cmd_real_time_rms)
61     bot.register_command('loop', cmd_loop_state)
62     bot.register_command('item', cmd_item)
63
64 def send_multi_lines(bot, lines, text):
65     global log
66
67     msg = ""
68     br = ""
69     for newline in lines:
70         msg += br
71         br = "<br>"
72         if (len(msg) + len(newline)) > (bot.mumble.get_max_message_length() - 4) != 0: # 4 == len("<br>")
73             bot.send_msg(msg, text)
74             msg = ""
75         msg += newline
76
77     bot.send_msg(msg, text)
78
79 # ---------------- Commands ------------------
80
81
82 def cmd_joinme(bot, user, text, command, parameter):
83     global log
84
85     bot.mumble.users.myself.move_in(
86         bot.mumble.users[text.actor]['channel_id'], token=parameter)
87
88
89 def cmd_user_ban(bot, user, text, command, parameter):
90     global log
91
92     if bot.is_admin(user):
93         if parameter:
94             bot.mumble.users[text.actor].send_text_message(util.user_ban(parameter))
95         else:
96             bot.mumble.users[text.actor].send_text_message(util.get_user_ban())
97     else:
98         bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
99     return
100
101
102 def cmd_user_unban(bot, user, text, command, parameter):
103     global log
104
105     if bot.is_admin(user):
106         if parameter:
107             bot.mumble.users[text.actor].send_text_message(util.user_unban(parameter))
108     else:
109         bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
110     return
111
112
113 def cmd_url_ban(bot, user, text, command, parameter):
114     global log
115
116     if bot.is_admin(user):
117         if parameter:
118             bot.mumble.users[text.actor].send_text_message(util.url_ban(util.get_url_from_input(parameter)))
119         else:
120             bot.mumble.users[text.actor].send_text_message(util.get_url_ban())
121     else:
122         bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
123     return
124
125
126 def cmd_url_unban(bot, user, text, command, parameter):
127     global log
128
129     if bot.is_admin(user):
130         if parameter:
131             bot.mumble.users[text.actor].send_text_message(util.url_unban(util.get_url_from_input(parameter)))
132     else:
133         bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
134     return
135
136
137 def cmd_play(bot, user, text, command, parameter):
138     global log
139
140     if len(var.playlist) > 0:
141         if parameter:
142             if parameter.isdigit() and 1 <= int(parameter) <= len(var.playlist):
143                 var.playlist.point_to(int(parameter) - 1 - 1) # First "-1" transfer 12345 to 01234, second "-1"
144                                                             # point to the previous item. the loop will next to
145                                                             # the one you want
146                 bot.interrupt()
147             else:
148                 bot.send_msg(constants.strings('invalid_index', index=parameter), text)
149
150         elif bot.is_pause:
151             bot.resume()
152         else:
153             bot.send_msg(var.playlist.current_item().format_current_playing(), text)
154     else:
155         bot.is_pause = False
156         bot.send_msg(constants.strings('queue_empty'), text)
157
158
159 def cmd_pause(bot, user, text, command, parameter):
160     global log
161
162     bot.pause()
163     bot.send_msg(constants.strings('paused'))
164
165
166 def cmd_play_file(bot, user, text, command, parameter):
167     global log
168
169     # if parameter is {index}
170     if parameter.isdigit():
171         files = util.get_recursive_file_list_sorted(var.music_folder)
172         if int(parameter) < len(files):
173             filename = files[int(parameter)].replace(var.music_folder, '')
174             music_wrapper = PlaylistItemWrapper(FileItem(bot, filename), user)
175             var.playlist.append(music_wrapper)
176             music = music_wrapper.item
177             log.info("cmd: add to playlist: " + music.format_debug_string())
178             bot.send_msg(constants.strings('file_added', item=music.format_song_string(user)), text)
179
180     # if parameter is {path}
181     else:
182         # sanitize "../" and so on
183         path = os.path.abspath(os.path.join(var.music_folder, parameter))
184         if not path.startswith(os.path.abspath(var.music_folder)):
185             bot.send_msg(constants.strings('no_file'), text)
186             return
187
188         if os.path.isfile(path):
189             music_wrapper = PlaylistItemWrapper(FileItem(bot, parameter), user)
190             var.playlist.append(music_wrapper)
191             music = music_wrapper.item
192             log.info("cmd: add to playlist: " + music.format_debug_string())
193             bot.send_msg(constants.strings('file_added', item=music.format_song_string(user)), text)
194             return
195
196         # if parameter is {folder}
197         elif os.path.isdir(path):
198             if parameter != '.' and parameter != './':
199                 if not parameter.endswith("/"):
200                     parameter += "/"
201             else:
202                 parameter = ""
203
204             files = util.get_recursive_file_list_sorted(var.music_folder)
205             music_library = util.Dir(var.music_folder)
206             for file in files:
207                 music_library.add_file(file)
208
209             files = music_library.get_files(parameter)
210             msgs = [constants.strings('multiple_file_added')]
211             count = 0
212
213             for file in files:
214                 count += 1
215                 music_wrapper = PlaylistItemWrapper(FileItem(bot, file), user)
216                 var.playlist.append(music_wrapper)
217                 music = music_wrapper.item
218                 log.info("cmd: add to playlist: " + music.format_debug_string())
219                 msgs.append("{} ({})".format(music.title, music.path))
220
221             if count != 0:
222                 send_multi_lines(bot, msgs, text)
223             else:
224                 bot.send_msg(constants.strings('no_file'), text)
225
226         else:
227             # try to do a partial match
228             files = util.get_recursive_file_list_sorted(var.music_folder)
229             matches = [(index, file) for index, file in enumerate(files) if parameter.lower() in file.lower()]
230             if len(matches) == 0:
231                 bot.send_msg(constants.strings('no_file'), text)
232             elif len(matches) == 1:
233                 file = matches[0][1]
234                 music_wrapper = PlaylistItemWrapper(FileItem(bot, file), user)
235                 var.playlist.append(music_wrapper)
236                 music = music_wrapper.item
237                 log.info("cmd: add to playlist: " + music.format_debug_string())
238                 bot.send_msg(constants.strings('file_added', item=music.format_song_string(user)), text)
239             else:
240                 msgs = [ constants.strings('multiple_matches')]
241                 for match in matches:
242                     msgs.append("<b>{:0>3d}</b> - {:s}".format(match[0], match[1]))
243                 send_multi_lines(bot, msgs, text)
244
245
246 def cmd_play_file_match(bot, user, text, command, parameter):
247     global log
248
249     music_folder = var.music_folder
250     if parameter:
251         files = util.get_recursive_file_list_sorted(music_folder)
252         msgs = [ constants.strings('multiple_file_added')]
253         count = 0
254         try:
255             for file in files:
256                 match = re.search(parameter, file)
257                 if match:
258                     count += 1
259                     music_wrapper = PlaylistItemWrapper(FileItem(bot, file), user)
260                     var.playlist.append(music_wrapper)
261                     music = music_wrapper.item
262                     log.info("cmd: add to playlist: " + music.format_debug_string())
263                     msgs.append("{} ({})".format(music.title, music.path))
264
265             if count != 0:
266                 send_multi_lines(bot, msgs, text)
267             else:
268                 bot.send_msg(constants.strings('no_file'), text)
269
270         except re.error as e:
271             msg = constants.strings('wrong_pattern', error=str(e))
272             bot.send_msg(msg, text)
273     else:
274         bot.send_msg(constants.strings('bad_parameter', command))
275
276
277 def cmd_play_url(bot, user, text, command, parameter):
278     global log
279
280     url = util.get_url_from_input(parameter)
281     music_wrapper = PlaylistItemWrapper(URLItem(bot, url), user)
282     var.playlist.append(music_wrapper)
283
284     log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
285     bot.send_msg(constants.strings('file_added', item=music_wrapper.format_song_string()), text)
286     if len(var.playlist) == 2:
287         # If I am the second item on the playlist. (I am the next one!)
288         bot.async_download_next()
289
290
291 def cmd_play_playlist(bot, user, text, command, parameter):
292     global log
293
294     offset = 0  # if you want to start the playlist at a specific index
295     try:
296         offset = int(parameter.split(" ")[-1])
297     except ValueError:
298         pass
299
300     url = util.get_url_from_input(parameter)
301     log.debug("cmd: fetching media info from playlist url %s" % url)
302     items = get_playlist_info(bot, url=url, start_index=offset, user=user)
303     if len(items) > 0:
304         var.playlist.extend(list(map(lambda item: PlaylistItemWrapper(item, user), items)))
305         for music in items:
306             log.info("cmd: add to playlist: " + music.format_debug_string())
307     else:
308         bot.send_msg(constants.strings("playlist_fetching_failed"), text)
309
310
311 def cmd_play_radio(bot, user, text, command, parameter):
312     global log
313
314     if not parameter:
315         all_radio = var.config.items('radio')
316         msg = constants.strings('preconfigurated_radio')
317         for i in all_radio:
318             comment = ""
319             if len(i[1].split(maxsplit=1)) == 2:
320                 comment = " - " + i[1].split(maxsplit=1)[1]
321             msg += "<br />" + i[0] + comment
322         bot.send_msg(msg, text)
323     else:
324         if var.config.has_option('radio', parameter):
325             parameter = var.config.get('radio', parameter)
326             parameter = parameter.split()[0]
327         url = util.get_url_from_input(parameter)
328         if url:
329             music_wrapper = PlaylistItemWrapper(RadioItem(bot, url), user)
330
331             var.playlist.append(music_wrapper)
332             log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
333         else:
334             bot.send_msg(constants.strings('bad_url'))
335
336
337 def cmd_rb_query(bot, user, text, command, parameter):
338     global log
339
340     log.info('cmd: Querying radio stations')
341     if not parameter:
342         log.debug('rbquery without parameter')
343         msg = constants.strings('rb_query_empty')
344         bot.send_msg(msg, text)
345     else:
346         log.debug('cmd: Found query parameter: ' + parameter)
347         # bot.send_msg('Searching for stations - this may take some seconds...', text)
348         rb_stations = radiobrowser.getstations_byname(parameter)
349         msg = constants.strings('rb_query_result')
350         msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
351         if not rb_stations:
352             log.debug('cmd: No matches found for rbquery ' + parameter)
353             bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
354         else:
355             for s in rb_stations:
356                 stationid = s['id']
357                 stationname = s['stationname']
358                 country = s['country']
359                 codec = s['codec']
360                 bitrate = s['bitrate']
361                 genre = s['genre']
362                 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
363                 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
364                     stationid, stationname, genre, codec, bitrate, country)
365             msg += '</table>'
366             # Full message as html table
367             if len(msg) <= 5000:
368                 bot.send_msg(msg, text)
369             # Shorten message if message too long (stage I)
370             else:
371                 log.debug('Result too long stage I')
372                 msg = constants.strings('rb_query_result') + ' (shortened L1)'
373                 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
374                 for s in rb_stations:
375                     stationid = s['id']
376                     stationname = s['stationname']
377                     # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
378                     msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
379                 msg += '</table>'
380                 if len(msg) <= 5000:
381                     bot.send_msg(msg, text)
382                 # Shorten message if message too long (stage II)
383                 else:
384                     log.debug('Result too long stage II')
385                     msg = constants.strings('rb_query_result') + ' (shortened L2)'
386                     msg += '!rbplay ID - Station Name'
387                     for s in rb_stations:
388                         stationid = s['id']
389                         stationname = s['stationname'][:12]
390                         # msg += f'{stationid} - {stationname}'
391                         msg += '%s - %s' % (stationid, stationname)
392                     if len(msg) <= 5000:
393                         bot.send_msg(msg, text)
394                     # Message still too long
395                     else:
396                         bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
397                                      text)
398
399
400 def cmd_rb_play(bot, user, text, command, parameter):
401     global log
402
403     log.debug('cmd: Play a station by ID')
404     if not parameter:
405         log.debug('rbplay without parameter')
406         msg = constants.strings('rb_play_empty')
407         bot.send_msg(msg, text)
408     else:
409         log.debug('cmd: Retreiving url for station ID ' + parameter)
410         rstation = radiobrowser.getstationname_byid(parameter)
411         stationname = rstation[0]['name']
412         country = rstation[0]['country']
413         codec = rstation[0]['codec']
414         bitrate = rstation[0]['bitrate']
415         genre = rstation[0]['tags']
416         homepage = rstation[0]['homepage']
417         msg = 'Radio station added to playlist:'
418         # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
419         #       f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
420         msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
421                '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
422                % (parameter, stationname, genre, codec, bitrate, country, homepage)
423         log.debug('cmd: Added station to playlist %s' % stationname)
424         bot.send_msg(msg, text)
425         url = radiobrowser.geturl_byid(parameter)
426         if url != "-1":
427             log.info('cmd: Found url: ' + url)
428             music_wrapper = PlaylistItemWrapper(RadioItem(bot, url, stationname), user)
429             var.playlist.append(music_wrapper)
430             log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
431             bot.async_download_next()
432         else:
433             log.info('cmd: No playable url found.')
434             msg += "No playable url found for this station, please try another station."
435             bot.send_msg(msg, text)
436
437 yt_last_result = []
438 yt_last_page = 0 # TODO: if we keep adding global variables, we need to consider sealing all commands up into classes.
439
440 def cmd_yt_search(bot, user, text, command, parameter):
441     global log, yt_last_result, yt_last_page
442     item_per_page = 5
443
444     if parameter:
445         # if next page
446         if parameter.startswith("-n"):
447             yt_last_page += 1
448             if len(yt_last_result) > yt_last_page * item_per_page:
449                 msg = _yt_format_result(yt_last_result, yt_last_page * item_per_page, item_per_page)
450                 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
451             else:
452                 bot.send_msg(constants.strings('yt_no_more'))
453
454         # if query
455         else:
456             results = util.youtube_search(parameter)
457             if results:
458                 yt_last_result = results
459                 yt_last_page = 0
460                 msg = _yt_format_result(results, 0, item_per_page)
461                 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
462             else:
463                 bot.send_msg(constants.strings('yt_query_error'))
464     else:
465         bot.send_msg(constants.strings('bad_parameter', command=command), text)
466
467 def _yt_format_result(results, start, count):
468     msg = '<table><tr><th width="10%">Index</th><th>Title</th><th width="20%">Uploader</th></tr>'
469     for index, item in enumerate(results[start:start+count]):
470         msg += '<tr><td>{index:d}</td><td>{title}</td><td>{uploader}</td></tr>'.format(
471             index=index + 1 + start, title=item[1], uploader=item[2])
472     msg += '</table>'
473
474     return msg
475
476
477 def cmd_yt_play(bot, user, text, command, parameter):
478     global log, yt_last_result, yt_last_page
479
480     if parameter:
481         if parameter.isdigit() and 0 <= int(parameter) - 1 < len(yt_last_result):
482             url = "https://www.youtube.com/watch?v=" + yt_last_result[int(parameter) - 1][0]
483             cmd_play_url(bot, user, text, command, url)
484         else:
485             results = util.youtube_search(parameter)
486             if results:
487                 yt_last_result = results
488                 yt_last_page = 0
489                 url = "https://www.youtube.com/watch?v=" + yt_last_result[0][0]
490                 cmd_play_url(bot, user, text, command, url)
491             else:
492                 bot.send_msg(constants.strings('yt_query_error'))
493     else:
494         bot.send_msg(constants.strings('bad_parameter', command=command), text)
495
496
497 def cmd_help(bot, user, text, command, parameter):
498     global log
499
500     bot.send_msg(constants.strings('help'), text)
501     if bot.is_admin(user):
502         bot.send_msg(constants.strings('admin_help'), text)
503
504
505 def cmd_stop(bot, user, text, command, parameter):
506     global log
507
508     bot.stop()
509     bot.send_msg(constants.strings('stopped'), text)
510
511
512 def cmd_clear(bot, user, text, command, parameter):
513     global log
514
515     bot.clear()
516     bot.send_msg(constants.strings('cleared'), text)
517
518
519 def cmd_kill(bot, user, text, command, parameter):
520     global log
521
522     if bot.is_admin(user):
523         bot.pause()
524         bot.exit = True
525     else:
526         bot.mumble.users[text.actor].send_text_message(
527             constants.strings('not_admin'))
528
529
530 def cmd_update(bot, user, text, command, parameter):
531     global log
532
533     if bot.is_admin(user):
534         bot.mumble.users[text.actor].send_text_message(
535             constants.strings('start_updating'))
536         msg = util.update(bot.version)
537         bot.mumble.users[text.actor].send_text_message(msg)
538     else:
539         bot.mumble.users[text.actor].send_text_message(
540             constants.strings('not_admin'))
541
542
543 def cmd_stop_and_getout(bot, user, text, command, parameter):
544     global log
545
546     bot.stop()
547     if bot.channel:
548         bot.mumble.channels.find_by_name(bot.channel).move_in()
549
550
551 def cmd_volume(bot, user, text, command, parameter):
552     global log
553
554     # The volume is a percentage
555     if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
556         bot.volume_set = float(float(parameter) / 100)
557         bot.send_msg(constants.strings('change_volume',
558             volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
559         var.db.set('bot', 'volume', str(bot.volume_set))
560         log.info('cmd: volume set to %d' % (bot.volume_set * 100))
561     else:
562         bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
563
564
565 def cmd_ducking(bot, user, text, command, parameter):
566     global log
567
568     if parameter == "" or parameter == "on":
569         bot.is_ducking = True
570         var.db.set('bot', 'ducking', True)
571         bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
572         bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
573         bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
574                                           bot.ducking_sound_received)
575         bot.mumble.set_receive_sound(True)
576         log.info('cmd: ducking is on')
577         msg = "Ducking on."
578         bot.send_msg(msg, text)
579     elif parameter == "off":
580         bot.is_ducking = False
581         bot.mumble.set_receive_sound(False)
582         var.db.set('bot', 'ducking', False)
583         msg = "Ducking off."
584         log.info('cmd: ducking is off')
585         bot.send_msg(msg, text)
586
587
588 def cmd_ducking_threshold(bot, user, text, command, parameter):
589     global log
590
591     if parameter and parameter.isdigit():
592         bot.ducking_threshold = int(parameter)
593         var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
594         msg = "Ducking threshold set to %d." % bot.ducking_threshold
595         bot.send_msg(msg, text)
596     else:
597         msg = "Current ducking threshold is %d." % bot.ducking_threshold
598         bot.send_msg(msg, text)
599
600
601 def cmd_ducking_volume(bot, user, text, command, parameter):
602     global log
603
604     # The volume is a percentage
605     if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
606         bot.ducking_volume = float(float(parameter) / 100)
607         bot.send_msg(constants.strings('change_ducking_volume',
608             volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
609         # var.db.set('bot', 'volume', str(bot.volume_set))
610         var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
611         log.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
612     else:
613         bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
614
615
616 def cmd_current_music(bot, user, text, command, parameter):
617     global log
618
619     reply = ""
620     if len(var.playlist) > 0:
621         bot.send_msg(var.playlist.current_item().format_current_playing())
622     else:
623         reply = constants.strings('not_playing')
624     bot.send_msg(reply, text)
625
626
627 def cmd_skip(bot, user, text, command, parameter):
628     global log
629
630     bot.interrupt()
631
632     if len(var.playlist) == 0:
633         bot.send_msg(constants.strings('queue_empty'), text)
634
635
636 def cmd_last(bot, user, text, command, parameter):
637     global log
638
639     if len(var.playlist) > 0:
640         bot.interrupt()
641         var.playlist.point_to(len(var.playlist) - 1)
642     else:
643         bot.send_msg(constants.strings('queue_empty'), text)
644
645
646 def cmd_remove(bot, user, text, command, parameter):
647     global log
648
649     # Allow to remove specific music into the queue with a number
650     if parameter and parameter.isdigit() and int(parameter) > 0 \
651             and int(parameter) <= len(var.playlist):
652
653         index = int(parameter) - 1
654
655         removed = None
656         if index == var.playlist.current_index:
657             removed = var.playlist.remove(index)
658
659             if index < len(var.playlist):
660                 if not bot.is_pause:
661                     bot.interrupt()
662                     var.playlist.current_index -= 1
663                     # then the bot will move to next item
664
665             else: # if item deleted is the last item of the queue
666                 var.playlist.current_index -= 1
667                 if not bot.is_pause:
668                     bot.interrupt()
669         else:
670             removed = var.playlist.remove(index)
671
672         bot.send_msg(constants.strings('removing_item',
673             item=removed.format_short_string()), text)
674
675         log.info("cmd: delete from playlist: " + removed.format_debug_string())
676     else:
677         bot.send_msg(constants.strings('bad_parameter', command=command))
678
679
680 def cmd_list_file(bot, user, text, command, parameter):
681     global log
682
683     folder_path = var.music_folder
684
685     files = util.get_recursive_file_list_sorted(folder_path)
686     msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
687     try:
688         count = 0
689         for index, file in enumerate(files):
690             if parameter:
691                 match = re.search(parameter, file)
692                 if not match:
693                     continue
694
695             count += 1
696             msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
697
698         if count != 0:
699             send_multi_lines(bot, msgs, text)
700         else:
701             bot.send_msg(constants.strings('no_file'), text)
702
703     except re.error as e:
704         msg = constants.strings('wrong_pattern', error=str(e))
705         bot.send_msg(msg, text)
706
707
708 def cmd_queue(bot, user, text, command, parameter):
709     global log
710
711     if len(var.playlist) == 0:
712         msg = constants.strings('queue_empty')
713         bot.send_msg(msg, text)
714     else:
715         msgs = [ constants.strings('queue_contents')]
716         for i, value in enumerate(var.playlist):
717             newline = ''
718             music = value.item
719             if i == var.playlist.current_index:
720                 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, music.display_type(),
721                                                            music.format_short_string())
722             else:
723                 newline = '<b>{}</b> ({}) {}'.format(i + 1, music.display_type(),
724                                                            music.format_short_string())
725
726             msgs.append(newline)
727
728         send_multi_lines(bot, msgs, text)
729
730 def cmd_random(bot, user, text, command, parameter):
731     global log
732
733     bot.interrupt()
734     var.playlist.randomize()
735
736 def cmd_repeat(bot, user, text, command, parameter):
737     global log
738
739     repeat = 1
740     if parameter and parameter.isdigit():
741         repeat = int(parameter)
742
743     music = var.playlist.current_item()
744     for _ in range(repeat):
745         var.playlist.insert(
746             var.playlist.current_index + 1,
747             music
748         )
749         log.info("bot: add to playlist: " + music.format_debug_string)
750
751     bot.send_msg(constants.strings("repeat", song=music.format_song_string, n=str(repeat)), text)
752
753 def cmd_mode(bot, user, text, command, parameter):
754     global log
755
756     if not parameter:
757         bot.send_msg(constants.strings("current_mode", mode=var.playlist.mode), text)
758         return
759     if not parameter in ["one-shot", "repeat", "random"]:
760         bot.send_msg(constants.strings('unknown_mode', mode=parameter), text)
761     else:
762         var.db.set('playlist', 'playback_mode', parameter)
763         var.playlist = media.playlist.get_playlist(parameter, var.playlist)
764         log.info("command: playback mode changed to %s." % parameter)
765         bot.send_msg(constants.strings("change_mode", mode=var.playlist.mode,
766                                        user=bot.mumble.users[text.actor]['name']), text)
767         if parameter == "random":
768             bot.interrupt()
769             bot.launch_music()
770
771 def cmd_drop_database(bot, user, text, command, parameter):
772     global log
773
774     var.db.drop_table()
775     var.db = Database(var.dbfile)
776     bot.send_msg(constants.strings('database_dropped'), text)
777
778 # Just for debug use
779 def cmd_real_time_rms(bot, user, text, command, parameter):
780     bot._display_rms = not bot._display_rms
781
782 def cmd_loop_state(bot, user, text, command, parameter):
783     print(bot._loop_status)
784
785 def cmd_item(bot, user, text, command, parameter):
786     print(bot.wait_for_downloading)
787     print(var.playlist.current_item().item.to_dict())