Exemple #1
0
def cal(force_update=False, save=False):
    weekly_list = website.bangumi_calendar(force_update=force_update,
                                           save=save)
    # for web api
    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
    return r
Exemple #2
0
def cal(force_update=False, save=False):
    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)

    # for web api
    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
    return r
Exemple #3
0
def filter_(ret):
    bangumi_obj = Bangumi(name=ret.name)
    bangumi_obj.select_obj()
    if not bangumi_obj:
        print_error('Bangumi {0} does not exist.'.format(bangumi_obj.name))

    followed_obj = Followed(bangumi_name=bangumi_obj.name)
    followed_obj.select_obj()

    if not followed_obj:
        print_error(
            'Bangumi {0} has not subscribed, try \'bgmi add "{1}"\'.'.format(
                bangumi_obj.name, bangumi_obj.name))

    subtitle = ret.subtitle
    include = ret.include
    exclude = ret.exclude
    regex = ret.regex

    followed_filter_obj = Filter(bangumi_name=ret.name)
    followed_filter_obj.select_obj()

    if not followed_filter_obj:
        followed_filter_obj.save()

    if subtitle is not None:
        subtitle = map(lambda s: s.strip(), subtitle.split(','))

        subtitle = map(lambda s: s['id'],
                       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: True
                          if s in subtitle_list else False, 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()
    print_info('Usable subtitle group: {0}'.format(', '.join(
        map(lambda s: s['name'],
            Subtitle.get_subtitle(bangumi_obj.subtitle_group.split(', ')))
    )) if bangumi_obj.subtitle_group else 'None')
    print_filter(followed_filter_obj)
Exemple #4
0
def process_subtitle(data):
    '''get subtitle group name from links
    '''
    result = []
    for s in data:
        f = Subtitle(id=s['tag_id'], name=s['name'])
        if not f.select():
            f.save()
        result.append(s['tag_id'])
    return result
Exemple #5
0
    def fetch(self, save=False, group_by_weekday=True):
        bangumi_result, subtitle_group_result = self.fetch_bangumi_calendar_and_subtitle_group(
        )
        if subtitle_group_result:
            for subtitle_group in subtitle_group_result:
                s, if_created = Subtitle.get_or_create(
                    id=_unicode(subtitle_group['id']),
                    name=_unicode(subtitle_group['name']))
                if if_created:
                    s.save()
        if not bangumi_result:
            print('no result return None')
            return []

        for bangumi in bangumi_result:
            bangumi['cover'] = self.cover_url + bangumi['cover']

        if save:
            for bangumi in bangumi_result:
                self.save_data(bangumi)
        if group_by_weekday:
            result_group_by_weekday = defaultdict(list)
            for bangumi in bangumi_result:
                result_group_by_weekday[bangumi['update_time'].lower()].append(
                    bangumi)
            bangumi_result = result_group_by_weekday
        return bangumi_result
Exemple #6
0
def print_filter(followed_filter_obj):
    print_info('Followed subtitle group: {0}'.format(', '.join(
        map(lambda s: s['name'],
            Subtitle.get_subtitle(followed_filter_obj.subtitle.split(', ')))
    ) if followed_filter_obj.subtitle else 'None'))
    print_info('Include keywords: {0}'.format(followed_filter_obj.include))
    print_info('Exclude keywords: {0}'.format(followed_filter_obj.exclude))
    print_info('Regular expression: {0}'.format(followed_filter_obj.regex))
Exemple #7
0
 def followed_bangumi():
     weekly_list_followed = Bangumi.get_updating_bangumi(status=STATUS_FOLLOWED)
     weekly_list_updated = Bangumi.get_updating_bangumi(status=STATUS_UPDATED)
     weekly_list = defaultdict(list)
     for k, v in chain(weekly_list_followed.items(), weekly_list_updated.items()):
         weekly_list[k].extend(v)
     for bangumi_list in weekly_list.values():
         for bangumi in bangumi_list:
             bangumi['subtitle_group'] = [{'name': x['name'],
                                           'id': x['id']} for x in
                                          Subtitle.get_subtitle_by_id(bangumi['subtitle_group'].split(', '))]
     return weekly_list
Exemple #8
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,
    }
    return result
Exemple #9
0
def filter_(name, subtitle=None, include=None, exclude=None, regex=None):
    result = {'status': 'success', 'message': ''}
    bangumi_obj = Bangumi(name=name)
    bangumi_obj.select_obj()
    if not bangumi_obj:
        result['status'] = 'error'
        result['message'] = 'Bangumi {0} does not exist.'.format(
            bangumi_obj.name)
        return result

    followed_obj = Followed(bangumi_name=bangumi_obj.name)
    followed_obj.select_obj()

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

    followed_filter_obj = Filter(bangumi_name=name)
    followed_filter_obj.select_obj()

    if not followed_filter_obj:
        followed_filter_obj.save()

    if subtitle is not None:
        subtitle = map(lambda s: s.strip(), subtitle.split(','))
        subtitle = map(lambda s: s['id'],
                       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(bangumi_obj.subtitle_group.split(', '))))
    print_info('Usable subtitle group: {0}'.format(
        ', '.join(subtitle_list) if subtitle_list else 'None'))

    print_filter(followed_filter_obj)
    result['data'] = {
        'name':
        name,
        'subtitle_group':
        list(
            map(lambda s: s['name'],
                Subtitle.get_subtitle(
                    bangumi_obj.subtitle_group.split(', ')))),
        'followed':
        list(
            map(
                lambda s: s['name'],
                Subtitle.get_subtitle(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,
    }
    return result
Exemple #10
0
def bangumi_calendar(force_update=False, today=False, followed=False, save=True):
    env_columns = 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)

    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 = fetch(save=save, status=True)
    else:
        if followed:
            weekly_list_followed = Bangumi.get_all_bangumi(status=STATUS_FOLLOWED)
            weekly_list_updated = Bangumi.get_all_bangumi(status=STATUS_UPDATED)
            weekly_list = defaultdict(list)
            for k, v in chain(weekly_list_followed.items(), weekly_list_updated.items()):
                weekly_list[k].extend(v)
        else:
            weekly_list = Bangumi.get_all_bangumi()

    if not weekly_list:
        if not followed:
            print_warning('warning: no bangumi schedule, fetching ...')
            weekly_list = fetch(save=save)
        else:
            print_warning('you have not subscribed any bangumi')

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

    def print_line():
        num = COL - 3
        # print('+', '-' * num, '+', '-' * num, '+', '-' * num, '+')
        split = '-' * num + '   '
        print(split * row)

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

    spacial_append_chars = ['Ⅱ', 'Ⅲ', '♪', 'Δ', '×', '☆', 'é', '·', '♭']
    spacial_remove_chars = []

    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='')
            if not followed:
                print()
                print_line()

            for i, bangumi in enumerate(weekly_list[weekday.lower()]):
                if isinstance(bangumi['name'], _unicode):
                    # bangumi['name'] = bangumi['name']
                    pass

                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 += 1

                for s in spacial_remove_chars:
                    if s in bangumi['name']:
                        space_count -= 1

                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)

                if followed:
                    if i > 0:
                        print(' ' * 5, end='')
                    f = map(lambda s: s['name'], Subtitle.get_subtitle(bangumi['subtitle_group'].split(', ')))
                    print(bangumi['name'], ', '.join(f))
                else:
                    print(' ' + bangumi['name'], ' ' * space_count, end='')
                    if (i + 1) % row == 0 or i + 1 == len(weekly_list[weekday.lower()]):
                        print()

            if not followed:
                print()