Beispiel #1
0
def delete(name='', clear_all=False, batch=False):
    """
    :param name:
    :type name: unicode
    :param clear_all:
    :type clear_all: bool
    :param batch:
    :type batch: bool
    :return:
    """
    # action delete
    # just delete subscribed bangumi or clear all the subscribed bangumi
    result = {}
    logger.debug('delete {}'.format(name))
    if clear_all:
        if Followed.delete_followed(batch=batch):
            result['status'] = "warning"
            result['message'] = 'all subscriptions have been deleted'
        else:
            print_error('user canceled')
    elif name:
        try:
            followed = Followed.get(bangumi_name=name)
            followed.status = STATUS_DELETED
            followed.save()
            result['status'] = 'warning'
            result['message'] = 'Bangumi {} has been deleted'.format(name)
        except Followed.DoesNotExist:
            result['status'] = 'error'
            result['message'] = 'Bangumi %s does not exist' % name
    else:
        result['status'] = 'warning'
        result['message'] = 'Nothing has been done.'
    logger.debug(result)
    return result
Beispiel #2
0
def delete(name='', clear_all=False, batch=False):
    """
    :param name:
    :type name: unicode
    :param clear_all:
    :type clear_all: bool
    :param batch:
    :type batch: bool
    :return:
    """
    # action delete
    # just delete subscribed bangumi or clear all the subscribed bangumi
    result = {}
    logger.debug('delete {}'.format(name))
    if clear_all:
        if Followed.delete_followed(batch=batch):
            result['status'] = "warning"
            result['message'] = 'all subscriptions have been deleted'
        else:
            print_error('user canceled')
    elif name:
        try:
            followed = Followed.get(bangumi_name=name)
            followed.status = STATUS_DELETED
            followed.save()
            result['status'] = 'warning'
            result['message'] = 'Bangumi {} has been deleted'.format(name)
        except Followed.DoesNotExist:
            result['status'] = 'error'
            result['message'] = 'Bangumi %s does not exist' % name
    else:
        result['status'] = 'warning'
        result['message'] = 'Nothing has been done.'
    logger.debug(result)
    return result
Beispiel #3
0
def delete(name="", clear_all=False, batch=False):
    """
    :param name:
    :type name: unicode
    :param clear_all:
    :type clear_all: bool
    :param batch:
    :type batch: bool
    :return:
    """
    # action delete
    # just delete subscribed bangumi or clear all the subscribed bangumi
    result = {}
    logger.debug("delete {}".format(name))
    if clear_all:
        if Followed.delete_followed(batch=batch):
            result["status"] = "warning"
            result["message"] = "all subscriptions have been deleted"
        else:
            print_error("user canceled")
    elif name:
        try:
            followed = Followed.get(bangumi_name=name)
            followed.status = STATUS_DELETED
            followed.save()
            result["status"] = "warning"
            result["message"] = "Bangumi {} has been deleted".format(name)
        except Followed.DoesNotExist:
            result["status"] = "error"
            result["message"] = "Bangumi %s does not exist" % name
    else:
        result["status"] = "warning"
        result["message"] = "Nothing has been done."
    logger.debug(result)
    return result
Beispiel #4
0
def delete(name: str = "",
           clear_all: bool = False,
           batch: bool = False) -> ControllerResult:
    """
    :param name:
    :param clear_all:
    :param batch:
    """
    # action delete
    # just delete subscribed bangumi or clear all the subscribed bangumi
    result = {}
    logger.debug("delete %s", name)
    if clear_all:
        if Followed.delete_followed(batch=batch):
            result["status"] = "warning"
            result["message"] = "all subscriptions have been deleted"
        else:
            print_error("user canceled")
    elif name:
        try:
            followed = Followed.get(bangumi_name=name)
            followed.status = STATUS_DELETED
            followed.save()
            result["status"] = "warning"
            result["message"] = f"Bangumi {name} has been deleted"
        except Followed.DoesNotExist:
            result["status"] = "error"
            result["message"] = f"Bangumi {name} does not exist"
    else:
        result["status"] = "warning"
        result["message"] = "Nothing has been done."
    logger.debug(result)
    return result
Beispiel #5
0
def filter_(name, subtitle=None, include=None, exclude=None, regex=None):
    result = {'status': 'success', 'message': ''}
    try:
        bangumi_obj = Bangumi.fuzzy_get(name=name)
    except Bangumi.DoesNotExist:
        result['status'] = 'error'
        result['message'] = 'Bangumi {0} does not exist.'.format(name)
        return result

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist as exc:
        result['status'] = 'error'
        result['message'] = 'Bangumi {name} has not subscribed, try \'bgmi add "{name}"\'.' \
            .format(name=bangumi_obj.name)
        return result

    followed_filter_obj, is_this_obj_created = Filter.get_or_create(bangumi_name=name)

    if is_this_obj_created:
        followed_filter_obj.save()

    if subtitle is not None:
        subtitle = [s.strip() for s in subtitle.split(',')]
        subtitle = [s['id'] for s in Subtitle.get_subtitle_by_name(subtitle)]
        subtitle_list = [s.split('.')[0] for s in bangumi_obj.subtitle_group.split(', ') if '.' in s]
        subtitle_list.extend(bangumi_obj.subtitle_group.split(', '))
        subtitle = filter(lambda s: s in subtitle_list, subtitle)
        subtitle = ', '.join(subtitle)
        followed_filter_obj.subtitle = subtitle

    if include is not None:
        followed_filter_obj.include = include

    if exclude is not None:
        followed_filter_obj.exclude = exclude

    if regex is not None:
        followed_filter_obj.regex = regex

    followed_filter_obj.save()
    subtitle_list = list(map(lambda s: s['name'],
                             Subtitle.get_subtitle_by_id(bangumi_obj.subtitle_group.split(', '))))

    result['data'] = {
        'name': name,
        'subtitle_group': subtitle_list,
        'followed': list(map(lambda s: s['name'], Subtitle.get_subtitle_by_id(followed_filter_obj.subtitle.split(', ')))
                         if followed_filter_obj.subtitle else []),
        'include': followed_filter_obj.include,
        'exclude': followed_filter_obj.exclude,
        'regex': followed_filter_obj.regex,
    }
    logger.debug(result)
    return result
Beispiel #6
0
def test_update_download(mock_download_driver: mock.Mock):
    """TODO: mock HTTP requests in this test"""
    name = "hello world"
    mock_website = mock.Mock()
    mock_website.get_maximum_episode = mock.Mock(
        return_value=(
            4,
            [
                Episode(episode=3, download="magnet:mm", title="t 720p", name=name),
                Episode(episode=4, download="magnet:4", title="t 1080p", name=name),
            ],
        )
    )

    Bangumi(name=name, subtitle_group="", keyword=name, cover="").save()
    Followed(bangumi_name=name, episode=2).save()

    with mock.patch("bgmi.lib.controllers.website", mock_website):
        update([], download=True, not_ignore=False)

    mock_download_driver.add_download.assert_has_calls(
        [
            mock.call(url="magnet:mm", save_path=os.path.join(SAVE_PATH, name, "3")),
            mock.call(url="magnet:4", save_path=os.path.join(SAVE_PATH, name, "4")),
        ]
    )
Beispiel #7
0
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
Beispiel #8
0
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
Beispiel #9
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
Beispiel #10
0
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
Beispiel #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())
    year = None
    month = None

    print_info('Bangumi Timeline')
    for i in data:
        if i.status == STATUS_DELETED:
            slogan = ' ABANDON'
            color = RED
        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%s%s] %s' %
                  (color, slogan, COLOR_END, i.bangumi_name))
Beispiel #12
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))
Beispiel #13
0
    def get(self):
        type_ = self.get_argument("type", 0)

        cal = Calendar()
        cal.add("prodid",
                "-//BGmi Followed Bangumi Calendar//bangumi.ricterz.me//")
        cal.add("version", "2.0")

        data = Followed.get_all_followed()
        data.extend(self.patch_list)

        if type_ == 0:

            bangumi = defaultdict(list)
            [
                bangumi[Bangumi.week.index(i["update_time"]) + 1].append(
                    i["bangumi_name"]) for i in data
            ]

            weekday = datetime.datetime.now().weekday()
            for i, k in enumerate(range(weekday, weekday + 7)):
                if k % 7 in bangumi:
                    for v in bangumi[k % 7]:
                        event = Event()
                        event.add("summary", v)
                        event.add(
                            "dtstart",
                            datetime.datetime.now().date() +
                            datetime.timedelta(i - 1),
                        )
                        event.add(
                            "dtend",
                            datetime.datetime.now().date() +
                            datetime.timedelta(i - 1),
                        )
                        cal.add_component(event)
        else:
            data = [bangumi for bangumi in data if bangumi["status"] == 2]
            for bangumi in data:
                event = Event()
                event.add("summary",
                          "Updated: {}".format(bangumi["bangumi_name"]))
                event.add("dtstart", datetime.datetime.now().date())
                event.add("dtend", datetime.datetime.now().date())
                cal.add_component(event)

        cal.add("name", "Bangumi Calendar")
        cal.add("X-WR-CALNAM", "Bangumi Calendar")
        cal.add("description", "Followed Bangumi Calendar")
        cal.add("X-WR-CALDESC", "Followed Bangumi Calendar")

        self.write(cal.to_ical())
        self.finish()
Beispiel #14
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
Beispiel #15
0
def fetch_(ret):
    try:
        bangumi_obj = Bangumi.get(name=ret.name)
    except Bangumi.DoesNotExist:
        print_error('Bangumi {0} not exist'.format(ret.name))
        return

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist:
        print_error('Bangumi {0} is not followed'.format(ret.name))
        return

    followed_filter_obj = Filter.get(bangumi_name=ret.name)
    print_filter(followed_filter_obj)

    print_info('Fetch bangumi {0} ...'.format(bangumi_obj.name))
    _, data = website.get_maximum_episode(bangumi_obj, ignore_old_row=False if ret.not_ignore else True)

    if not data:
        print_warning('Nothing.')
    for i in data:
        print_success(i['title'])
Beispiel #16
0
def fetch_(ret):
    try:
        bangumi_obj = Bangumi.get(name=ret.name)
    except Bangumi.DoesNotExist:
        print_error('Bangumi {0} not exist'.format(ret.name))
        return

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist:
        print_error('Bangumi {0} is not followed'.format(ret.name))
        return

    followed_filter_obj = Filter.get(bangumi_name=ret.name)
    print_filter(followed_filter_obj)

    print_info('Fetch bangumi {0} ...'.format(bangumi_obj.name))
    _, data = website.get_maximum_episode(
        bangumi_obj, ignore_old_row=False if ret.not_ignore else True)

    if not data:
        print_warning('Nothing.')
    for i in data:
        print_success(i['title'])
Beispiel #17
0
def fetch_(ret: Any) -> None:
    try:
        bangumi_obj = Bangumi.get(name=ret.name)
    except Bangumi.DoesNotExist:
        print_error(f"Bangumi {ret.name} not exist")
        return

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist:
        print_error(f"Bangumi {ret.name} is not followed")
        return

    followed_filter_obj = Filter.get(bangumi_name=ret.name)
    print_filter(followed_filter_obj)

    print_info(f"Fetch bangumi {bangumi_obj.name} ...")
    _, data = website.get_maximum_episode(
        bangumi_obj, ignore_old_row=not bool(ret.not_ignore))

    if not data:
        print_warning("Nothing.")
    for i in data:
        print_success(i.title)
Beispiel #18
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
Beispiel #19
0
    def get(self, type_=''):
        data = Followed.get_all_followed(STATUS_DELETED, STATUS_UPDATING if not type_ == 'old' else STATUS_END)

        if type_ == 'index':
            data.extend(self.patch_list)
            data.sort(key=lambda _: _['updated_time'] if _['updated_time'] else 1)

        for bangumi in data:
            bangumi['cover'] = '{}/{}'.format(COVER_URL, normalize_path(bangumi['cover']))

        data.reverse()

        for item in data:
            item['player'] = get_player(item['bangumi_name'])

        self.write(self.jsonify(data))
        self.finish()
Beispiel #20
0
    def get(self, type_=''):
        data = Followed.get_all_followed(STATUS_DELETED, STATUS_UPDATING if not type_ == 'old' else STATUS_END)

        if type_ == 'index':
            data.extend(self.patch_list)
            data.sort(key=lambda _: _['updated_time'] if _['updated_time'] else 1)

        for bangumi in data:
            bangumi['cover'] = '{}/{}'.format(COVER_URL, normalize_path(bangumi['cover']))

        data.reverse()

        for item in data:
            item['player'] = get_player(item['bangumi_name'])

        self.write(self.jsonify(data))
        self.finish()
Beispiel #21
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
Beispiel #22
0
def status_(name, status=STATUS_DELETED):
    result = {'status': 'success', 'message': ''}

    if not status in FOLLOWED_STATUS or not status:
        result['status'] = 'error'
        result['message'] = 'Invalid status: {0}'.format(status)
        return result

    status = int(status)
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        result['status'] = 'error'
        result['message'] = 'Followed<{0}> does not exists'.format(name)
        return result

    followed_obj.status = status
    followed_obj.save()
    result['message'] = 'Followed<{0}> has been marked as status {1}'.format(name, status)
    return result
Beispiel #23
0
def status_(name: str, status: int = STATUS_DELETED) -> ControllerResult:
    result = {"status": "success", "message": ""}

    if (status not in FOLLOWED_STATUS) or (not status):
        result["status"] = "error"
        result["message"] = f"Invalid status: {status}"
        return result

    status = int(status)
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        result["status"] = "error"
        result["message"] = f"Followed<{name}> does not exists"
        return result

    followed_obj.status = status
    followed_obj.save()
    result["message"] = f"Followed<{name}> has been marked as status {status}"
    return result
Beispiel #24
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))
Beispiel #25
0
    def get(self, type_=""):
        data = Followed.get_all_followed(
            STATUS_DELETED,
            STATUS_UPDATING if not type_ == "old" else STATUS_END)

        if type_ == "index":
            data.extend(self.patch_list)
            data.sort(
                key=lambda _: _["updated_time"] if _["updated_time"] else 1)

        for bangumi in data:
            bangumi["cover"] = "{}/{}".format(COVER_URL,
                                              normalize_path(bangumi["cover"]))

        data.reverse()

        for item in data:
            item["player"] = get_player(item["bangumi_name"])

        self.write(self.jsonify(data))
        self.finish()
Beispiel #26
0
def status_(name, status=STATUS_DELETED):
    result = {"status": "success", "message": ""}

    if not status in FOLLOWED_STATUS or not status:
        result["status"] = "error"
        result["message"] = "Invalid status: {}".format(status)
        return result

    status = int(status)
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        result["status"] = "error"
        result["message"] = "Followed<{}> does not exists".format(name)
        return result

    followed_obj.status = status
    followed_obj.save()
    result["message"] = "Followed<{}> has been marked as status {}".format(
        name, status)
    return result
Beispiel #27
0
def status_(name, status=STATUS_DELETED):
    result = {'status': 'success', 'message': ''}

    if not status in FOLLOWED_STATUS or not status:
        result['status'] = 'error'
        result['message'] = 'Invalid status: {0}'.format(status)
        return result

    status = int(status)
    try:
        followed_obj = Followed.get(bangumi_name=name)
    except Followed.DoesNotExist:
        result['status'] = 'error'
        result['message'] = 'Followed<{0}> does not exists'.format(name)
        return result

    followed_obj.status = status
    followed_obj.save()
    result['message'] = 'Followed<{0}> has been marked as status {1}'.format(
        name, status)
    return result
Beispiel #28
0
    def get(self):
        type_ = self.get_argument('type', 0)

        cal = Calendar()
        cal.add('prodid', '-//BGmi Followed Bangumi Calendar//bangumi.ricterz.me//')
        cal.add('version', '2.0')

        data = Followed.get_all_followed()
        data.extend(self.patch_list)

        if type_ == 0:

            bangumi = defaultdict(list)
            [bangumi[Bangumi.week.index(i['update_time']) + 1].append(i['bangumi_name']) for i in data]

            weekday = datetime.datetime.now().weekday()
            for i, k in enumerate(range(weekday, weekday + 7)):
                if k % 7 in bangumi:
                    for v in bangumi[k % 7]:
                        event = Event()
                        event.add('summary', v)
                        event.add('dtstart', datetime.datetime.now().date() + datetime.timedelta(i - 1))
                        event.add('dtend', datetime.datetime.now().date() + datetime.timedelta(i - 1))
                        cal.add_component(event)
        else:
            data = [bangumi for bangumi in data if bangumi['status'] == 2]
            for bangumi in data:
                event = Event()
                event.add('summary', 'Updated: {}'.format(bangumi['bangumi_name']))
                event.add('dtstart', datetime.datetime.now().date())
                event.add('dtend', datetime.datetime.now().date())
                cal.add_component(event)

        cal.add('name', 'Bangumi Calendar')
        cal.add('X-WR-CALNAM', 'Bangumi Calendar')
        cal.add('description', 'Followed Bangumi Calendar')
        cal.add('X-WR-CALDESC', 'Followed Bangumi Calendar')

        self.write(cal.to_ical())
        self.finish()
Beispiel #29
0
    def get(self, type_: str = "") -> None:
        data: List[dict] = Followed.get_all_followed(
            STATUS_DELETED, STATUS_END if type_ == "old" else STATUS_UPDATING)

        def sorter(_: Dict[str, int]) -> int:
            return _["updated_time"] if _["updated_time"] else 1

        if type_ == "index":
            data.extend(self.patch_list)
            data.sort(key=sorter)

        for bangumi in data:
            bangumi["cover"] = "{}/{}".format(COVER_URL,
                                              normalize_path(bangumi["cover"]))

        data.reverse()

        for item in data:
            item["player"] = get_player(item["bangumi_name"])

        self.write(self.jsonify(data))
        self.finish()
Beispiel #30
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))
Beispiel #31
0
def filter_(name, subtitle=None, include=None, exclude=None, regex=None):
    result = {'status': 'success', 'message': ''}
    try:
        bangumi_obj = Bangumi.get(name=name)
    except Bangumi.DoesNotExist:
        result['status'] = 'error'
        result['message'] = 'Bangumi {0} does not exist.'.format(name)
        return result

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist as exc:
        result['status'] = 'error'
        result['message'] = 'Bangumi {name} has not subscribed, try \'bgmi add "{name}"\'.' \
            .format(name=bangumi_obj.name)
        return result

    followed_filter_obj, is_this_obj_created = Filter.get_or_create(
        bangumi_name=name)

    if is_this_obj_created:
        followed_filter_obj.save()

    if subtitle is not None:
        subtitle = [s.strip() for s in subtitle.split(',')]
        subtitle = [s['id'] for s in Subtitle.get_subtitle_by_name(subtitle)]
        subtitle_list = [
            s.split('.')[0] for s in bangumi_obj.subtitle_group.split(', ')
            if '.' in s
        ]
        subtitle_list.extend(bangumi_obj.subtitle_group.split(', '))
        subtitle = filter(lambda s: s in subtitle_list, subtitle)
        subtitle = ', '.join(subtitle)
        followed_filter_obj.subtitle = subtitle

    if include is not None:
        followed_filter_obj.include = include

    if exclude is not None:
        followed_filter_obj.exclude = exclude

    if regex is not None:
        followed_filter_obj.regex = regex

    followed_filter_obj.save()
    subtitle_list = list(
        map(
            lambda s: s['name'],
            Subtitle.get_subtitle_by_id(
                bangumi_obj.subtitle_group.split(', '))))

    result['data'] = {
        'name':
        name,
        'subtitle_group':
        subtitle_list,
        'followed':
        list(
            map(
                lambda s: s['name'],
                Subtitle.
                get_subtitle_by_id(followed_filter_obj.subtitle.split(', ')
                                   )) if followed_filter_obj.subtitle else []),
        'include':
        followed_filter_obj.include,
        'exclude':
        followed_filter_obj.exclude,
        'regex':
        followed_filter_obj.regex,
    }
    logger.debug(result)
    return result
Beispiel #32
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 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
Beispiel #33
0
def test_mark(bangumi_names):
    name = bangumi_names[0]
    main(f"add {name} --episode 0".split())
    main(f"mark {name} 1".split())
    assert Followed.get(bangumi_name=name).episode == 1
Beispiel #34
0
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
Beispiel #35
0
def filter_(
    name: str,
    subtitle: Optional[str] = None,
    include: Optional[str] = None,
    exclude: Optional[str] = None,
    regex: Optional[str] = None,
) -> ControllerResult:
    result = {"status": "success", "message": ""}  # type: Dict[str, Any]
    try:
        bangumi_obj = Bangumi.fuzzy_get(name=name)
    except Bangumi.DoesNotExist:
        result["status"] = "error"
        result["message"] = f"Bangumi {name} does not exist."
        return result

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist:
        result["status"] = "error"
        result[
            "message"] = "Bangumi {name} has not subscribed, try 'bgmi add \"{name}\"'.".format(
                name=bangumi_obj.name)
        return result

    followed_filter_obj, is_this_obj_created = Filter.get_or_create(
        bangumi_name=bangumi_obj.name)

    if is_this_obj_created:
        followed_filter_obj.save()

    if subtitle is not None:
        _subtitle = [s.strip() for s in subtitle.split(",")]
        _subtitle = [s["id"] for s in Subtitle.get_subtitle_by_name(_subtitle)]
        subtitle_list = [
            s.split(".")[0] for s in bangumi_obj.subtitle_group.split(", ")
            if "." in s
        ]
        subtitle_list.extend(bangumi_obj.subtitle_group.split(", "))
        followed_filter_obj.subtitle = ", ".join(
            filter(lambda s: s in subtitle_list, _subtitle))

    if include is not None:
        followed_filter_obj.include = include

    if exclude is not None:
        followed_filter_obj.exclude = exclude

    if regex is not None:
        followed_filter_obj.regex = regex

    followed_filter_obj.save()
    subtitle_list = [
        s["name"] for s in Subtitle.get_subtitle_by_id(
            bangumi_obj.subtitle_group.split(", "))
    ]

    result["data"] = {
        "name":
        bangumi_obj.name,
        "subtitle_group":
        subtitle_list,
        "followed": [
            s["name"] for s in Subtitle.get_subtitle_by_id(
                followed_filter_obj.subtitle.split(", "))
        ] if followed_filter_obj.subtitle else [],
        "include":
        followed_filter_obj.include,
        "exclude":
        followed_filter_obj.exclude,
        "regex":
        followed_filter_obj.regex,
    }
    logger.debug(result)
    return result
Beispiel #36
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
Beispiel #37
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<{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
Beispiel #38
0
def filter_(name, subtitle=None, include=None, exclude=None, regex=None):
    result = {"status": "success", "message": ""}
    try:
        bangumi_obj = Bangumi.fuzzy_get(name=name)
    except Bangumi.DoesNotExist:
        result["status"] = "error"
        result["message"] = "Bangumi {} does not exist.".format(name)
        return result

    try:
        Followed.get(bangumi_name=bangumi_obj.name)
    except Followed.DoesNotExist as exc:
        result["status"] = "error"
        result[
            "message"] = "Bangumi {name} has not subscribed, try 'bgmi add \"{name}\"'.".format(
                name=bangumi_obj.name)
        return result

    followed_filter_obj, is_this_obj_created = Filter.get_or_create(
        bangumi_name=name)

    if is_this_obj_created:
        followed_filter_obj.save()

    if subtitle is not None:
        subtitle = [s.strip() for s in subtitle.split(",")]
        subtitle = [s["id"] for s in Subtitle.get_subtitle_by_name(subtitle)]
        subtitle_list = [
            s.split(".")[0] for s in bangumi_obj.subtitle_group.split(", ")
            if "." in s
        ]
        subtitle_list.extend(bangumi_obj.subtitle_group.split(", "))
        subtitle = filter(lambda s: s in subtitle_list, subtitle)
        subtitle = ", ".join(subtitle)
        followed_filter_obj.subtitle = subtitle

    if include is not None:
        followed_filter_obj.include = include

    if exclude is not None:
        followed_filter_obj.exclude = exclude

    if regex is not None:
        followed_filter_obj.regex = regex

    followed_filter_obj.save()
    subtitle_list = list(
        map(
            lambda s: s["name"],
            Subtitle.get_subtitle_by_id(
                bangumi_obj.subtitle_group.split(", ")),
        ))

    result["data"] = {
        "name":
        name,
        "subtitle_group":
        subtitle_list,
        "followed":
        list(
            map(
                lambda s: s["name"],
                Subtitle.
                get_subtitle_by_id(followed_filter_obj.subtitle.split(", ")),
            ) if followed_filter_obj.subtitle else []),
        "include":
        followed_filter_obj.include,
        "exclude":
        followed_filter_obj.exclude,
        "regex":
        followed_filter_obj.regex,
    }
    logger.debug(result)
    return result