Пример #1
0
def cmd_delete_from_library(bot, user, text, command, parameter):
    global song_shortlist, log
    try:
        indexes = [int(i) for i in parameter.split(" ")]
    except ValueError:
        bot.send_msg(constants.strings('bad_parameter', command=command), text)
        return

    if len(indexes) > 1:
        msgs = [constants.strings('multiple_file_added') + "<ul>"]
        count = 0
        for index in indexes:
            if 1 <= index <= len(song_shortlist):
                music_dict = song_shortlist[index - 1]
                if 'id' in music_dict:
                    music_wrapper = get_cached_wrapper_by_id(
                        bot, music_dict['id'], user)
                    log.info("cmd: remove from library: " +
                             music_wrapper.format_debug_string())
                    msgs.append("<li>[{}] <b>{}</b></li>".format(
                        music_wrapper.item().type,
                        music_wrapper.item().title))
                    var.playlist.remove_by_id(music_dict['id'])
                    var.cache.free_and_delete(music_dict['id'])
                    count += 1
            else:
                bot.send_msg(
                    constants.strings('bad_parameter', command=command), text)
                return

        if count == 0:
            bot.send_msg(constants.strings('bad_parameter', command=command),
                         text)
            return

        msgs.append("</ul>")
        send_multi_lines(bot, msgs, None, "")
        return
    elif len(indexes) == 1:
        index = indexes[0]
        if 1 <= index <= len(song_shortlist):
            music_dict = song_shortlist[index - 1]
            if 'id' in music_dict:
                music_wrapper = get_cached_wrapper_by_id(
                    bot, music_dict['id'], user)
                bot.send_msg(
                    constants.strings('file_deleted',
                                      item=music_wrapper.format_song_string()),
                    text)
                log.info("cmd: remove from library: " +
                         music_wrapper.format_debug_string())
                var.playlist.remove_by_id(music_dict['id'])
                var.cache.free_and_delete(music_dict['id'])
                return

    bot.send_msg(constants.strings('bad_parameter', command=command), text)
Пример #2
0
    def load(self):
        current_index = var.db.getint("playlist", "current_index", fallback=-1)
        if current_index == -1:
            return

        items = var.db.items("playlist_item")
        if items:
            music_wrappers = []
            items.sort(key=lambda v: int(v[0]))
            for item in items:
                item = json.loads(item[1])
                music_wrapper = get_cached_wrapper_by_id(var.bot, item['id'], item['user'])
                if music_wrapper:
                    music_wrappers.append(music_wrapper)
            self.from_list(music_wrappers, current_index)
Пример #3
0
def library():
    global log
    ITEM_PER_PAGE = 10

    if request.form:
        log.debug("web: Post request from %s: %s" %
                  (request.remote_addr, str(request.form)))

        if request.form['action'] in ['add', 'query', 'delete']:
            condition = build_library_query_condition(request.form)

            total_count = 0
            try:
                total_count = var.music_db.query_music_count(condition)
            except sqlite3.OperationalError:
                pass

            if not total_count:
                return ('', 204)

            if request.form['action'] == 'add':
                items = dicts_to_items(var.music_db.query_music(condition))
                music_wrappers = []
                for item in items:
                    music_wrapper = get_cached_wrapper(item, user)
                    music_wrappers.append(music_wrapper)

                    log.info("cmd: add to playlist: " +
                             music_wrapper.format_debug_string())

                var.playlist.extend(music_wrappers)

                return redirect("./", code=302)
            elif request.form['action'] == 'delete':
                items = dicts_to_items(var.music_db.query_music(condition))
                for item in items:
                    var.playlist.remove_by_id(item.id)
                    item = var.cache.get_item_by_id(item.id)

                    if os.path.isfile(item.uri()):
                        log.info("web: delete file " + item.uri())
                        os.remove(item.uri())

                    var.cache.free_and_delete(item.id)

                if len(os.listdir(var.music_folder +
                                  request.form['dir'])) == 0:
                    os.rmdir(var.music_folder + request.form['dir'])

                time.sleep(0.1)
                return redirect("./", code=302)
            else:
                page_count = math.ceil(total_count / ITEM_PER_PAGE)

                current_page = int(
                    request.form['page']) if 'page' in request.form else 1
                if current_page <= page_count:
                    condition.offset((current_page - 1) * ITEM_PER_PAGE)
                else:
                    current_page = 1

                condition.limit(ITEM_PER_PAGE)
                items = dicts_to_items(var.music_db.query_music(condition))

                results = []
                for item in items:
                    result = {}
                    result['id'] = item.id
                    result['title'] = item.title
                    result['type'] = item.display_type()
                    result['tags'] = [(tag, tag_color(tag))
                                      for tag in item.tags]
                    if item.type != 'radio' and item.thumbnail:
                        result[
                            'thumb'] = f"data:image/PNG;base64,{item.thumbnail}"
                    else:
                        result['thumb'] = "static/image/unknown-album.png"

                    if item.type == 'file':
                        result['path'] = item.path
                        result['artist'] = item.artist
                    else:
                        result['path'] = item.url
                        result['artist'] = "??"

                    results.append(result)

                return jsonify({
                    'items': results,
                    'total_pages': page_count,
                    'active_page': current_page
                })
        elif request.form['action'] == 'edit_tags':
            tags = list(dict.fromkeys(
                request.form['tags'].split(",")))  # remove duplicated items
            if request.form['id'] in var.cache:
                music_wrapper = get_cached_wrapper_by_id(
                    request.form['id'], user)
                music_wrapper.clear_tags()
                music_wrapper.add_tags(tags)
                var.playlist.version += 1
            else:
                item = var.music_db.query_music_by_id(request.form['id'])
                item['tags'] = tags
                var.music_db.insert_music(item)
            return redirect("./", code=302)

    else:
        abort(400)
Пример #4
0
def post():
    global log

    if request.method == 'POST':
        if request.form:
            log.debug("web: Post request from %s: %s" %
                      (request.remote_addr, str(request.form)))

        if 'add_item_at_once' in request.form:
            music_wrapper = get_cached_wrapper_by_id(
                request.form['add_item_at_once'], user)
            if music_wrapper:
                var.playlist.insert(var.playlist.current_index + 1,
                                    music_wrapper)
                log.info('web: add to playlist(next): ' +
                         music_wrapper.format_debug_string())
                if not var.bot.is_pause:
                    var.bot.interrupt()
                else:
                    var.bot.is_pause = False
            else:
                abort(404)

        if 'add_item_bottom' in request.form:
            music_wrapper = get_cached_wrapper_by_id(
                request.form['add_item_bottom'], user)

            if music_wrapper:
                var.playlist.append(music_wrapper)
                log.info('web: add to playlist(bottom): ' +
                         music_wrapper.format_debug_string())
            else:
                abort(404)

        elif 'add_item_next' in request.form:
            music_wrapper = get_cached_wrapper_by_id(
                request.form['add_item_next'], user)
            if music_wrapper:
                var.playlist.insert(var.playlist.current_index + 1,
                                    music_wrapper)
                log.info('web: add to playlist(next): ' +
                         music_wrapper.format_debug_string())
            else:
                abort(404)

        elif 'add_url' in request.form:
            music_wrapper = get_cached_wrapper_from_scrap(
                type='url', url=request.form['add_url'], user=user)
            var.playlist.append(music_wrapper)

            log.info("web: add to playlist: " +
                     music_wrapper.format_debug_string())
            if len(var.playlist) == 2:
                # If I am the second item on the playlist. (I am the next one!)
                var.bot.async_download_next()

        elif 'add_radio' in request.form:
            url = request.form['add_radio']
            music_wrapper = get_cached_wrapper_from_scrap(type='radio',
                                                          url=url,
                                                          user=user)
            var.playlist.append(music_wrapper)

            log.info("cmd: add to playlist: " +
                     music_wrapper.format_debug_string())

        elif 'delete_music' in request.form:
            music_wrapper = var.playlist[int(request.form['delete_music'])]
            log.info("web: delete from playlist: " +
                     music_wrapper.format_debug_string())

            if len(var.playlist) >= int(request.form['delete_music']):
                index = int(request.form['delete_music'])

                if index == var.playlist.current_index:
                    var.playlist.remove(index)

                    if index < len(var.playlist):
                        if not var.bot.is_pause:
                            var.bot.interrupt()
                            var.playlist.current_index -= 1
                            # then the bot will move to next item

                    else:  # if item deleted is the last item of the queue
                        var.playlist.current_index -= 1
                        if not var.bot.is_pause:
                            var.bot.interrupt()
                else:
                    var.playlist.remove(index)

        elif 'play_music' in request.form:
            music_wrapper = var.playlist[int(request.form['play_music'])]
            log.info("web: jump to: " + music_wrapper.format_debug_string())

            if len(var.playlist) >= int(request.form['play_music']):
                var.playlist.point_to(int(request.form['play_music']) - 1)
                if not var.bot.is_pause:
                    var.bot.interrupt()
                else:
                    var.bot.is_pause = False
                time.sleep(0.1)

        elif 'delete_item_from_library' in request.form:
            _id = request.form['delete_item_from_library']
            var.playlist.remove_by_id(_id)
            item = var.cache.get_item_by_id(_id)

            if os.path.isfile(item.uri()):
                log.info("web: delete file " + item.uri())
                os.remove(item.uri())

            var.cache.free_and_delete(_id)
            time.sleep(0.1)

        elif 'add_tag' in request.form:
            music_wrappers = get_cached_wrappers_by_tags(
                [request.form['add_tag']], user)
            for music_wrapper in music_wrappers:
                log.info("cmd: add to playlist: " +
                         music_wrapper.format_debug_string())
            var.playlist.extend(music_wrappers)

        elif 'action' in request.form:
            action = request.form['action']
            if action == "randomize":
                if var.playlist.mode != "random":
                    var.playlist = media.playlist.get_playlist(
                        "random", var.playlist)
                else:
                    var.playlist.randomize()
                var.bot.interrupt()
                var.db.set('playlist', 'playback_mode', "random")
                log.info("web: playback mode changed to random.")
            if action == "one-shot":
                var.playlist = media.playlist.get_playlist(
                    "one-shot", var.playlist)
                var.db.set('playlist', 'playback_mode', "one-shot")
                log.info("web: playback mode changed to one-shot.")
            if action == "repeat":
                var.playlist = media.playlist.get_playlist(
                    "repeat", var.playlist)
                var.db.set('playlist', 'playback_mode', "repeat")
                log.info("web: playback mode changed to repeat.")
            if action == "autoplay":
                var.playlist = media.playlist.get_playlist(
                    "autoplay", var.playlist)
                var.db.set('playlist', 'playback_mode', "autoplay")
                log.info("web: playback mode changed to autoplay.")
            if action == "rescan":
                var.cache.build_dir_cache()
                log.info("web: Local file cache refreshed.")
            elif action == "stop":
                if var.config.getboolean("bot", "clear_when_stop_in_oneshot", fallback=False) \
                        and var.playlist.mode == 'one-shot':
                    var.bot.clear()
                else:
                    var.bot.stop()
            elif action == "pause":
                var.bot.pause()
            elif action == "resume":
                var.bot.resume()
            elif action == "clear":
                var.bot.clear()
            elif action == "volume_up":
                if var.bot.volume_set + 0.03 < 1.0:
                    var.bot.volume_set = var.bot.volume_set + 0.03
                else:
                    var.bot.volume_set = 1.0
                var.db.set('bot', 'volume', str(var.bot.volume_set))
                log.info("web: volume up to %d" % (var.bot.volume_set * 100))
            elif action == "volume_down":
                if var.bot.volume_set - 0.03 > 0:
                    var.bot.volume_set = var.bot.volume_set - 0.03
                else:
                    var.bot.volume_set = 0
                var.db.set('bot', 'volume', str(var.bot.volume_set))
                log.info("web: volume up to %d" % (var.bot.volume_set * 100))

    return status()
Пример #5
0
def post():
    global log

    payload = request.form if request.form else request.json
    if payload:
        log.debug("web: Post request from %s: %s" %
                  (request.remote_addr, str(payload)))

        if 'add_item_at_once' in payload:
            music_wrapper = get_cached_wrapper_by_id(
                payload['add_item_at_once'], user)
            if music_wrapper:
                var.playlist.insert(var.playlist.current_index + 1,
                                    music_wrapper)
                log.info('web: add to playlist(next): ' +
                         music_wrapper.format_debug_string())
                if not var.bot.is_pause:
                    var.bot.interrupt()
                else:
                    var.bot.is_pause = False
            else:
                abort(404)

        if 'add_item_bottom' in payload:
            music_wrapper = get_cached_wrapper_by_id(
                payload['add_item_bottom'], user)

            if music_wrapper:
                var.playlist.append(music_wrapper)
                log.info('web: add to playlist(bottom): ' +
                         music_wrapper.format_debug_string())
            else:
                abort(404)

        elif 'add_item_next' in payload:
            music_wrapper = get_cached_wrapper_by_id(payload['add_item_next'],
                                                     user)
            if music_wrapper:
                var.playlist.insert(var.playlist.current_index + 1,
                                    music_wrapper)
                log.info('web: add to playlist(next): ' +
                         music_wrapper.format_debug_string())
            else:
                abort(404)

        elif 'add_url' in payload:
            music_wrapper = get_cached_wrapper_from_scrap(
                type='url', url=payload['add_url'], user=user)
            var.playlist.append(music_wrapper)

            log.info("web: add to playlist: " +
                     music_wrapper.format_debug_string())
            if len(var.playlist) == 2:
                # If I am the second item on the playlist. (I am the next one!)
                var.bot.async_download_next()

        elif 'add_radio' in payload:
            url = payload['add_radio']
            music_wrapper = get_cached_wrapper_from_scrap(type='radio',
                                                          url=url,
                                                          user=user)
            var.playlist.append(music_wrapper)

            log.info("cmd: add to playlist: " +
                     music_wrapper.format_debug_string())

        elif 'delete_music' in payload:
            music_wrapper = var.playlist[int(payload['delete_music'])]
            log.info("web: delete from playlist: " +
                     music_wrapper.format_debug_string())

            if len(var.playlist) >= int(payload['delete_music']):
                index = int(payload['delete_music'])

                if index == var.playlist.current_index:
                    var.playlist.remove(index)

                    if index < len(var.playlist):
                        if not var.bot.is_pause:
                            var.bot.interrupt()
                            var.playlist.current_index -= 1
                            # then the bot will move to next item

                    else:  # if item deleted is the last item of the queue
                        var.playlist.current_index -= 1
                        if not var.bot.is_pause:
                            var.bot.interrupt()
                else:
                    var.playlist.remove(index)

        elif 'play_music' in payload:
            music_wrapper = var.playlist[int(payload['play_music'])]
            log.info("web: jump to: " + music_wrapper.format_debug_string())

            if len(var.playlist) >= int(payload['play_music']):
                var.bot.play(int(payload['play_music']))
                time.sleep(0.1)
        elif 'move_playhead' in payload:
            if float(payload['move_playhead']) < var.playlist.current_item(
            ).item().duration:
                log.info(
                    f"web: move playhead to {float(payload['move_playhead'])} s."
                )
                var.bot.play(var.playlist.current_index,
                             float(payload['move_playhead']))

        elif 'delete_item_from_library' in payload:
            _id = payload['delete_item_from_library']
            var.playlist.remove_by_id(_id)
            item = var.cache.get_item_by_id(_id)

            if os.path.isfile(item.uri()):
                log.info("web: delete file " + item.uri())
                os.remove(item.uri())

            var.cache.free_and_delete(_id)
            time.sleep(0.1)

        elif 'add_tag' in payload:
            music_wrappers = get_cached_wrappers_by_tags([payload['add_tag']],
                                                         user)
            for music_wrapper in music_wrappers:
                log.info("cmd: add to playlist: " +
                         music_wrapper.format_debug_string())
            var.playlist.extend(music_wrappers)

        elif 'action' in payload:
            action = payload['action']
            if action == "randomize":
                if var.playlist.mode != "random":
                    var.playlist = media.playlist.get_playlist(
                        "random", var.playlist)
                else:
                    var.playlist.randomize()
                var.bot.interrupt()
                var.db.set('playlist', 'playback_mode', "random")
                log.info("web: playback mode changed to random.")
            if action == "one-shot":
                var.playlist = media.playlist.get_playlist(
                    "one-shot", var.playlist)
                var.db.set('playlist', 'playback_mode', "one-shot")
                log.info("web: playback mode changed to one-shot.")
            if action == "repeat":
                var.playlist = media.playlist.get_playlist(
                    "repeat", var.playlist)
                var.db.set('playlist', 'playback_mode', "repeat")
                log.info("web: playback mode changed to repeat.")
            if action == "autoplay":
                var.playlist = media.playlist.get_playlist(
                    "autoplay", var.playlist)
                var.db.set('playlist', 'playback_mode', "autoplay")
                log.info("web: playback mode changed to autoplay.")
            if action == "rescan":
                var.cache.build_dir_cache()
                var.music_db.manage_special_tags()
                log.info("web: Local file cache refreshed.")
            elif action == "stop":
                if var.config.getboolean("bot", "clear_when_stop_in_oneshot", fallback=False) \
                        and var.playlist.mode == 'one-shot':
                    var.bot.clear()
                else:
                    var.bot.stop()
            elif action == "next":
                if not var.bot.is_pause:
                    var.bot.interrupt()
                else:
                    var.playlist.next()
                    var.bot.wait_for_ready = True
            elif action == "pause":
                var.bot.pause()
            elif action == "resume":
                var.bot.resume()
            elif action == "clear":
                var.bot.clear()
            elif action == "volume_up":
                if var.bot.volume_helper.plain_volume_set + 0.03 < 1.0:
                    var.bot.volume_helper.set_volume(
                        var.bot.volume_helper.plain_volume_set + 0.03)
                else:
                    var.bot.volume_helper.set_volume(1.0)
                var.db.set('bot', 'volume',
                           str(var.bot.volume_helper.plain_volume_set))
                log.info("web: volume up to %d" %
                         (var.bot.volume_helper.plain_volume_set * 100))
            elif action == "volume_down":
                if var.bot.volume_helper.plain_volume_set - 0.03 > 0:
                    var.bot.volume_helper.set_volume(
                        var.bot.unconverted_volume - 0.03)
                else:
                    var.bot.volume_helper.set_volume(1.0)
                var.db.set('bot', 'volume',
                           str(var.bot.volume_helper.plain_volume_set))
                log.info("web: volume down to %d" %
                         (var.bot.volume_helper.plain_volume_set * 100))
            elif action == "volume_set_value":
                if 'new_volume' in payload:
                    if float(payload['new_volume']) > 1:
                        var.bot.volume_helper.set_volume(1.0)
                    elif float(payload['new_volume']) < 0:
                        var.bot.volume_helper.set_volume(0)
                    else:
                        # value for new volume is between 0 and 1, round to two decimal digits
                        var.bot.volume_helper.set_volume(
                            round(float(payload['new_volume']), 2))

                    var.db.set('bot', 'volume',
                               str(var.bot.volume_helper.plain_volume_set))
                    log.info("web: volume set to %d" %
                             (var.bot.volume_helper.plain_volume_set * 100))

    return status()