Ejemplo n.º 1
0
Archivo: fetch.py Proyecto: ihciah/BGmi
def get_response(url, method='GET', **kwargs):
    if os.environ.get('DEBUG'):
        print_info('Request URL: {0}'.format(url))
    try:
        return getattr(requests, method.lower())(url, **kwargs).json()
    except requests.ConnectionError:
        print_error('error: failed to establish a new connection')
Ejemplo n.º 2
0
Archivo: main.py Proyecto: xxoxx/BGmi
def download_manager(ret):
    print_info(
        'Download status value: Not Downloaded: 0 / Downloading: 1 / Downloaded: 2\n',
        indicator=False)

    if ret.action.download == DOWNLOAD_ACTION_LIST:
        status = ret.action.download.list.status
        status = int(status) if status is not None else None
        delegate = get_download_class(instance=False)
        delegate.download_status(status=status)

    elif ret.action.download == DOWNLOAD_ACTION_MARK:
        download_id = ret.action.download.mark.id
        status = ret.action.download.mark.status
        if not download_id or not status:
            print_error('No id or status specified.')
        download_obj = Download(_id=download_id)
        download_obj.select_obj()
        if not download_obj:
            print_error('Download object does not exist.')
        print_info('Download Object <{0} - {1}>, Status: {2}'.format(
            download_obj.name, download_obj.episode, download_obj.status))
        download_obj.status = status
        download_obj.save()
        print_success('Download status has been marked as {0}'.format(
            DOWNLOAD_CHOICE_LIST_DICT.get(int(status))))
Ejemplo n.º 3
0
def update(ret):
    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'] + 86400) < now:
            followed_obj = Followed(bangumi_name=i['bangumi_name'])
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

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

    if ret.action.update.name is None:
        updated_bangumi_obj = Followed.get_all_followed()
    else:
        updated_bangumi_obj = []
        for i in ret.action.update.name:
            f = Followed(bangumi_name=i)
            f.select_obj()
            updated_bangumi_obj.append(f)

    for subscribe in updated_bangumi_obj:
        print_info('fetching %s ...' % subscribe['bangumi_name'])
        bangumi_obj = Bangumi(name=subscribe['bangumi_name'])
        bangumi_obj.select_obj()

        # filter by subtitle group
        if not bangumi_obj:
            print_error(
                'The bangumi {0} you subscribed does not exists ..'.format(
                    subscribe['bangumi_name']),
                exit_=False)
            continue

        episode, all_episode_data = get_maximum_episode(bangumi=bangumi_obj)
        if episode.get('episode') > subscribe['episode']:
            episode_range = range(subscribe['episode'] + 1,
                                  episode.get('episode'))
            print_success('%s updated, episode: %d' %
                          (subscribe['bangumi_name'], episode['episode']))
            _ = Followed(bangumi_name=subscribe['bangumi_name'])
            _.episode = episode['episode']
            _.status = STATUS_UPDATED
            _.updated_time = int(time.time())
            _.save()
            download_queue.append(episode)
            for i in episode_range:
                for epi in all_episode_data:
                    if epi['episode'] == i:
                        download_queue.append(epi)
                        break

    if ret.action.update and ret.action.update.download:
        download_prepare(download_queue)
        print_info('Re-downloading ...')
        download_prepare(
            Download.get_all_downloads(status=STATUS_NOT_DOWNLOAD))
Ejemplo n.º 4
0
 def download(self):
     if self.old_version:
         self.server.aria2.addUri([self.torrent], {"dir": self.save_path})
     else:
         self.server.aria2.addUri(ARIA2_RPC_TOKEN, [self.torrent],
                                  {"dir": self.save_path})
     print_info(
         'Add torrent into the download queue, the file will be saved at {0}'
         .format(self.save_path))
Ejemplo n.º 5
0
def exec_sql(sql):
    try:
        print_info('Execute {}'.format(sql))
        conn = sqlite3.connect(DB_PATH)
        conn.execute(sql)
        conn.commit()
        conn.close()
    except sqlite3.OperationalError:
        print_error('Execute SQL statement failed', exit_=False)
Ejemplo n.º 6
0
def fetch_episode(_id, name='', **kwargs):
    result = []
    response_data = []

    subtitle_group = kwargs.get('subtitle_group', None)
    include = kwargs.get('include', None)
    exclude = kwargs.get('exclude', None)
    regex = kwargs.get('regex', None)
    max_page = int(kwargs.get('max', int(MAX_PAGE)))

    if subtitle_group and subtitle_group.split(', '):
        condition = subtitle_group.split(', ')
        for c in condition:
            data = {'tag_id': [_id, c, BANGUMI_TAG]}
            response = get_response(DETAIL_URL, 'POST', json=data)
            response_data.extend(response['torrents'])
    else:
        response_data = []
        for i in range(max_page):
            if max_page > 1:
                print_info('Fetch page {0} ...'.format(i + 1))
            data = {'tag_id': [_id, BANGUMI_TAG], 'p': i + 1}
            response = get_response(DETAIL_URL, 'POST', json=data)
            if response:
                response_data.extend(response['torrents'])

    for info in response_data:
        if '合集' not in info['title']:
            result.append({
                'download': info['magnet'],
                'name': name,
                'subtitle_group': info['team_id'],
                'title': info['title'],
                'episode': parse_episode(info['title']),
                'time': int(time.mktime(datetime.datetime.strptime(info['publish_time'].split('.')[0],
                                                                   "%Y-%m-%dT%H:%M:%S").timetuple()))
            })

    if include:
        include_list = list(map(lambda s: s.strip(), include.split(',')))
        result = list(filter(lambda s: True if all(map(lambda t: t in s['title'],
                                                       include_list)) else False, result))

    if exclude:
        exclude_list = list(map(lambda s: s.strip(), exclude.split(',')))
        result = list(filter(lambda s: True if all(map(lambda t: t not in s['title'],
                                                       exclude_list)) else False, result))

    if regex:
        try:
            match = re.compile(regex)
            result = list(filter(lambda s: True if match.findall(s['title']) else False, result))
        except re.error:
            pass

    return result
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
 def download(self):
     try:
         import transmissionrpc
         tc = transmissionrpc.Client(TRANSMISSION_RPC_URL,
                                     port=TRANSMISSION_RPC_PORT)
         tc.add_torrent(self.torrent, download_dir=self.save_path)
         print_info(
             'Add torrent into the download queue, the file will be saved at {0}'
             .format(self.save_path))
     except ImportError:
         pass
Ejemplo n.º 9
0
def get_response(url, method='GET', **kwargs):
    if os.environ.get('DEBUG'):
        print_info('Request URL: {0}'.format(url))
    try:
        if os.environ.get('DEBUG'):
            print(getattr(requests, method.lower())(url, **kwargs).text)

        return getattr(requests, method.lower())(url, **kwargs).json()
    except requests.ConnectionError:
        print_error('error: failed to establish a new connection')
    except ValueError:
        print_error('error: server returned data maybe not be json, please contact [email protected]')
Ejemplo n.º 10
0
    def download(self):
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)

        command = [
            WGET_PATH, '--no-parent', '-r', '--no-host-directories',
            '--cut-dirs', '100', '--reject', 'index.html', '-P',
            '{0}/'.format(self.save_path),
            'https://bgmi.ricterz.me/bangumi/{0}/{1}/'.format(
                self.name, self.episode)
        ]
        print_info('Start download ...')
        self.call(command)
Ejemplo n.º 11
0
    def download(self):
        overwrite = '--overwrite' if self.overwrite else ''

        command = [
            BGMI_LX_PATH, 'download', '--torrent', overwrite,
            '--output-dir={0}'.format(self.save_path), self.torrent,
            '--verification-code-path={0}'.format(
                os.path.join(BGMI_TMP_PATH, 'vcode.jpg'))
        ]

        print_info('Run command {0}'.format(' '.join(command)))
        print_warning('Verification code path: {0}'.format(
            os.path.join(BGMI_TMP_PATH, 'vcode.jpg')))
        self.call(command)
Ejemplo n.º 12
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))
Ejemplo n.º 13
0
def mark(ret):
    name = ret.name
    episode = ret.episode
    followed_obj = Followed(bangumi_name=name)
    followed_obj.select_obj()

    if not followed_obj:
        print_error('Subscribe <%s> does not exist.' % name)

    if episode is not None:
        followed_obj.episode = episode
        followed_obj.save()
        print_success('%s has been mark as episode: %s' %
                      (followed_obj, followed_obj.episode))
    else:
        print_info('%s, episode: %s' % (followed_obj, followed_obj.episode))
Ejemplo n.º 14
0
Archivo: main.py Proyecto: xxoxx/BGmi
def followed(ret):
    if ret.action.followed == FOLLOWED_ACTION_MARK:
        name = ret.action.followed.mark.name
        episode = ret.action.followed.mark.episode
        followed_obj = Followed(bangumi_name=name)
        followed_obj.select_obj()

        if not followed_obj:
            print_error('Subscribe <%s> does not exist.' % name)

        if episode:
            followed_obj.episode = episode
            followed_obj.save()
            print_success('%s has been mark as episode: %s' %
                          (followed_obj, followed_obj.episode))
        else:
            print_info('%s, episode: %s' %
                       (followed_obj, followed_obj.episode))
    else:
        bangumi_calendar(force_update=False, followed=True, save=False)
Ejemplo n.º 15
0
Archivo: main.py Proyecto: xxoxx/BGmi
def filter_(ret):
    bangumi_obj = Bangumi(name=ret.action.filter.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.action.filter.subtitle_group
    if subtitle:
        if not ret.action.filter.remove and not ret.action.filter.remove_all:
            if not followed_obj.subtitle_group:
                followed_obj.subtitle_group = subtitle
            else:
                group = followed_obj.subtitle_group.split(',')
                for i in subtitle.split(','):
                    if i not in group:
                        group.append(i)
                followed_obj.subtitle_group = ','.join(group)
        elif ret.action.filter.remove:
            if followed_obj.subtitle_group:
                group = followed_obj.subtitle_group.split(',')
                new_group = []
                while group:
                    _ = group.pop()
                    if _ not in subtitle:
                        new_group.append(_)
                followed_obj.subtitle_group = ','.join(new_group)

    if ret.action.filter.remove_all:
        followed_obj.subtitle_group = ''

    followed_obj.save()
    print_info('Usable subtitle group: {0}'.format(bangumi_obj.subtitle_group))
    print_info('Added subtitle group: {0}'.format(followed_obj.subtitle_group))
Ejemplo n.º 16
0
def download_manager(ret):
    if ret.id:
        download_id = ret.id
        status = ret.status
        if download_id is None or status is None:
            print_error('No id or status specified.')
        download_obj = Download(_id=download_id)
        download_obj.select_obj()
        if not download_obj:
            print_error('Download object does not exist.')
        print_info('Download Object <{0} - {1}>, Status: {2}'.format(
            download_obj.name, download_obj.episode, download_obj.status))
        download_obj.status = status
        download_obj.save()
        print_success('Download status has been marked as {0}'.format(
            DOWNLOAD_CHOICE_LIST_DICT.get(int(status))))
    else:
        status = ret.status
        status = int(status) if status is not None else None
        delegate = get_download_class(instance=False)
        delegate.download_status(status=status)
Ejemplo n.º 17
0
 def download_status(status=None):
     print_info('Print download status in database')
     DownloadService.download_status(status=status)
     print()
     print_info('Print download status in aria2c-rpc')
     server = PatchedServerProxy(ARIA2_RPC_URL)
     # self.server.aria2
     status_dict = {
         STATUS_DOWNLOADING: ['tellActive'],
         STATUS_NOT_DOWNLOAD: ['tellWaiting'],
         STATUS_DOWNLOADED: ['tellStopped'],
         None: ['tellStopped', 'tellWaiting', 'tellActive'],
     }
     for method in status_dict.get(status):
         if method not in ('tellActive', ):
             params = (0, 1000)
         else:
             params = ()
         data = server.aria2[method](*params)
         if data:
             print_warning('RPC {0}:'.format(method), indicator=False)
         for row in data:
             print_success('- {0}'.format(row['dir']), indicator=False)
             for file in row['files']:
                 print_info('    * {0}'.format(file['path']),
                            indicator=False)
Ejemplo n.º 18
0
def fetch_(ret):
    bangumi_obj = Bangumi(name=ret.name)
    bangumi_obj.select_obj()

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

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

    if bangumi_obj:
        print_info('Fetch bangumi {0} ...'.format(bangumi_obj.name))
        _, data = 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'])

    else:
        print_error('Bangumi {0} not exist'.format(ret.name))
Ejemplo n.º 19
0
    def download_status(status=None):
        last_status = -1
        for download_data in Download.get_all_downloads(status=status):
            latest_status = download_data['status']
            name = '  {0}. <{1}: {2}>'.format(download_data['id'],
                                              download_data['name'],
                                              download_data['episode'])
            if latest_status != last_status:
                if latest_status == STATUS_DOWNLOADING:
                    print('Downloading items:')
                elif latest_status == STATUS_NOT_DOWNLOAD:
                    print('Not downloaded items:')
                elif latest_status == STATUS_DOWNLOADED:
                    print('Downloaded items:')

            if download_data['status'] == STATUS_NOT_DOWNLOAD:
                print_info(name, indicator=False)
            elif download_data['status'] == STATUS_DOWNLOADING:
                print_warning(name, indicator=False)
            elif download_data['status'] == STATUS_DOWNLOADED:
                print_success(name, indicator=False)
            last_status = download_data['status']
Ejemplo n.º 20
0
 def download_status(status=None):
     print_info('Print download status in database')
     DownloadService.download_status(status=status)
     print()
     print_info('Print download status in transmission-rpc')
     try:
         import transmissionrpc
         tc = transmissionrpc.Client(TRANSMISSION_RPC_URL,
                                     port=TRANSMISSION_RPC_PORT)
         for torrent in tc.get_torrents():
             print_info('  * {0}: {1}'.format(torrent.status, torrent),
                        indicator=False)
     except ImportError:
         pass
Ejemplo n.º 21
0
    def install():
        # install xunlei-lixian
        import tarfile
        import requests
        print_info(
            'Downloading xunlei-lixian from https://github.com/iambus/xunlei-lixian/'
        )
        r = requests.get(
            'https://github.com/iambus/xunlei-lixian/tarball/master',
            stream=True,
            headers={'Accept-Encoding': ''})
        f = NamedTemporaryFile(delete=False)

        with f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
        f.close()
        print_success('Download successfully, save at %s, extracting ...' %
                      f.name)
        zip_file = tarfile.open(f.name, 'r:gz')
        zip_file.extractall(os.path.join(BGMI_PATH, 'tools/xunlei-lixian'))
        dir_name = zip_file.getnames()[0]

        print_info('Create link file ...')

        if not os.path.exists(BGMI_LX_PATH):
            os.symlink(
                os.path.join(
                    BGMI_PATH,
                    'tools/xunlei-lixian/{0}/lixian_cli.py'.format(dir_name)),
                BGMI_LX_PATH)
        else:
            print_warning('{0} already exists'.format(BGMI_LX_PATH))

        print_success('All done')
        print_info(
            'Please run command \'{0} config\' to configure your lixian-xunlei '
            '(Notice: only for Thunder VIP)'.format(BGMI_LX_PATH))
Ejemplo n.º 22
0
    def download_status(status=None):
        Aria2DownloadRPC.check_aria2c_version()

        print_info('Print download status in database')
        DownloadService.download_status(status=status)
        print()
        print_info('Print download status in aria2c-rpc')
        try:
            server = PatchedServerProxy(ARIA2_RPC_URL)
            # self.server.aria2
            status_dict = {
                STATUS_DOWNLOADING: ['tellActive'],
                STATUS_NOT_DOWNLOAD: ['tellWaiting'],
                STATUS_DOWNLOADED: ['tellStopped'],
                None: ['tellStopped', 'tellWaiting', 'tellActive'],
            }
            for method in status_dict.get(status):
                if method not in ('tellActive', ):
                    params = (0, 1000)
                else:
                    params = ()
                if Aria2DownloadRPC.old_version:
                    data = server.aria2[method](*params)
                else:
                    data = server.aria2[method](ARIA2_RPC_TOKEN, *params)

                if data:
                    print_warning('RPC {0}:'.format(method), indicator=False)

                for row in data:
                    print_success('- {0}'.format(row['dir']), indicator=False)
                    for file_ in row['files']:
                        print_info('    * {0}'.format(file_['path']),
                                   indicator=False)

        except Exception as e:
            print_error('Cannot connect to aria2-rpc server')
Ejemplo n.º 23
0
Archivo: fetch.py Proyecto: xxoxx/BGmi
def bangumi_calendar(force_update=False,
                     today=False,
                     followed=False,
                     save=True):
    env_columns = get_terminal_col()

    if env_columns < 36:
        print_error('terminal window is too small.')
    row = int(env_columns / 36 if env_columns / 36 <= 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 = 33
        # 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(
                '\033[1;32m%s. \033[0m' %
                (weekday if not today else 'Bangumi Schedule for Today (%s)' %
                 weekday),
                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 = 34 - (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'] = '\033[1;33m%s\033[0m' % bangumi['name']

                if bangumi['status'] == STATUS_UPDATED:
                    bangumi['name'] = '\033[1;32m%s\033[0m' % bangumi['name']

                if followed:
                    if i > 0:
                        print(' ' * 5, end='')
                    print(bangumi['name'], bangumi['subtitle_group'])
                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()
Ejemplo n.º 24
0
 def install():
     print_info('Please install curl by yourself')
Ejemplo n.º 25
0
 def download(self):
     command = [
         ARIA2_PATH, '--seed-time=0', '-d', self.save_path, self.torrent
     ]
     print_info('Run command {0}'.format(' '.join(command)))
     self.call(command)
Ejemplo n.º 26
0
def install_crontab():
    print_info('Installing crontab job')
    path = os.path.join(os.path.dirname(__file__), 'crontab.sh')
    os.system('sh \'%s\'' % path)
Ejemplo n.º 27
0
def update(ret):
    ignore = False if ret.not_ignore else True
    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'] + 86400) < now:
            followed_obj = Followed(bangumi_name=i['bangumi_name'])
            followed_obj.status = STATUS_FOLLOWED
            followed_obj.save()

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

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

    if not ret.name:
        updated_bangumi_obj = Followed.get_all_followed()
    else:
        updated_bangumi_obj = []
        for i in ret.name:
            f = Followed(bangumi_name=i)
            f.select_obj()
            updated_bangumi_obj.append(f)

    for subscribe in updated_bangumi_obj:
        print_info('fetching %s ...' % subscribe['bangumi_name'])
        bangumi_obj = Bangumi(name=subscribe['bangumi_name'])
        bangumi_obj.select_obj()

        followed_obj = Followed(bangumi_name=subscribe['bangumi_name'])
        followed_obj.select_obj()

        # filter by subtitle group
        if not bangumi_obj or not followed_obj:
            print_error(
                'Bangumi<{0}> does not exist or not been followed.'.format(
                    subscribe['bangumi_name']),
                exit_=False)
            continue

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

        if (episode.get('episode') > subscribe['episode']) or (len(
                ret.name) == 1 and ret.download):
            if len(ret.name) == 1 and ret.download:
                episode_range = ret.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()

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

    if ret.download is not None:
        download_prepare(download_queue)
        print_info('Re-downloading ...')
        download_prepare(
            Download.get_all_downloads(status=STATUS_NOT_DOWNLOAD))
Ejemplo n.º 28
0
Archivo: main.py Proyecto: xxoxx/BGmi
def main():
    c = CommandParser()
    action = c.add_arg_group('action')

    sub_parser_add = action.add_sub_parser(ACTION_ADD,
                                           help='Subscribe bangumi.')
    sub_parser_add.add_argument('name',
                                arg_type='+',
                                required=True,
                                help='Bangumi name to subscribe.')

    sub_parser_filter = action.add_sub_parser(ACTION_FILTER,
                                              help='Set bangumi fetch filter.')
    sub_parser_filter.add_argument('name',
                                   required=True,
                                   help='Bangumi name to set the filter.')
    sub_parser_filter.add_argument('subtitle_group',
                                   help='Subtitle group name.')
    sub_parser_filter.add_argument('--remove',
                                   help='Remove subtitle group filter.')
    sub_parser_filter.add_argument(
        '--remove-all',
        help='Remove all the subtitle group filter.',
        mutex='--remove')

    sub_parser_del = action.add_sub_parser(ACTION_DELETE,
                                           help='Unsubscribe bangumi.')
    sub_parser_del.add_argument('--name',
                                arg_type='+',
                                mutex='--clear-all',
                                help='Bangumi name to unsubscribe.')
    sub_parser_del.add_argument('--clear-all',
                                help='Clear all the subscriptions.')
    sub_parser_del.add_argument('--batch', help='No confirmation.')

    sub_parser_fetch = action.add_sub_parser(ACTION_FETCH,
                                             help='Fetch a specific bangumi.')
    sub_parser_fetch.add_argument('name',
                                  help='Bangumi name to fetch.',
                                  required=True)

    sub_parser_update = action.add_sub_parser(
        ACTION_UPDATE,
        help='Update bangumi calendar and '
        'subscribed bangumi episode.')
    sub_parser_update.add_argument('--download',
                                   help='Download the bangumi when updated.')

    sub_parser_cal = action.add_sub_parser(ACTION_CAL,
                                           help='Print bangumi calendar.')
    sub_parser_cal.add_argument('filter',
                                default='today',
                                choice=FILTER_CHOICES,
                                help='Calendar form filter %s.' %
                                ', '.join(FILTER_CHOICES))
    sub_parser_cal.add_argument('--today',
                                help='Show bangumi calendar for today.')
    sub_parser_cal.add_argument(
        '--force-update', help='Get the newest bangumi calendar from dmhy.')
    sub_parser_cal.add_argument(
        '--no-save', help='Do not save the bangumi data when force update.')

    sub_parser_config = action.add_sub_parser(ACTION_CONFIG,
                                              help='Config BGmi.')
    sub_parser_config.add_argument('name', help='Config name')
    sub_parser_config.add_argument('value', help='Config value')

    sub_parser_followed = action.add_sub_parser(
        ACTION_FOLLOWED, help='Followed bangumi manager.')
    sub_parser_followed.add_sub_parser('list', help='List followed bangumi.')
    followed_mark = sub_parser_followed.add_sub_parser(
        'mark', help='Mark specific bangumi\'s episode.')
    followed_mark.add_argument('name', help='Bangumi name.', required=True)
    followed_mark.add_argument('episode', help='Bangumi episode.')

    sub_parser_download = action.add_sub_parser(ACTION_DOWNLOAD,
                                                help='Download manager.')
    download_list = sub_parser_download.add_sub_parser(
        'list', help='List download queue.')
    download_list.add_argument('status',
                               help='Download status: 0, 1, 2',
                               choice=(0, 1, 2, None))

    download_mark = sub_parser_download.add_sub_parser(
        'mark', help='Mark download status with a specific id.')
    download_mark.add_argument('id', help='Download id')
    download_mark.add_argument('status',
                               help='Status will be marked',
                               choice=(0, 1, 2))

    positional = c.add_arg_group('positional')
    positional.add_argument('install', help='Install xunlei-lixian for BGmi.')

    c.add_argument('-h', help='Print help text.')
    c.add_argument('--version', help='Show the version of BGmi.')
    c.add_argument('--debug', help='Enable DEBUG mode.')

    ret = c.parse_command()

    if ret.version:
        print_version()
        raise SystemExit

    if ret.positional.install == 'install':
        import bgmi.setup
        bgmi.setup.install()
        raise SystemExit

    elif ret.action == ACTION_ADD:
        add(ret)

    elif ret.action == ACTION_FILTER:
        filter_(ret)

    elif ret.action == ACTION_FETCH:
        bangumi_obj = Bangumi(name=ret.action.fetch.name)
        bangumi_obj.select_obj()

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

        if bangumi_obj:
            print_info('Fetch bangumi {0} ...'.format(bangumi_obj.name))
            _, data = get_maximum_episode(bangumi_obj)
            for i in data:
                print_success(i['title'])

        else:
            print_error('Bangumi {0} not exist'.format(ret.action.fetch.name))

    elif ret.action == ACTION_DELETE:
        delete(ret)

    elif ret.action == ACTION_UPDATE:
        update(ret)

    elif ret.action == ACTION_CAL:
        cal(ret)

    elif ret.action == ACTION_CONFIG:
        write_config(ret.action.config.name, ret.action.config.value)

    elif ret.action == ACTION_FOLLOWED:
        if not ret.action.followed == 'mark' and not ret.action.followed.list:
            c.print_help()
        else:
            followed(ret)

    elif ret.action == ACTION_DOWNLOAD:
        if ret.action.download in DOWNLOAD_ACTION:
            download_manager(ret)
        else:
            c.print_help()
    else:
        c.print_help()
Ejemplo n.º 29
0
 def download(self):
     self.server.aria2.addUri([self.torrent], {"dir": self.save_path})
     print_info(
         'Add torrent into the download queue, the file will be saved at {0}'
         .format(self.save_path))