예제 #1
0
파일: controllers.py 프로젝트: zhkrb/BGmi
def cal(force_update=False, save=False):
    logger.debug('cal force_update: {} save: {}'.format(force_update, save))
    weekly_list = website.bangumi_calendar(force_update=force_update,
                                           save=save)
    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
    for day, value in weekly_list.items():
        for index, bangumi in enumerate(value):
            bangumi['cover'] = normalize_path(bangumi['cover'])
            if isinstance(bangumi['subtitle_group'], list):
                subtitle_group = list(
                    map(lambda x: {
                        'name': x['name'],
                        'id': x['id']
                    }, Subtitle.get_subtitle_by_id(bangumi['subtitle_group'])))
            else:
                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 list_():
    result = {}
    weekday_order = Bangumi.week
    followed_bangumi = website.followed_bangumi()

    script_bangumi = ScriptRunner().get_models_dict()

    if not followed_bangumi and not script_bangumi:
        result["status"] = "warning"
        result["message"] = "you have not subscribed any bangumi"
        return result

    for i in script_bangumi:
        i["subtitle_group"] = [{"name": "<BGmi Script>"}]
        followed_bangumi[i["update_time"].lower()].append(i)

    result["status"] = "info"
    result["message"] = ""
    for index, weekday in enumerate(weekday_order):
        if followed_bangumi[weekday.lower()]:
            result["message"] += "{}{}. {}".format(GREEN, weekday, COLOR_END)
            for i, bangumi in enumerate(followed_bangumi[weekday.lower()]):
                if (bangumi["status"] in (STATUS_UPDATED, STATUS_FOLLOWED)
                        and "episode" in bangumi):
                    bangumi["name"] = "%s(%d)" % (bangumi["name"],
                                                  bangumi["episode"])
                if i > 0:
                    result["message"] += " " * 5
                f = map(lambda x: x["name"], bangumi["subtitle_group"])
                result["message"] += "{}: {}\n".format(
                    bangumi["name"], ", ".join(f) if f else "<None>")

    return result
예제 #3
0
파일: controllers.py 프로젝트: Trim21/BGmi
def list_() -> ControllerResult:
    result = {}
    weekday_order = BANGUMI_UPDATE_TIME
    followed_bangumi = website.followed_bangumi()

    script_bangumi = ScriptRunner().get_models_dict()

    if not followed_bangumi and not script_bangumi:
        result["status"] = "warning"
        result["message"] = "you have not subscribed any bangumi"
        return result

    for i in script_bangumi:
        i["subtitle_group"] = [{"name": "<BGmi Script>"}]
        followed_bangumi[i["update_time"].lower()].append(i)

    result["status"] = "info"
    result["message"] = ""
    for weekday in weekday_order:
        if followed_bangumi[weekday.lower()]:
            result["message"] += f"{GREEN}{weekday}. {COLOR_END}"
            for j, bangumi in enumerate(followed_bangumi[weekday.lower()]):
                if (bangumi["status"] in (STATUS_UPDATED, STATUS_FOLLOWED)
                        and "episode" in bangumi):
                    bangumi[
                        "name"] = f"{bangumi['name']}({bangumi['episode']:d})"
                if j > 0:
                    result["message"] += " " * 5
                f = [x["name"] for x in bangumi["subtitle_group"]]
                result["message"] += "{}: {}\n".format(
                    bangumi["name"], ", ".join(f) if f else "<None>")

    return result
예제 #4
0
파일: controllers.py 프로젝트: zhkrb/BGmi
def mark(name, episode):
    """

    :param name: name of the bangumi you want to mark
    :type name: str
    :param episode: bangumi episode you want to mark
    :type episode: int
    :return: result
    :rtype: dict[status: str,message: str]
    """
    result = {}
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        runner = ScriptRunner()
        followed_obj = runner.get_model(name)
        if not followed_obj:
            result['status'] = 'error'
            result[
                'message'] = 'Subscribe or Script <{}> does not exist.'.format(
                    name)
            return result

    if episode is not None:
        followed_obj.episode = episode
        followed_obj.save()
        result['status'] = 'success'
        result['message'] = '{} has been mark as episode: {}'.format(
            name, episode)
    else:  # episode is None
        result['status'] = 'info'
        result['message'] = '{}, episode: {}'.format(name,
                                                     followed_obj.episode)
    return result
예제 #5
0
파일: controllers.py 프로젝트: Trim21/BGmi
def mark(name: str, episode: int) -> ControllerResult:
    """

    :param name: name of the bangumi you want to mark
    :param episode: bangumi episode you want to mark
    """
    result = {}
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        runner = ScriptRunner()
        followed_obj = runner.get_model(name)  # type: ignore
        if not followed_obj:
            result["status"] = "error"
            result["message"] = f"Subscribe or Script <{name}> does not exist."
            return result

    if episode is not None:
        followed_obj.episode = episode
        followed_obj.save()
        result["status"] = "success"
        result["message"] = f"{name} has been mark as episode: {episode}"
    else:  # episode is None
        result["status"] = "info"
        result["message"] = f"{name}, episode: {followed_obj.episode}"
    return result
예제 #6
0
파일: controllers.py 프로젝트: zhkrb/BGmi
def list_():
    result = {}
    weekday_order = Bangumi.week
    followed_bangumi = website.followed_bangumi()

    script_bangumi = ScriptRunner().get_models_dict()

    if not followed_bangumi and not script_bangumi:
        result['status'] = 'warning'
        result['message'] = 'you have not subscribed any bangumi'
        return result

    for i in script_bangumi:
        i['subtitle_group'] = [{'name': '<BGmi Script>'}]
        followed_bangumi[i['update_time'].lower()].append(i)

    result['status'] = 'info'
    result['message'] = ''
    for index, weekday in enumerate(weekday_order):
        if followed_bangumi[weekday.lower()]:
            result['message'] += '%s%s. %s' % (GREEN, weekday, COLOR_END)
            for i, bangumi in enumerate(followed_bangumi[weekday.lower()]):
                if bangumi['status'] in (STATUS_UPDATED, STATUS_FOLLOWED
                                         ) and 'episode' in bangumi:
                    bangumi['name'] = '%s(%d)' % (bangumi['name'],
                                                  bangumi['episode'])
                if i > 0:
                    result['message'] += ' ' * 5
                f = map(lambda x: x['name'], bangumi['subtitle_group'])
                result['message'] += '%s: %s\n' % (
                    bangumi['name'], ', '.join(f) if f else '<None>')

    return result
예제 #7
0
파일: base.py 프로젝트: luoxiai/BGmi
    def __init__(self, *args, **kwargs):
        if self.patch_list is None:
            runner = ScriptRunner()
            self.patch_list = runner.get_models_dict()
            for i in self.patch_list:
                i['cover'] = normalize_path(i['cover'])

        super(BaseHandler, self).__init__(*args, **kwargs)
예제 #8
0
파일: controllers.py 프로젝트: Trim21/BGmi
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
예제 #9
0
파일: base.py 프로젝트: scjtqs/BGmi
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        if self.latest_version is None:
            if os.path.exists(os.path.join(BGMI_PATH, "latest")):
                with open(os.path.join(BGMI_PATH, "latest")) as f:
                    self.latest_version = f.read().strip()

        runner = ScriptRunner()
        self.patch_list = runner.get_models_dict()
        for i in self.patch_list:
            i["cover"] = normalize_path(i["cover"])

        super().__init__(*args, **kwargs)
예제 #10
0
파일: base.py 프로젝트: rayyouxinsheng/BGmi
    def __init__(self, *args, **kwargs):
        if self.latest_version is None:
            if os.path.exists(os.path.join(BGMI_PATH, 'latest')):
                with open(os.path.join(BGMI_PATH, 'latest')) as f:
                    self.latest_version = f.read().strip()

        if self.patch_list is None:
            runner = ScriptRunner()
            self.patch_list = runner.get_models_dict()
            for i in self.patch_list:
                i['cover'] = normalize_path(i['cover'])

        super(BaseHandler, self).__init__(*args, **kwargs)
예제 #11
0
def getBangumiList():
	
	# subscribe list
	data = Followed.get_all_followed(STATUS_DELETED, STATUS_UPDATING)

	# bgmi-scripts list
	runner = ScriptRunner()
	patch_list = runner.get_models_dict()
	for i in patch_list:
		i['cover'] = normalize_path(i['cover'])

	data.extend(patch_list)
	return data
예제 #12
0
    def bangumi_calendar(self, force_update=False, save=True, cover=False):
        if force_update and not test_connection():
            force_update = False
            print_warning('network is unreachable')

        if force_update:
            print_info('fetching bangumi info ...')
            Bangumi.delete_all()
            weekly_list = self.fetch(save=save)
        else:
            weekly_list = Bangumi.get_all_bangumi()
        if not weekly_list:
            print_warning('warning: no bangumi schedule, fetching ...')
            weekly_list = self.fetch(save=save)

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

        if cover:
            # download cover to local
            cover_to_be_download = []
            for daily_bangumi in weekly_list.values():
                for bangumi in daily_bangumi:
                    followed_obj = Followed(bangumi_name=bangumi['name'])
                    if followed_obj:
                        bangumi['status'] = followed_obj.status
                    _, file_path, _ = self.convert_cover_to_path(
                        bangumi['cover'])

                    if not glob.glob(file_path):
                        cover_to_be_download.append(bangumi['cover'])

            if cover_to_be_download:
                print_info('updating cover')
                for cover in tqdm.tqdm(cover_to_be_download):
                    self.download_cover(cover)

        return weekly_list
예제 #13
0
def cal(force_update=False, save=False):
    logger.debug("cal force_update: {} save: {}".format(force_update, save))
    weekly_list = website.bangumi_calendar(force_update=force_update,
                                           save=save)
    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
    for day, value in weekly_list.items():
        for index, bangumi in enumerate(value):
            bangumi["cover"] = normalize_path(bangumi["cover"])
            if isinstance(bangumi["subtitle_group"], list):
                subtitle_group = list(
                    map(
                        lambda x: {
                            "name": x["name"],
                            "id": x["id"]
                        },
                        Subtitle.get_subtitle_by_id(bangumi["subtitle_group"]),
                    ))
            else:
                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
예제 #14
0
파일: controllers.py 프로젝트: zhkrb/BGmi
def update(name, download=None, not_ignore=False):
    logger.debug(
        'updating bangumi info with args: download: {}'.format(download))
    result = {
        'status': 'info',
        'message': '',
        'data': {
            'updated': [],
            'downloaded': []
        }
    }

    ignore = not bool(not_ignore)
    print_info('marking bangumi status ...')
    now = int(time.time())

    for i in Followed.get_all_followed():
        if i['updated_time'] and int(i['updated_time'] + 60 * 60 * 24) < now:
            followed_obj = Followed.get(bangumi_name=i['bangumi_name'])
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    for script in ScriptRunner().scripts:
        obj = script.Model().obj
        if obj.updated_time and int(obj.updated_time + 60 * 60 * 24) < now:
            obj.status = STATUS_FOLLOWED
            obj.save()

    print_info('updating bangumi data ...')
    website.fetch(save=True, group_by_weekday=False)
    print_info('updating subscriptions ...')
    download_queue = []

    if download:
        if not name:
            print_warning('No specified bangumi, ignore `--download` option')
        if len(name) > 1:
            print_warning(
                'Multiple specified bangumi, ignore `--download` option')

    if not name:
        updated_bangumi_obj = Followed.get_all_followed()
    else:
        updated_bangumi_obj = []
        for i in name:
            try:
                f = Followed.get(bangumi_name=i)
                f = model_to_dict(f)
                updated_bangumi_obj.append(f)
            except DoesNotExist:
                pass

    runner = ScriptRunner()
    script_download_queue = runner.run()

    for subscribe in updated_bangumi_obj:
        print_info('fetching %s ...' % subscribe['bangumi_name'])
        try:
            bangumi_obj = Bangumi.get(name=subscribe['bangumi_name'])
        except Bangumi.DoesNotExist:
            print_error('Bangumi<{0}> does not exists.'.format(
                subscribe['bangumi_name']),
                        exit_=False)
            continue
        try:
            followed_obj = Followed.get(bangumi_name=subscribe['bangumi_name'])
        except Followed.DoesNotExist:
            print_error('Bangumi<{0}> is not followed.'.format(
                subscribe['bangumi_name']),
                        exit_=False)
            continue

        episode, all_episode_data = website.get_maximum_episode(
            bangumi=bangumi_obj, ignore_old_row=ignore, max_page=1)

        if (episode.get('episode') > subscribe['episode']) or (len(name) == 1
                                                               and download):
            if len(name) == 1 and download:
                episode_range = download
            else:
                episode_range = range(subscribe['episode'] + 1,
                                      episode.get('episode', 0) + 1)
                print_success('%s updated, episode: %d' %
                              (subscribe['bangumi_name'], episode['episode']))
                followed_obj.episode = episode['episode']
                followed_obj.status = STATUS_UPDATED
                followed_obj.updated_time = int(time.time())
                followed_obj.save()
                result['data']['updated'].append({
                    'bangumi':
                    subscribe['bangumi_name'],
                    'episode':
                    episode['episode']
                })

            for i in episode_range:
                for epi in all_episode_data:
                    if epi['episode'] == i:
                        download_queue.append(epi)
                        break

    if download is not None:
        result['data']['downloaded'] = download_queue
        download_prepare(download_queue)
        download_prepare(script_download_queue)
        print_info('Re-downloading ...')
        download_prepare(
            Download.get_all_downloads(status=STATUS_NOT_DOWNLOAD))

    return result
예제 #15
0
파일: controllers.py 프로젝트: Trim21/BGmi
def update(name: List[str],
           download: Any = None,
           not_ignore: bool = False) -> ControllerResult:
    logger.debug("updating bangumi info with args: download: %r", download)
    result: Dict[str, Any] = {
        "status": "info",
        "message": "",
        "data": {
            "updated": [],
            "downloaded": []
        },
    }

    ignore = not bool(not_ignore)
    print_info("marking bangumi status ...")
    now = int(time.time())

    for i in Followed.get_all_followed():
        if i["updated_time"] and int(i["updated_time"] + 60 * 60 * 24) < now:
            followed_obj = Followed.get(bangumi_name=i["bangumi_name"])
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    for script in ScriptRunner().scripts:
        obj = script.Model().obj
        if obj.updated_time and int(obj.updated_time + 60 * 60 * 24) < now:
            obj.status = STATUS_FOLLOWED
            obj.save()

    print_info("updating subscriptions ...")
    download_queue = []

    if download:
        if not name:
            print_warning("No specified bangumi, ignore `--download` option")
        if len(name) > 1:
            print_warning(
                "Multiple specified bangumi, ignore `--download` option")

    if not name:
        updated_bangumi_obj = Followed.get_all_followed()
    else:
        updated_bangumi_obj = []
        for n in name:
            try:
                f = Followed.get(bangumi_name=n)
                f = model_to_dict(f)
                updated_bangumi_obj.append(f)
            except DoesNotExist:
                pass

    runner = ScriptRunner()
    script_download_queue = runner.run()

    for subscribe in updated_bangumi_obj:
        print_info(f"fetching {subscribe['bangumi_name']} ...")
        try:
            bangumi_obj = Bangumi.get(name=subscribe["bangumi_name"])
        except Bangumi.DoesNotExist:
            print_error(
                "Bangumi<{}> does not exists.".format(
                    subscribe["bangumi_name"]),
                exit_=False,
            )
            continue
        try:
            followed_obj = Followed.get(bangumi_name=subscribe["bangumi_name"])
        except Followed.DoesNotExist:
            print_error(
                "Bangumi<{}> is not followed.".format(
                    subscribe["bangumi_name"]),
                exit_=False,
            )
            continue

        try:
            episode, all_episode_data = website.get_maximum_episode(
                bangumi=bangumi_obj,
                ignore_old_row=ignore,
                max_page=int(MAX_PAGE))
        except requests.exceptions.ConnectionError as e:
            print_warning(f"error {e} to fetch {bangumi_obj.name}, skip")
            continue

        if (episode > subscribe["episode"]) or (len(name) == 1 and download):
            if len(name) == 1 and download:
                episode_range = download
            else:
                episode_range = range(subscribe["episode"] + 1, episode + 1)
                print_success(
                    f"{subscribe['bangumi_name']} updated, episode: {episode:d}"
                )
                followed_obj.episode = episode
                followed_obj.status = STATUS_UPDATED
                followed_obj.updated_time = int(time.time())
                followed_obj.save()
                result["data"]["updated"].append({
                    "bangumi":
                    subscribe["bangumi_name"],
                    "episode":
                    episode
                })

            for i in episode_range:
                for epi in all_episode_data:
                    if epi.episode == i:
                        download_queue.append(epi)
                        break

    if download is not None:
        result["data"]["downloaded"] = download_queue
        download_prepare(download_queue)
        download_prepare(script_download_queue)
        print_info("Re-downloading ...")
        download_prepare([
            Episode(
                **{
                    key: value
                    for key, value in x.items() if key not in ["id", "status"]
                })
            for x in Download.get_all_downloads(status=STATUS_NOT_DOWNLOAD)
        ])

    return result
예제 #16
0
def cal_wrapper(ret):
    force_update = ret.force_update
    today = ret.today
    save = not ret.no_save

    runner = ScriptRunner()
    if ret.download_cover:
        cover = runner.get_download_cover()
    else:
        cover = None

    weekly_list = website.bangumi_calendar(force_update=force_update,
                                           save=save,
                                           cover=cover)

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

    def shift(seq, n):
        n %= len(seq)
        return seq[n:] + seq[:n]

    if today:
        weekday_order = (Bangumi.week[datetime.datetime.today().weekday()], )
    else:
        weekday_order = shift(Bangumi.week,
                              datetime.datetime.today().weekday())

    env_columns = 42 if os.environ.get("TRAVIS_CI",
                                       False) else get_terminal_col()

    col = 42

    if env_columns < col:
        print_warning("terminal window is too small.")
        env_columns = col

    row = int(env_columns / col if env_columns / col <= 3 else 3)

    def print_line():
        num = col - 3
        split = "-" * num + "   "
        print(split * row)

    for index, weekday in enumerate(weekday_order):
        if weekly_list[weekday.lower()]:
            print(
                "{}{}. {}".format(
                    GREEN,
                    weekday if not today else
                    "Bangumi Schedule for Today (%s)" % weekday,
                    COLOR_END,
                ),
                end="",
            )
            print()
            print_line()
            for i, bangumi in enumerate(weekly_list[weekday.lower()]):
                if (bangumi["status"] in (STATUS_UPDATED, STATUS_FOLLOWED)
                        and "episode" in bangumi):
                    bangumi["name"] = "%s(%d)" % (bangumi["name"],
                                                  bangumi["episode"])

                half = len(
                    re.findall("[%s]" % string.printable, bangumi["name"]))
                full = len(bangumi["name"]) - half
                space_count = col - 2 - (full * 2 + half)

                for s in SPACIAL_APPEND_CHARS:
                    if s in bangumi["name"]:
                        space_count += bangumi["name"].count(s)

                for s in SPACIAL_REMOVE_CHARS:
                    if s in bangumi["name"]:
                        space_count -= bangumi["name"].count(s)

                if bangumi["status"] == STATUS_FOLLOWED:
                    bangumi["name"] = "{}{}{}".format(YELLOW, bangumi["name"],
                                                      COLOR_END)

                if bangumi["status"] == STATUS_UPDATED:
                    bangumi["name"] = "{}{}{}".format(GREEN, bangumi["name"],
                                                      COLOR_END)
                try:
                    print(" " + bangumi["name"], " " * space_count, end="")
                except UnicodeEncodeError:
                    continue

                if (i + 1) % row == 0 or i + 1 == len(
                        weekly_list[weekday.lower()]):
                    print()
            print()
예제 #17
0
파일: cli.py 프로젝트: canbion/BGmi
def cal_wrapper(ret):
    force_update = ret.force_update
    today = ret.today
    save = not ret.no_save

    runner = ScriptRunner()
    if ret.download_cover:
        cover = runner.get_download_cover()
    else:
        cover = None

    weekly_list = website.bangumi_calendar(force_update=force_update,
                                           save=save,
                                           cover=cover)

    patch_list = runner.get_models_dict()
    for i in patch_list:
        weekly_list[i['update_time'].lower()].append(i)

    def shift(seq, n):
        n %= len(seq)
        return seq[n:] + seq[:n]

    if today:
        weekday_order = (Bangumi.week[datetime.datetime.today().weekday()], )
    else:
        weekday_order = shift(Bangumi.week,
                              datetime.datetime.today().weekday())

    env_columns = 42 if os.environ.get('TRAVIS_CI',
                                       False) else get_terminal_col()

    col = 42

    if env_columns < col:
        print_warning('terminal window is too small.')
        env_columns = col

    row = int(env_columns / col if env_columns / col <= 3 else 3)

    def print_line():
        num = col - 3
        split = '-' * num + '   '
        print(split * row)

    for index, weekday in enumerate(weekday_order):
        if weekly_list[weekday.lower()]:
            print('%s%s. %s' %
                  (GREEN, weekday if not today else
                   'Bangumi Schedule for Today (%s)' % weekday, COLOR_END),
                  end='')
            print()
            print_line()
            for i, bangumi in enumerate(weekly_list[weekday.lower()]):
                if bangumi['status'] in (STATUS_UPDATED, STATUS_FOLLOWED
                                         ) and 'episode' in bangumi:
                    bangumi['name'] = '%s(%d)' % (bangumi['name'],
                                                  bangumi['episode'])

                half = len(
                    re.findall('[%s]' % string.printable, bangumi['name']))
                full = (len(bangumi['name']) - half)
                space_count = col - 2 - (full * 2 + half)

                for s in SPACIAL_APPEND_CHARS:
                    if s in bangumi['name']:
                        space_count += bangumi['name'].count(s)

                for s in SPACIAL_REMOVE_CHARS:
                    if s in bangumi['name']:
                        space_count -= bangumi['name'].count(s)

                if bangumi['status'] == STATUS_FOLLOWED:
                    bangumi['name'] = '%s%s%s' % (YELLOW, bangumi['name'],
                                                  COLOR_END)

                if bangumi['status'] == STATUS_UPDATED:
                    bangumi['name'] = '%s%s%s' % (GREEN, bangumi['name'],
                                                  COLOR_END)
                print(' ' + bangumi['name'], ' ' * space_count, end='')
                if (i + 1) % row == 0 or i + 1 == len(
                        weekly_list[weekday.lower()]):
                    print()
            print()
예제 #18
0
def update(name, download=None, not_ignore=False):
    logger.debug(
        "updating bangumi info with args: download: {}".format(download))
    result = {
        "status": "info",
        "message": "",
        "data": {
            "updated": [],
            "downloaded": []
        },
    }

    ignore = not bool(not_ignore)
    print_info("marking bangumi status ...")
    now = int(time.time())

    for i in Followed.get_all_followed():
        if i["updated_time"] and int(i["updated_time"] + 60 * 60 * 24) < now:
            followed_obj = Followed.get(bangumi_name=i["bangumi_name"])
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

    for script in ScriptRunner().scripts:
        obj = script.Model().obj
        if obj.updated_time and int(obj.updated_time + 60 * 60 * 24) < now:
            obj.status = STATUS_FOLLOWED
            obj.save()

    print_info("updating subscriptions ...")
    download_queue = []

    if download:
        if not name:
            print_warning("No specified bangumi, ignore `--download` option")
        if len(name) > 1:
            print_warning(
                "Multiple specified bangumi, ignore `--download` option")

    if not name:
        updated_bangumi_obj = Followed.get_all_followed()
    else:
        updated_bangumi_obj = []
        for i in name:
            try:
                f = Followed.get(bangumi_name=i)
                f = model_to_dict(f)
                updated_bangumi_obj.append(f)
            except DoesNotExist:
                pass

    runner = ScriptRunner()
    script_download_queue = runner.run()

    for subscribe in updated_bangumi_obj:
        print_info("fetching %s ..." % subscribe["bangumi_name"])
        try:
            bangumi_obj = Bangumi.get(name=subscribe["bangumi_name"])
        except Bangumi.DoesNotExist:
            print_error(
                "Bangumi<{}> does not exists.".format(
                    subscribe["bangumi_name"]),
                exit_=False,
            )
            continue
        try:
            followed_obj = Followed.get(bangumi_name=subscribe["bangumi_name"])
        except Followed.DoesNotExist:
            print_error(
                "Bangumi<{}> is not followed.".format(
                    subscribe["bangumi_name"]),
                exit_=False,
            )
            continue

        episode, all_episode_data = website.get_maximum_episode(
            bangumi=bangumi_obj, ignore_old_row=ignore, max_page=1)

        if (episode.get("episode") > subscribe["episode"]) or (len(name) == 1
                                                               and download):
            if len(name) == 1 and download:
                episode_range = download
            else:
                episode_range = range(subscribe["episode"] + 1,
                                      episode.get("episode", 0) + 1)
                print_success("%s updated, episode: %d" %
                              (subscribe["bangumi_name"], episode["episode"]))
                followed_obj.episode = episode["episode"]
                followed_obj.status = STATUS_UPDATED
                followed_obj.updated_time = int(time.time())
                followed_obj.save()
                result["data"]["updated"].append({
                    "bangumi":
                    subscribe["bangumi_name"],
                    "episode":
                    episode["episode"],
                })

            for i in episode_range:
                for epi in all_episode_data:
                    if epi["episode"] == i:
                        download_queue.append(epi)
                        break

    if download is not None:
        result["data"]["downloaded"] = download_queue
        download_prepare(download_queue)
        download_prepare(script_download_queue)
        print_info("Re-downloading ...")
        download_prepare(
            Download.get_all_downloads(status=STATUS_NOT_DOWNLOAD))

    return result
예제 #19
0
def cal_wrapper(ret: Any) -> None:
    force_update = ret.force_update
    today = ret.today
    save = not ret.no_save

    runner = ScriptRunner()
    cover = None  # type: Optional[List[str]]

    if ret.download_cover:
        cover = runner.get_download_cover()

    weekly_list = cal(force_update=force_update, save=save, cover=cover)

    def shift(seq: Tuple[str, ...], n: int) -> Tuple[str, ...]:
        n %= len(seq)
        return seq[n:] + seq[:n]

    order_without_unknown = BANGUMI_UPDATE_TIME[:-1]
    if today:
        weekday_order = (
            order_without_unknown[datetime.datetime.today().weekday()],
        )  # type: Tuple[str, ...]
    else:
        weekday_order = shift(order_without_unknown,
                              datetime.datetime.today().weekday())

    col = max(
        wcwidth.wcswidth(bangumi["name"]) for value in weekly_list.values()
        for bangumi in value)
    env_columns = col if os.environ.get("TRAVIS_CI",
                                        False) else get_terminal_col()

    if env_columns < col:
        print_warning("terminal window is too small.")
        env_columns = col

    row = int(env_columns / col if env_columns / col <= 3 else 3)

    def print_line() -> None:
        num = col - 3
        split = "-" * num + "   "
        print(split * row)

    for weekday in weekday_order + ("Unknown", ):
        if weekly_list[weekday.lower()]:
            print(
                "{}{}. {}".format(
                    GREEN,
                    weekday if not today else
                    f"Bangumi Schedule for Today ({weekday})",
                    COLOR_END,
                ),
                end="",
            )
            print()
            print_line()
            for i, bangumi in enumerate(weekly_list[weekday.lower()]):
                if (bangumi["status"] in (STATUS_UPDATED, STATUS_FOLLOWED)
                        and "episode" in bangumi):
                    bangumi["name"] = "{}({:d})".format(
                        bangumi["name"], bangumi["episode"])

                width = wcwidth.wcswidth(bangumi["name"])
                space_count = col - 2 - width

                for s in SPACIAL_APPEND_CHARS:
                    if s in bangumi["name"]:
                        space_count += bangumi["name"].count(s)

                for s in SPACIAL_REMOVE_CHARS:
                    if s in bangumi["name"]:
                        space_count -= bangumi["name"].count(s)

                if bangumi["status"] == STATUS_FOLLOWED:
                    bangumi["name"] = "{}{}{}".format(YELLOW, bangumi["name"],
                                                      COLOR_END)

                if bangumi["status"] == STATUS_UPDATED:
                    bangumi["name"] = "{}{}{}".format(GREEN, bangumi["name"],
                                                      COLOR_END)
                try:
                    print(" " + bangumi["name"], " " * space_count, end="")
                except UnicodeEncodeError:
                    continue

                if (i + 1) % row == 0 or i + 1 == len(
                        weekly_list[weekday.lower()]):
                    print()
            print()