Пример #1
0
def cal(force_update: bool = False,
        save: bool = False,
        cover: Optional[List[str]] = None) -> Dict[str, List[Dict[str, Any]]]:
    logger.debug("cal force_update: %r save: %r", force_update, save)

    weekly_list = Bangumi.get_updating_bangumi()
    if not weekly_list:
        print_warning("Warning: no bangumi schedule, fetching ...")
        force_update = True

    if force_update:
        print_info("Fetching bangumi info ...")
        website.fetch(save=save)

    weekly_list = Bangumi.get_updating_bangumi()

    if cover is not None:
        # download cover to local
        cover_to_be_download = cover
        for daily_bangumi in weekly_list.values():
            for bangumi in daily_bangumi:
                _, file_path = convert_cover_url_to_path(bangumi["cover"])

                if not (os.path.exists(file_path)
                        and bool(imghdr.what(file_path))):
                    cover_to_be_download.append(bangumi["cover"])

        if cover_to_be_download:
            print_info("Updating cover ...")
            download_cover(cover_to_be_download)

    runner = ScriptRunner()
    patch_list = runner.get_models_dict()
    for i in patch_list:
        weekly_list[i["update_time"].lower()].append(i)
    logger.debug(weekly_list)

    # for web api, return all subtitle group info
    r = weekly_list  # type: Dict[str, List[Dict[str, Any]]]
    for day, value in weekly_list.items():
        for index, bangumi in enumerate(value):
            bangumi["cover"] = normalize_path(bangumi["cover"])
            subtitle_group = list(
                map(
                    lambda x: {
                        "name": x["name"],
                        "id": x["id"]
                    },
                    Subtitle.get_subtitle_by_id(
                        bangumi["subtitle_group"].split(", "
                                                        "")),
                ))

            r[day][index]["subtitle_group"] = subtitle_group
    logger.debug(r)
    return r
Пример #2
0
def add(name, episode=None):
    """
    ret.name :str
    """
    # action add
    # add bangumi by a list of bangumi name
    # result = {}
    logger.debug('add name: {} episode: {}'.format(name, episode))
    if not Bangumi.get_updating_bangumi():
        website.fetch(save=True, group_by_weekday=False)

    try:
        bangumi_obj = Bangumi.fuzzy_get(name=name)
    except Bangumi.DoesNotExist:
        result = {'status': 'error',
                  'message': '{0} not found, please check the name'.format(name)}
        return result
    followed_obj, this_obj_created = Followed.get_or_create(bangumi_name=bangumi_obj.name,
                                                            defaults={'status': STATUS_FOLLOWED})
    if not this_obj_created:
        if followed_obj.status == STATUS_FOLLOWED:
            result = {'status': 'warning', 'message': '{0} already followed'.format(bangumi_obj.name)}
            return result
        else:
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    Filter.get_or_create(bangumi_name=name)

    bangumi_data, _ = website.get_maximum_episode(bangumi_obj, subtitle=False, max_page=MAX_PAGE)
    followed_obj.episode = bangumi_data['episode'] if episode is None else episode
    followed_obj.save()
    result = {'status': 'success', 'message': '{0} has been followed'.format(bangumi_obj.name)}
    logger.debug(result)
    return result
Пример #3
0
    def followed_bangumi():
        """

        :return: list of bangumi followed
        :rtype: list[dict]
        """
        weekly_list_followed = Bangumi.get_updating_bangumi(status=STATUS_FOLLOWED)
        weekly_list_updated = Bangumi.get_updating_bangumi(status=STATUS_UPDATED)
        weekly_list = defaultdict(list)
        for k, v in chain(weekly_list_followed.items(), weekly_list_updated.items()):
            weekly_list[k].extend(v)
        for bangumi_list in weekly_list.values():
            for bangumi in bangumi_list:
                bangumi['subtitle_group'] = [{'name': x['name'],
                                              'id': x['id']} for x in
                                             Subtitle.get_subtitle_by_id(bangumi['subtitle_group'].split(', '))]
        return weekly_list
Пример #4
0
    def followed_bangumi() -> Dict[str, list]:
        """

        :return: list of bangumi followed
        """
        weekly_list_followed = Bangumi.get_updating_bangumi(status=STATUS_FOLLOWED)
        weekly_list_updated = Bangumi.get_updating_bangumi(status=STATUS_UPDATED)
        weekly_list = defaultdict(list)
        for k, v in chain(weekly_list_followed.items(), weekly_list_updated.items()):
            weekly_list[k].extend(v)
        for bangumi_list in weekly_list.values():
            for bangumi in bangumi_list:
                bangumi["subtitle_group"] = [
                    {"name": x["name"], "id": x["id"]}
                    for x in Subtitle.get_subtitle_by_id(
                        bangumi["subtitle_group"].split(", ")
                    )
                ]
        return weekly_list
Пример #5
0
def complete(ret):
    # coding=utf-8
    """eval "$(bgmi complete)" to complete bgmi in bash"""
    updating_bangumi_names = [
        x["name"] for x in Bangumi.get_updating_bangumi(order=False)
    ]

    all_config = [x for x in bgmi.config.__all__ if not x == "DATA_SOURCE"]

    actions_and_opts = {}
    helper = {}
    for action_dict in actions_and_arguments:
        actions_and_opts[action_dict["action"]] = []
        for arg in action_dict.get("arguments", []):
            if isinstance(arg["dest"], str) and arg["dest"].startswith("-"):
                actions_and_opts[action_dict["action"]].append(arg)
            elif isinstance(arg["dest"], list):
                actions_and_opts[action_dict["action"]].append(arg)
        helper[action_dict["action"]] = action_dict.get("help", "")

    if "bash" in os.getenv("SHELL").lower():  # bash
        template_file_path = os.path.join(os.path.dirname(__file__), "..",
                                          "others", "_bgmi_completion_bash.sh")

    elif "zsh" in os.getenv("SHELL").lower():  # zsh
        template_file_path = os.path.join(os.path.dirname(__file__), "..",
                                          "others", "_bgmi_completion_zsh.sh")

    else:
        import sys

        print("unsupported shell {}".format(os.getenv("SHELL").lower()),
              file=sys.stderr)
        return

    with open(template_file_path) as template_file:
        shell_template = template.Template(template_file.read(), autoescape="")

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        bangumi=updating_bangumi_names,
        config=all_config,
        actions_and_opts=actions_and_opts,
        source=[x["id"] for x in SUPPORT_WEBSITE],
        helper=helper,
        isinstance=isinstance,
        string_types=(str, ),
    )  # type: bytes

    if os.environ.get("DEBUG", False):  # pragma: no cover
        with open("./_bgmi", "wb+") as template_file:
            template_file.write(template_with_content)

    template_with_content = template_with_content.decode("utf-8")
    print(template_with_content)
Пример #6
0
def complete(ret):
    # coding=utf-8
    """eval "$(bgmi complete)" to complete bgmi in bash"""
    updating_bangumi_names = [
        x['name'] for x in Bangumi.get_updating_bangumi(order=False)
    ]

    all_config = [x for x in bgmi.config.__all__ if not x == 'DATA_SOURCE']

    actions_and_opts = {}
    helper = {}
    for action_dict in actions_and_arguments:
        actions_and_opts[action_dict['action']] = []
        for arg in action_dict.get('arguments', []):
            if isinstance(arg['dest'],
                          string_types) and arg['dest'].startswith('-'):
                actions_and_opts[action_dict['action']].append(arg)
            elif isinstance(arg['dest'], list):
                actions_and_opts[action_dict['action']].append(arg)
        helper[action_dict['action']] = action_dict.get('help', '')

    if 'bash' in os.getenv('SHELL').lower():  # bash
        template_file_path = os.path.join(os.path.dirname(__file__), '..',
                                          'others', '_bgmi_completion_bash.sh')

    elif 'zsh' in os.getenv('SHELL').lower():  # zsh
        template_file_path = os.path.join(os.path.dirname(__file__), '..',
                                          'others', '_bgmi_completion_zsh.sh')

    else:
        import sys
        print('unsupported shell {}'.format(os.getenv('SHELL').lower()),
              file=sys.stderr)
        return

    with open(template_file_path, 'r') as template_file:
        shell_template = template.Template(template_file.read(), autoescape='')

    template_with_content = shell_template.generate(
        actions=ACTIONS,
        bangumi=updating_bangumi_names,
        config=all_config,
        actions_and_opts=actions_and_opts,
        source=[x['id'] for x in SUPPORT_WEBSITE],
        helper=helper,
        isinstance=isinstance,
        string_types=string_types)  # type: bytes

    if os.environ.get('DEBUG', False):  # pragma: no cover
        with open('./_bgmi', 'wb+') as template_file:
            template_file.write(template_with_content)

    template_with_content = template_with_content.decode('utf-8')
    print(template_with_content)
Пример #7
0
def history(ret):
    m = (
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    )
    data = Followed.select(Followed).order_by(Followed.updated_time.asc())
    bangumi_data = Bangumi.get_updating_bangumi()
    year = None
    month = None

    updating_bangumi = list(
        map(lambda s: s["name"], itertools.chain(*bangumi_data.values())))

    print_info("Bangumi Timeline")
    for i in data:
        if i.status == STATUS_DELETED:
            slogan = "ABANDON"
            color = RED
        else:
            if i.bangumi_name in updating_bangumi:
                slogan = "FOLLOWING"
                color = YELLOW
            else:
                slogan = "FINISHED"
                color = GREEN

        if not i.updated_time:
            date = datetime.datetime.fromtimestamp(0)
        else:
            date = datetime.datetime.fromtimestamp(int(i.updated_time))

        if date.year != 1970:
            if date.year != year:
                print("{}{}{}".format(GREEN, str(date.year), COLOR_END))
                year = date.year

            if date.year == year and date.month != month:
                print("  |\n  |--- {}{}{}\n  |      |".format(
                    YELLOW, m[date.month - 1], COLOR_END))
                month = date.month

            print("  |      |--- [{}{:<9}{}] ({:<2}) {}".format(
                color, slogan, COLOR_END, i.episode, i.bangumi_name))
Пример #8
0
def add(name, episode=None):
    """
    ret.name :str
    """
    # action add
    # add bangumi by a list of bangumi name
    # result = {}
    logger.debug('add name: {} episode: {}'.format(name, episode))
    if not Bangumi.get_updating_bangumi():
        website.fetch(save=True, group_by_weekday=False)

    try:
        bangumi_obj = Bangumi.get(name=name)
    except Bangumi.DoesNotExist:
        result = {
            'status': 'error',
            'message': '{0} not found, please check the name'.format(name)
        }
        return result

    followed_obj, this_obj_created = Followed.get_or_create(
        bangumi_name=bangumi_obj.name, defaults={'status': STATUS_FOLLOWED})
    if not this_obj_created:
        if followed_obj.status == STATUS_FOLLOWED:
            result = {
                'status': 'warning',
                'message': '{0} already followed'.format(bangumi_obj.name)
            }
            return result
        else:
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    Filter.get_or_create(bangumi_name=name)

    bangumi_data, _ = website.get_maximum_episode(bangumi_obj,
                                                  subtitle=False,
                                                  max_page=MAX_PAGE)
    followed_obj.episode = bangumi_data[
        'episode'] if episode is None else episode
    followed_obj.save()
    result = {
        'status': 'success',
        'message': '{0} has been followed'.format(bangumi_obj.name)
    }
    logger.debug(result)
    return result
Пример #9
0
def complete(ret):
    # coding=utf-8
    """eval "$(bgmi complete)" to complete bgmi in bash"""
    updating_bangumi_names = [x['name'] for x in Bangumi.get_updating_bangumi(order=False)]

    all_config = [x for x in bgmi.config.__all__ if not x == 'DATA_SOURCE']

    actions_and_opts = {}
    helper = {}
    for action_dict in actions_and_arguments:
        actions_and_opts[action_dict['action']] = []
        for arg in action_dict.get('arguments', []):
            if isinstance(arg['dest'], string_types) and arg['dest'].startswith('-'):
                actions_and_opts[action_dict['action']].append(arg)
            elif isinstance(arg['dest'], list):
                actions_and_opts[action_dict['action']].append(arg)
        helper[action_dict['action']] = action_dict.get('help', '')

    if 'bash' in os.getenv('SHELL').lower():  # bash
        template_file_path = os.path.join(os.path.dirname(__file__), '..', 'others', '_bgmi_completion_bash.sh')

    elif 'zsh' in os.getenv('SHELL').lower():  # zsh
        template_file_path = os.path.join(os.path.dirname(__file__), '..', 'others', '_bgmi_completion_zsh.sh')

    else:
        import sys
        print('unsupported shell {}'.format(os.getenv('SHELL').lower()), file=sys.stderr)
        return

    with open(template_file_path, 'r') as template_file:
        shell_template = template.Template(template_file.read(), autoescape='')

    template_with_content = shell_template.generate(actions=ACTIONS,
                                                    bangumi=updating_bangumi_names, config=all_config,
                                                    actions_and_opts=actions_and_opts,
                                                    source=[x['id'] for x in SUPPORT_WEBSITE],
                                                    helper=helper,
                                                    isinstance=isinstance,
                                                    string_types=string_types)  # type: bytes

    if os.environ.get('DEBUG', False):  # pragma: no cover
        with open('./_bgmi', 'wb+') as template_file:
            template_file.write(template_with_content)

    template_with_content = template_with_content.decode('utf-8')
    print(template_with_content)
Пример #10
0
def add(name: str, episode: int = None) -> ControllerResult:
    """
    ret.name :str
    """
    # action add
    # add bangumi by a list of bangumi name
    logger.debug("add name: %s episode: %d", name, episode)
    if not Bangumi.get_updating_bangumi():
        website.fetch(save=True, group_by_weekday=False)

    try:
        bangumi_obj = Bangumi.fuzzy_get(name=name)
    except Bangumi.DoesNotExist:
        result = {
            "status": "error",
            "message": f"{name} not found, please check the name",
        }
        return result
    followed_obj, this_obj_created = Followed.get_or_create(
        bangumi_name=bangumi_obj.name, defaults={"status": STATUS_FOLLOWED})
    if not this_obj_created:
        if followed_obj.status == STATUS_FOLLOWED:
            result = {
                "status": "warning",
                "message": f"{bangumi_obj.name} already followed",
            }
            return result
        else:
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    Filter.get_or_create(bangumi_name=name)

    max_episode, _ = website.get_maximum_episode(bangumi_obj,
                                                 max_page=int(MAX_PAGE))
    followed_obj.episode = max_episode if episode is None else episode

    followed_obj.save()
    result = {
        "status": "success",
        "message": f"{bangumi_obj.name} has been followed",
    }
    logger.debug(result)
    return result
Пример #11
0
def history(ret):
    m = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
         'August', 'September', 'October', 'November', 'December')
    data = Followed.select(Followed).order_by(Followed.updated_time.asc())
    bangumi_data = Bangumi.get_updating_bangumi()
    year = None
    month = None

    updating_bangumi = list(
        map(lambda s: s['name'], itertools.chain(*bangumi_data.values())))

    print_info('Bangumi Timeline')
    for i in data:
        if i.status == STATUS_DELETED:
            slogan = 'ABANDON'
            color = RED
        else:
            if i.bangumi_name in updating_bangumi:
                slogan = 'FOLLOWING'
                color = YELLOW
            else:
                slogan = 'FINISHED'
                color = GREEN

        if not i.updated_time:
            date = datetime.datetime.fromtimestamp(0)
        else:
            date = datetime.datetime.fromtimestamp(int(i.updated_time))

        if date.year != 1970:
            if date.year != year:
                print('%s%s%s' % (GREEN, str(date.year), COLOR_END))
                year = date.year

            if date.year == year and date.month != month:
                print('  |\n  |--- %s%s%s\n  |      |' %
                      (YELLOW, m[date.month - 1], COLOR_END))
                month = date.month

            print('  |      |--- [%s%-9s%s] (%-2s) %s' %
                  (color, slogan, COLOR_END, i.episode, i.bangumi_name))
Пример #12
0
    def bangumi_calendar(self, force_update=False, save=True, cover=None):
        """

        :param force_update:
        :type force_update: bool

        :param save: set true to enable save bangumi data to database
        :type save: bool

        :param cover: list of cover url (of scripts) want to download
        :type cover: list[str]
        """
        if force_update and not test_connection():
            force_update = False
            print_warning('Network is unreachable')

        if force_update:
            print_info('Fetching bangumi info ...')
            weekly_list = self.fetch(save=save)
        else:
            weekly_list = Bangumi.get_updating_bangumi()

        if not weekly_list:
            print_warning('Warning: no bangumi schedule, fetching ...')
            weekly_list = self.fetch(save=save)

        if cover is not None:
            # download cover to local
            cover_to_be_download = cover
            for daily_bangumi in weekly_list.values():
                for bangumi in daily_bangumi:
                    _, file_path = convert_cover_url_to_path(bangumi['cover'])

                    if not (os.path.exists(file_path) and imghdr.what(file_path)):
                        cover_to_be_download.append(bangumi['cover'])

            if cover_to_be_download:
                print_info('Updating cover ...')
                download_cover(cover_to_be_download)

        return weekly_list
Пример #13
0
def history(ret):
    m = ('January', 'February', 'March', 'April', 'May', 'June', 'July',
         'August', 'September', 'October', 'November', 'December')
    data = Followed.select(Followed).order_by(Followed.updated_time.asc())
    bangumi_data = Bangumi.get_updating_bangumi()
    year = None
    month = None

    updating_bangumi = list(map(lambda s: s['name'], itertools.chain(*bangumi_data.values())))

    print_info('Bangumi Timeline')
    for i in data:
        if i.status == STATUS_DELETED:
            slogan = 'ABANDON'
            color = RED
        else:
            if i.bangumi_name in updating_bangumi:
                slogan = 'FOLLOWING'
                color = YELLOW
            else:
                slogan = 'FINISHED'
                color = GREEN

        if not i.updated_time:
            date = datetime.datetime.fromtimestamp(0)
        else:
            date = datetime.datetime.fromtimestamp(int(i.updated_time))

        if date.year != 1970:
            if date.year != year:
                print('%s%s%s' % (GREEN, str(date.year), COLOR_END))
                year = date.year

            if date.year == year and date.month != month:
                print('  |\n  |--- %s%s%s\n  |      |' % (YELLOW, m[date.month - 1], COLOR_END))
                month = date.month

            print('  |      |--- [%s%-9s%s] (%-2s) %s' % (color, slogan, COLOR_END, i.episode, i.bangumi_name))