Exemple #1
0
    def get_bangumi(self, id):
        try:
            session = SessionManager.Session()

            bangumi = session.query(Bangumi).options(joinedload(Bangumi.episodes)).filter(Bangumi.id == id).one()

            episodes = []

            for episode in bangumi.episodes:
                eps = row2dict(episode)
                eps['thumbnail'] = utils.generate_thumbnail_link(episode, bangumi)
                episodes.append(eps)

            bangumi_dict = row2dict(bangumi)

            bangumi_dict['episodes'] = episodes

            bangumi_dict['cover'] = utils.generate_cover_link(bangumi)

            return json_resp({'data': bangumi_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()
    def recent_update(self, days):

        current = datetime.now()

        # from one week ago
        start_time = current - timedelta(days=days)

        session = SessionManager.Session()
        try:
            result = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.status == Episode.STATUS_DOWNLOADED).\
                filter(Episode.update_time >= start_time).\
                filter(Episode.update_time <= current).\
                order_by(desc(Episode.update_time))

            episode_list = []

            for eps, bgm in result:
                episode = row2dict(eps)
                episode['thumbnail'] = utils.generate_thumbnail_link(eps, bgm)
                episode['bangumi'] = row2dict(bgm)
                episode['bangumi']['cover'] = utils.generate_cover_link(bgm)
                episode_list.append(episode)

            return json_resp({'data': episode_list})
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #3
0
    def list_pending_delete_episode(self):
        try:
            current = datetime.now()
            session = SessionManager.Session()
            result = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.delete_mark != None).\
                all()

            eps_list = []
            for episode, bangumi in result:
                bgm = row2dict(bangumi)
                eps = row2dict(episode)
                # noinspection PyTypeChecker
                delete_eta = int(
                    (episode.delete_mark +
                     timedelta(minutes=self.delete_delay['episode']) -
                     current).total_seconds() / 60)
                eps['delete_eta'] = delete_eta
                eps['bangumi'] = bgm
                eps_list.append(eps)
            return json_resp({
                'data': eps_list,
                'delete_delay': self.delete_delay['episode']
            })
        finally:
            SessionManager.Session.remove()
Exemple #4
0
    def get_bangumi(self, id):
        try:
            session = SessionManager.Session()

            bangumi = session.query(Bangumi).options(joinedload(Bangumi.episodes)).\
                filter(Bangumi.id == id).\
                filter(Bangumi.delete_mark == None).\
                one()

            episodes = []

            for episode in bangumi.episodes:
                if episode.delete_mark is not None:
                    continue
                eps = row2dict(episode)
                eps['thumbnail'] = utils.generate_thumbnail_link(
                    episode, bangumi)
                episodes.append(eps)

            bangumi_dict = row2dict(bangumi)

            bangumi_dict['episodes'] = episodes

            bangumi_dict['cover'] = utils.generate_cover_link(bangumi)

            return json_resp({'data': bangumi_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()
Exemple #5
0
    def recent_update(self, days):

        current = datetime.now()

        # from one week ago
        start_time = current - timedelta(days=days)

        session = SessionManager.Session()
        try:
            result = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.status == Episode.STATUS_DOWNLOADED).\
                filter(Episode.update_time >= start_time).\
                filter(Episode.update_time <= current).\
                order_by(desc(Episode.update_time))

            episode_list = []

            for eps, bgm in result:
                episode = row2dict(eps)
                episode['thumbnail'] = utils.generate_thumbnail_link(eps, bgm)
                episode['bangumi'] = row2dict(bgm)
                episode['bangumi']['cover'] = utils.generate_cover_link(bgm)
                episode_list.append(episode)

            return json_resp({'data': episode_list})
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #6
0
    def episode_detail(self, episode_id):
        session = SessionManager.Session()
        try:
            (episode, bangumi) = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.id == episode_id).one()
            episode_dict = row2dict(episode)
            episode_dict['bangumi'] = row2dict(bangumi)
            episode_dict['thumbnail'] = utils.generate_thumbnail_link(
                episode, bangumi)

            if episode.status == Episode.STATUS_DOWNLOADED:
                episode_dict['videos'] = []
                torrent_file_cur = session.query(TorrentFile).filter(
                    TorrentFile.episode_id == episode_id)
                for torrent_file in torrent_file_cur:
                    episode_dict['videos'].append(
                        utils.generate_video_link(str(bangumi.id),
                                                  torrent_file.file_path))

            return json_resp(episode_dict)
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #7
0
 def __process_user_obj_in_bangumi(self, bangumi, bangumi_dict):
     if bangumi.created_by is not None:
         bangumi_dict['created_by'] = row2dict(bangumi.created_by)
         bangumi_dict['created_by'].pop('password', None)
     if bangumi.maintained_by is not None:
         bangumi_dict['maintained_by'] = row2dict(bangumi.maintained_by)
         bangumi_dict['maintained_by'].pop('password', None)
     bangumi_dict.pop('created_by_uid', None)
     bangumi_dict.pop('maintained_by_uid', None)
Exemple #8
0
 def __process_user_obj_in_bangumi(self, bangumi, bangumi_dict):
     if bangumi.created_by is not None:
         bangumi_dict['created_by'] = row2dict(bangumi.created_by, User)
         bangumi_dict['created_by'].pop('password', None)
     if bangumi.maintained_by is not None:
         bangumi_dict['maintained_by'] = row2dict(bangumi.maintained_by, User)
         bangumi_dict['maintained_by'].pop('password', None)
     bangumi_dict.pop('created_by_uid', None)
     bangumi_dict.pop('maintained_by_uid', None)
Exemple #9
0
    def get_bangumi(self, id, user_id):
        try:
            session = SessionManager.Session()

            bangumi = session.query(Bangumi).\
                options(joinedload(Bangumi.episodes).joinedload(Episode.thumbnail_image)).\
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None).\
                filter(Bangumi.id == id).\
                one()

            favorite = session.query(Favorites).\
                filter(Favorites.bangumi_id == id).\
                filter(Favorites.user_id == user_id).\
                first()

            watch_progress_list = session.query(WatchProgress).\
                filter(WatchProgress.bangumi_id == bangumi.id).\
                filter(WatchProgress.user_id == user_id).\
                all()

            episodes = []

            watch_progress_hash_table = {}
            for watch_progress in watch_progress_list:
                watch_progress_dict = row2dict(watch_progress)
                watch_progress_hash_table[
                    watch_progress.episode_id] = watch_progress_dict

            for episode in bangumi.episodes:
                if episode.delete_mark is not None:
                    continue
                eps = row2dict(episode)
                eps['thumbnail'] = utils.generate_thumbnail_link(
                    episode, bangumi)
                utils.process_episode_dict(episode, eps)
                if episode.id in watch_progress_hash_table:
                    eps['watch_progress'] = watch_progress_hash_table[
                        episode.id]
                episodes.append(eps)

            bangumi_dict = row2dict(bangumi)

            if favorite is not None:
                bangumi_dict['favorite_status'] = favorite.status

            bangumi_dict['episodes'] = episodes

            bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
            utils.process_bangumi_dict(bangumi, bangumi_dict)

            return json_resp({'data': bangumi_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #10
0
    def get_bangumi(self, id, user_id):
        try:
            session = SessionManager.Session()

            bangumi = session.query(Bangumi).\
                options(joinedload(Bangumi.episodes).joinedload(Episode.thumbnail_image)).\
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None).\
                filter(Bangumi.id == id).\
                one()

            favorite = session.query(Favorites).\
                filter(Favorites.bangumi_id == id).\
                filter(Favorites.user_id == user_id).\
                first()

            watch_progress_list = session.query(WatchProgress).\
                filter(WatchProgress.bangumi_id == bangumi.id).\
                filter(WatchProgress.user_id == user_id).\
                all()

            episodes = []

            watch_progress_hash_table = {}
            for watch_progress in watch_progress_list:
                watch_progress_dict = row2dict(watch_progress, WatchProgress)
                watch_progress_hash_table[watch_progress.episode_id] = watch_progress_dict

            for episode in bangumi.episodes:
                if episode.delete_mark is not None:
                    continue
                eps = row2dict(episode, Episode)
                eps['thumbnail'] = utils.generate_thumbnail_link(episode, bangumi)
                utils.process_episode_dict(episode, eps)
                if episode.id in watch_progress_hash_table:
                    eps['watch_progress'] = watch_progress_hash_table[episode.id]
                episodes.append(eps)

            bangumi_dict = row2dict(bangumi, Bangumi)

            if favorite is not None:
                bangumi_dict['favorite_status'] = favorite.status

            bangumi_dict['episodes'] = episodes

            bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
            utils.process_bangumi_dict(bangumi, bangumi_dict)

            return json_resp({'data': bangumi_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #11
0
    def on_air_bangumi(self):
        session = SessionManager.Session()
        current_day = datetime.today()
        start_time = datetime(current_day.year, current_day.month, 1)
        if current_day.month == 12:
            next_year = current_day.year + 1
            next_month = 1
        else:
            next_year = current_day.year
            next_month = current_day.month + 1
        end_time = datetime(next_year, next_month, 1)

        try:
            result = session.query(distinct(Episode.bangumi_id), Bangumi).\
                join(Bangumi).\
                filter(Episode.airdate >= start_time).\
                filter(Episode.airdate <= end_time)

            bangumi_list = [
                row2dict(bangumi) for bangumi_id, bangumi in result
            ]

            return json_resp({'data': bangumi_list})
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #12
0
    def delete_episode(self, episode):
        session = SessionManager.Session()
        try:
            task_content = {'episode_id': str(episode.id)}
            video_file_list = session.query(VideoFile).\
                filter(VideoFile.episode_id == episode.id).\
                all()

            watch_progress_list = session.query(WatchProgress).filter(
                WatchProgress.episode_id == episode.id).all()

            task_content['video_file_list'] = [
                row2dict(video_file) for video_file in video_file_list
            ]

            task_content['task_step'] = ['db', 'torrent', 'file_system']

            task = Task(type=Task.TYPE_EPISODE_DELETE,
                        content=json.dumps(task_content),
                        status=Task.STATUS_IN_PROGRESS)
            session.add(task)
            session.commit()

            for video_file in video_file_list:
                session.delete(video_file)

            # remove watch-progress
            for watch_progress in watch_progress_list:
                session.delete(watch_progress)

            # remove episode
            session.delete(episode)

            self.__unshift_task_step(task_content, task, session)

            # remove torrent
            if len(task_content['video_file_list']) > 0:
                threads.blockingCallFromThread(
                    reactor, download_manager.remove_torrents,
                    task_content['video_file_list']['torrent_id'], True)

            self.__unshift_task_step(task_content, task, session)

            # remove files of episode
            bangumi_folder_path = '{0}/{1}'.format(self.base_path,
                                                   str(episode.bangumi_id))
            for torrent_file in task_content['video_file_list']:
                file_path = '{0}/{1}'.format(bangumi_folder_path,
                                             torrent_file['file_path'])
                os.remove(file_path)

            task_content['task_step'].pop(0)
            task.content = json.dumps(task_content)
            task.status = Task.STATUS_COMPLETE

            session.commit()
            return str(task.id)

        finally:
            SessionManager.Session.remove()
    def on_air_bangumi(self):
        session = SessionManager.Session()
        current_day = datetime.today()
        start_time = datetime(current_day.year, current_day.month, 1)
        if current_day.month == 12:
            next_year = current_day.year + 1
            next_month = 1
        else:
            next_year = current_day.year
            next_month = current_day.month + 1
        end_time = datetime(next_year, next_month, 1)

        try:
            result = session.query(distinct(Episode.bangumi_id), Bangumi).\
                join(Bangumi).\
                filter(Episode.airdate >= start_time).\
                filter(Episode.airdate <= end_time)

            bangumi_list = []
            for bangumi_id, bangumi in result:
                bangumi_dict = row2dict(bangumi)
                bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
                bangumi_list.append(bangumi_dict)

            return json_resp({'data': bangumi_list})
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #14
0
    def get_all_announce(self, position, offset, count, content):
        session = SessionManager.Session()
        try:
            if content is not None:
                announce_list = session.query(Announce).\
                    filter(Announce.content == content).\
                    all()
            else:
                announce_list = session.query(Announce).\
                    filter(Announce.position == position).\
                    offset(offset).\
                    limit(count).\
                    all()

            total = session.query(func.count(Announce.id)). \
                scalar()

            announce_dict_list = []

            for announce in announce_list:
                announce_dict = row2dict(announce)
                announce_dict_list.append(announce_dict)

            if position == Announce.POSITION_BANGUMI:
                self.__add_bangumi_info(session, announce_dict_list)

            return json_resp({'data': announce_dict_list, 'total': total})
        finally:
            SessionManager.Session.remove()
Exemple #15
0
    def list_episode(self, page, count, sort_field, sort_order, status):
        try:

            session = SessionManager.Session()
            query_object = session.query(Episode).\
                filter(Episode.delete_mark == None)

            if status is not None:
                query_object = query_object.filter(Episode.status==status)
                # count total rows
                total = session.query(func.count(Episode.id)).filter(Episode.status==status).scalar()
            else:
                total = session.query(func.count(Episode.id)).scalar()

            offset = (page - 1) * count

            if sort_order == 'desc':
                episode_list = query_object.\
                    order_by(desc(getattr(Episode, sort_field))).\
                    offset(offset).\
                    limit(count).\
                    all()
            else:
                episode_list = query_object.\
                    order_by(asc(getattr(Episode, sort_field))).\
                    offset(offset).limit(count).\
                    all()

            episode_dict_list = [row2dict(episode, Episode) for episode in episode_list]

            return json_resp({'data': episode_dict_list, 'total': total})
        finally:
            SessionManager.Session.remove()
Exemple #16
0
    def list_episode(self, page, count, sort_field, sort_order, status):
        try:

            session = SessionManager.Session()
            query_object = session.query(Episode)

            if status is not None:
                query_object = query_object.filter(Episode.status == status)
                # count total rows
                total = session.query(func.count(
                    Episode.id)).filter(Episode.status == status).scalar()
            else:
                total = session.query(func.count(Episode.id)).scalar()

            offset = (page - 1) * count

            if sort_order == 'desc':
                episode_list = query_object.\
                    order_by(desc(getattr(Episode, sort_field))).\
                    offset(offset).\
                    limit(count).\
                    all()
            else:
                episode_list = query_object.\
                    order_by(asc(getattr(Episode, sort_field))).\
                    offset(offset).limit(count).\
                    all()

            episode_dict_list = [row2dict(episode) for episode in episode_list]

            return json_resp({'data': episode_dict_list, 'total': total})
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()
Exemple #17
0
    def get_all_announce(self, position, offset, count, content):
        session = SessionManager.Session()
        try:
            if content:
                announce_list = session.query(Announce).\
                    filter(Announce.content == content).\
                    all()
            else:
                announce_list = session.query(Announce).\
                    filter(Announce.position == position).\
                    offset(offset).\
                    limit(count).\
                    all()

            total = session.query(func.count(Announce.id)). \
                scalar()

            announce_dict_list = []

            for announce in announce_list:
                announce_dict = row2dict(announce, Announce)
                announce_dict_list.append(announce_dict)

            if position == Announce.POSITION_BANGUMI:
                self.__add_bangumi_info(session, announce_dict_list)

            return json_resp({'data': announce_dict_list, 'total': total})
        finally:
            SessionManager.Session.remove()
Exemple #18
0
    def list_pending_delete_banguimi(self):
        try:
            current = datetime.now()
            session = SessionManager.Session()
            bangumi_list = session.query(Bangumi).\
                filter(Bangumi.delete_mark != None).\
                all()

            bgm_list = []
            for bangumi in bangumi_list:
                bgm = row2dict(bangumi)
                # noinspection PyTypeChecker
                delete_eta = int(
                    (bangumi.delete_mark +
                     timedelta(minutes=self.delete_delay['bangumi']) -
                     current).total_seconds() / 60)
                bgm['delete_eta'] = delete_eta
                bgm_list.append(bgm)

            return json_resp({
                'data': bgm_list,
                'delete_delay': self.delete_delay['bangumi']
            })
        finally:
            SessionManager.Session.remove()
Exemple #19
0
    def list_bangumi(self, page, count, sort_field, sort_order, name, user_id,
                     bangumi_type):
        try:

            session = SessionManager.Session()
            query_object = session.query(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None)

            if bangumi_type != -1:
                query_object = query_object.filter(
                    Bangumi.type == bangumi_type)

            if name is not None:
                name_pattern = '%{0}%'.format(name.encode('utf-8'), )
                logger.debug(name_pattern)
                query_object = query_object.\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern)))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern))).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            if sort_order == 'desc':
                query_object = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field)))

            else:
                query_object = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field)))

            if count == -1:
                bangumi_list = query_object.all()
            else:
                offset = (page - 1) * count
                bangumi_list = query_object.offset(offset).limit(count).all()

            bangumi_id_list = [bgm.id for bgm in bangumi_list]

            favorites = session.query(Favorites).\
                filter(Favorites.bangumi_id.in_(bangumi_id_list)).\
                filter(Favorites.user_id == user_id).\
                all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                utils.process_bangumi_dict(bgm, bangumi)
                for fav in favorites:
                    if fav.bangumi_id == bgm.id:
                        bangumi['favorite_status'] = fav.status
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
        finally:
            SessionManager.Session.remove()
Exemple #20
0
 def query_episode():
     session = SessionManager.Session()
     try:
         (episode, bangumi) = session.query(Episode, Bangumi). \
             join(Bangumi). \
             options(joinedload(Bangumi.cover_image)). \
             options(joinedload(Episode.thumbnail_image)). \
             filter(Episode.delete_mark == None). \
             filter(Episode.id == episode_id).\
             one()
         episode_dict = row2dict(episode, Episode)
         episode_dict['bangumi'] = row2dict(bangumi, Bangumi)
         utils.process_bangumi_dict(bangumi, episode_dict['bangumi'])
         utils.process_episode_dict(episode, episode_dict)
         return episode_dict
     finally:
         SessionManager.Session.remove()
Exemple #21
0
 def list_task(self):
     try:
         session = SessionManager.Session()
         result = session.query(Task).all()
         task_list = [row2dict(task, Task) for task in result]
         return json_resp({'data': task_list})
     finally:
         SessionManager.Session.remove()
Exemple #22
0
 def list_task(self):
     try:
         session = SessionManager.Session()
         result = session.query(Task).all()
         task_list = [row2dict(task) for task in result]
         return json_resp({'data': task_list})
     finally:
         SessionManager.Session.remove()
Exemple #23
0
 def query_episode():
     session = SessionManager.Session()
     try:
         (episode, bangumi) = session.query(Episode, Bangumi). \
             join(Bangumi). \
             options(joinedload(Bangumi.cover_image)). \
             options(joinedload(Episode.thumbnail_image)). \
             filter(Episode.delete_mark == None). \
             filter(Episode.id == episode_id).\
             one()
         episode_dict = row2dict(episode, Episode)
         episode_dict['bangumi'] = row2dict(bangumi, Bangumi)
         utils.process_bangumi_dict(bangumi, episode_dict['bangumi'])
         utils.process_episode_dict(episode, episode_dict)
         return episode_dict
     finally:
         SessionManager.Session.remove()
Exemple #24
0
    def episode_detail(self, episode_id, user_id):
        session = SessionManager.Session()
        try:
            (episode, bangumi) = session.query(Episode, Bangumi).\
                join(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                options(joinedload(Episode.thumbnail_image)).\
                filter(Episode.delete_mark == None).\
                filter(Episode.id == episode_id).\
                one()
            watch_progress = session.query(WatchProgress).\
                filter(WatchProgress.episode_id == episode_id).\
                filter(WatchProgress.user_id == user_id).\
                first()

            episode_dict = row2dict(episode, Episode)
            episode_dict['bangumi'] = row2dict(bangumi, Bangumi)
            episode_dict['bangumi']['cover'] = utils.generate_cover_link(
                bangumi)
            utils.process_bangumi_dict(bangumi, episode_dict['bangumi'])
            episode_dict['thumbnail'] = utils.generate_thumbnail_link(
                episode, bangumi)
            utils.process_episode_dict(episode, episode_dict)

            if watch_progress is not None:
                episode_dict['watch_progress'] = row2dict(
                    watch_progress, WatchProgress)

            if episode.status == Episode.STATUS_DOWNLOADED:
                episode_dict['video_files'] = []
                video_file_list = session.query(VideoFile).filter(
                    VideoFile.episode_id == episode_id).all()
                for video_file in video_file_list:
                    if video_file.status != VideoFile.STATUS_DOWNLOADED:
                        continue
                    video_file_dict = row2dict(video_file, VideoFile)
                    video_file_dict['url'] = utils.generate_video_link(
                        str(bangumi.id), video_file.file_path)
                    episode_dict['video_files'].append(video_file_dict)

            return json_resp(episode_dict)
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #25
0
    def list_bangumi(self, page, count, sort_field, sort_order, name, user_id, bangumi_type):
        try:

            session = SessionManager.Session()
            query_object = session.query(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None)

            if bangumi_type != -1:
                query_object = query_object.filter(Bangumi.type == bangumi_type)

            if name is not None:
                name_pattern = '%{0}%'.format(name.encode('utf-8'),)
                logger.debug(name_pattern)
                query_object = query_object.\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern)))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern))).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            if sort_order == 'desc':
                query_object = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field)))

            else:
                query_object = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field)))

            if count == -1:
                bangumi_list = query_object.all()
            else:
                offset = (page - 1) * count
                bangumi_list = query_object.offset(offset).limit(count).all()

            bangumi_id_list = [bgm.id for bgm in bangumi_list]

            favorites = session.query(Favorites).\
                filter(Favorites.bangumi_id.in_(bangumi_id_list)).\
                filter(Favorites.user_id == user_id).\
                all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm, Bangumi)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                utils.process_bangumi_dict(bgm, bangumi)
                for fav in favorites:
                    if fav.bangumi_id == bgm.id:
                        bangumi['favorite_status'] = fav.status
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
        finally:
            SessionManager.Session.remove()
Exemple #26
0
    def feed_back(self, episode_id, video_file_id, user, message):
        from server import app
        session = SessionManager.Session()
        try:
            episode = session.query(Episode).\
                options(joinedload(Episode.bangumi)).\
                options(joinedload(Episode.video_files)).\
                filter(Episode.id == episode_id).\
                one()
            episode_dict = row2dict(episode, Episode)
            episode_dict['bangumi'] = row2dict(episode.bangumi, Bangumi)
            episode_dict['video_files'] = []
            for video_file in episode.video_files:
                video_file_dict = row2dict(video_file, VideoFile)
                episode_dict['video_files'].append(video_file_dict)

            bangumi_url = '{0}://{1}/admin/bangumi/{2}'.format(
                app.config['SITE_PROTOCOL'], app.config['SITE_HOST'],
                episode_dict['bangumi_id'])

            maintained_by_uid = episode_dict['bangumi'].get(
                'maintained_by_uid')
            if maintained_by_uid is None:
                # find all admin
                admin_list = session.query(User).\
                    filter(User.level >= 2).\
                    all()

                self.__send_email_to_all(bangumi_url,
                                         episode_dict, video_file_id,
                                         row2dict(user,
                                                  User), admin_list, message)
            else:
                admin = session.query(User).\
                    filter(User.id == maintained_by_uid).\
                    one()
                self.__send_email_to(bangumi_url, episode_dict, video_file_id,
                                     row2dict(user, User), admin, message)

            return json_resp({'message': 'ok'})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #27
0
 def query_token():
     session = SessionManager.Session()
     try:
         token_list = session.query(WebHookToken).\
             options(joinedload(WebHookToken.web_hook)).\
             filter(WebHookToken.user_id == user_id).\
             all()
         token_dict_list = []
         for token in token_list:
             if token.web_hook.status == WebHook.STATUS_IS_DEAD:
                 continue
             if not token.web_hook.has_permission(WebHook.PERMISSION_EMAIL):
                 continue
             token_dict = row2dict(token, WebHookToken)
             token_dict['web_hook'] = row2dict(token.web_hook, WebHook)
             token_dict_list.append(token_dict)
         return token_dict_list
     finally:
         SessionManager.Session.remove()
Exemple #28
0
 def query_token():
     session = SessionManager.Session()
     try:
         token_list = session.query(WebHookToken).\
             options(joinedload(WebHookToken.web_hook)).\
             filter(WebHookToken.user_id == user_id).\
             all()
         token_dict_list = []
         for token in token_list:
             if token.web_hook.status == WebHook.STATUS_IS_DEAD:
                 continue
             if not token.web_hook.has_permission(WebHook.PERMISSION_EMAIL):
                 continue
             token_dict = row2dict(token, WebHookToken)
             token_dict['web_hook'] = row2dict(token.web_hook, WebHook)
             token_dict_list.append(token_dict)
         return token_dict_list
     finally:
         SessionManager.Session.remove()
Exemple #29
0
    def get_episode_video_file_list(self, episode_id):
        try:
            session = SessionManager.Session()
            video_file_list = session.query(VideoFile).\
                filter(VideoFile.episode_id == episode_id).\
                all()

            result = [row2dict(video_file, VideoFile) for video_file in video_file_list]
            return json_resp({'data': result})
        finally:
            SessionManager.Session.remove()
Exemple #30
0
    def get_episode_video_file_list(self, episode_id):
        try:
            session = SessionManager.Session()
            video_file_list = session.query(VideoFile).\
                filter(VideoFile.episode_id == episode_id).\
                all()

            result = [row2dict(video_file) for video_file in video_file_list]
            return json_resp({'data': result})
        finally:
            SessionManager.Session.remove()
Exemple #31
0
    def list_pending_delete_episode(self):
        try:
            current = datetime.utcnow()
            session = SessionManager.Session()
            result = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.delete_mark != None).\
                all()

            eps_list = []
            for episode, bangumi in result:
                bgm = row2dict(bangumi, Bangumi)
                eps = row2dict(episode. Episode)
                # noinspection PyTypeChecker
                delete_eta = int((episode.delete_mark + timedelta(minutes=self.delete_delay['episode']) - current).total_seconds() / 60)
                eps['delete_eta'] = delete_eta
                eps['bangumi'] = bgm
                eps_list.append(eps)
            return json_resp({'data': eps_list, 'delete_delay': self.delete_delay['episode']})
        finally:
            SessionManager.Session.remove()
Exemple #32
0
    def episode_detail(self, episode_id, user_id):
        session = SessionManager.Session()
        try:
            (episode, bangumi) = session.query(Episode, Bangumi).\
                join(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                options(joinedload(Episode.thumbnail_image)).\
                filter(Episode.delete_mark == None).\
                filter(Episode.id == episode_id).\
                one()
            watch_progress = session.query(WatchProgress).\
                filter(WatchProgress.episode_id == episode_id).\
                filter(WatchProgress.user_id == user_id).\
                first()

            episode_dict = row2dict(episode, Episode)
            episode_dict['bangumi'] = row2dict(bangumi, Bangumi)
            episode_dict['bangumi']['cover'] = utils.generate_cover_link(bangumi)
            utils.process_bangumi_dict(bangumi, episode_dict['bangumi'])
            episode_dict['thumbnail'] = utils.generate_thumbnail_link(episode, bangumi)
            utils.process_episode_dict(episode, episode_dict)

            if watch_progress is not None:
                episode_dict['watch_progress'] = row2dict(watch_progress, WatchProgress)

            if episode.status == Episode.STATUS_DOWNLOADED:
                episode_dict['video_files'] = []
                video_file_list = session.query(VideoFile).filter(VideoFile.episode_id == episode_id).all()
                for video_file in video_file_list:
                    if video_file.status != VideoFile.STATUS_DOWNLOADED:
                        continue
                    video_file_dict = row2dict(video_file, VideoFile)
                    video_file_dict['url'] = utils.generate_video_link(str(bangumi.id), video_file.file_path)
                    episode_dict['video_files'].append(video_file_dict)

            return json_resp(episode_dict)
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #33
0
    def list_bangumi(self, page, count, sort_field, sort_order, name,
                     bangumi_type):
        try:
            session = SessionManager.Session()
            query_object = session.query(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                options(joinedload(Bangumi.created_by)).\
                options(joinedload(Bangumi.maintained_by)).\
                filter(Bangumi.delete_mark == None)

            if bangumi_type != -1:
                query_object = query_object.filter(
                    Bangumi.type == bangumi_type)

            if name is not None:
                name_pattern = '%{0}%'.format(name.encode('utf-8'), )
                logger.debug(name_pattern)
                query_object = query_object.\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern)))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern))).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            if sort_order == 'desc':
                query_object = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field)))
            else:
                query_object = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field)))

            # we now support query all method by passing count = -1
            if count == -1:
                bangumi_list = query_object.all()
            else:
                offset = (page - 1) * count
                bangumi_list = query_object.offset(offset).limit(count).all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                utils.process_bangumi_dict(bgm, bangumi)
                self.__process_user_obj_in_bangumi(bgm, bangumi)
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
            # raise ClientError('something happened')
        finally:
            SessionManager.Session.remove()
Exemple #34
0
    def get_available_announce(self):
        session = SessionManager.Session()
        current_time = datetime.utcnow()
        try:
            announce_list = session.query(Announce).\
                filter(Announce.start_time <= current_time).\
                filter(Announce.end_time >= current_time).\
                all()

            return json_resp(
                {'data': [row2dict(announce) for announce in announce_list]})
        finally:
            SessionManager.Session.remove()
Exemple #35
0
    def get_web_hook_by_id(self, web_hook_id):
        session = SessionManager.Session()
        try:
            web_hook = session.query(WebHook).\
                filter(WebHook.id == web_hook_id).\
                one()
            web_hook_dict = row2dict(web_hook, WebHook)
            web_hook_dict.pop('shared_secret', None)
            web_hook_dict.pop('created_by_uid', None)

            return json_resp({'data': web_hook_dict})
        finally:
            SessionManager.Session.remove()
Exemple #36
0
    def feed_back(self, episode_id, video_file_id, user, message):
        from server import app
        session = SessionManager.Session()
        try:
            episode = session.query(Episode).\
                options(joinedload(Episode.bangumi)).\
                options(joinedload(Episode.video_files)).\
                filter(Episode.id == episode_id).\
                one()
            episode_dict = row2dict(episode, Episode)
            episode_dict['bangumi'] = row2dict(episode.bangumi, Bangumi)
            episode_dict['video_files'] = []
            for video_file in episode.video_files:
                video_file_dict = row2dict(video_file, VideoFile)
                episode_dict['video_files'].append(video_file_dict)

            bangumi_url = '{0}://{1}/admin/bangumi/{2}'.format(app.config['SITE_PROTOCOL'],
                                                               app.config['SITE_HOST'],
                                                               episode_dict['bangumi_id'])

            maintained_by_uid = episode_dict['bangumi'].get('maintained_by_uid')
            if maintained_by_uid is None:
                # find all admin
                admin_list = session.query(User).\
                    filter(User.level >= 2).\
                    all()

                self.__send_email_to_all(bangumi_url, episode_dict, video_file_id, row2dict(user, User), admin_list, message)
            else:
                admin = session.query(User).\
                    filter(User.id == maintained_by_uid).\
                    one()
                self.__send_email_to(bangumi_url, episode_dict, video_file_id, row2dict(user, User), admin, message)

            return json_resp({'message': 'ok'})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #37
0
    def get_episode(self, episode_id):
        try:
            session = SessionManager.Session()
            episode = session.query(Episode).filter(Episode.id == episode_id).one()
            episode_dict = row2dict(episode)

            return json_resp({'data': episode_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #38
0
 def get_available_announce(self):
     session = SessionManager.Session()
     current_time = datetime.utcnow()
     try:
         announce_list = session.query(Announce).\
             filter(Announce.start_time <= current_time).\
             filter(Announce.end_time >= current_time).\
             all()
         announce_dict_list = [row2dict(announce, Announce) for announce in announce_list]
         self.__add_bangumi_info(session, announce_dict_list)
         return json_resp({'data': announce_dict_list})
     finally:
         SessionManager.Session.remove()
Exemple #39
0
    def episode_detail(self, episode_id):
        session = SessionManager.Session()
        try:
            (episode, bangumi) = session.query(Episode, Bangumi).\
                join(Bangumi).\
                filter(Episode.id == episode_id).one()
            episode_dict = row2dict(episode)
            episode_dict['bangumi'] = row2dict(bangumi)
            episode_dict['thumbnail'] = utils.generate_thumbnail_link(episode, bangumi)

            if episode.status == Episode.STATUS_DOWNLOADED:
                episode_dict['videos'] = []
                torrent_file_cur = session.query(TorrentFile).filter(TorrentFile.episode_id == episode_id)
                for torrent_file in torrent_file_cur:
                    episode_dict['videos'].append(utils.generate_video_link(str(bangumi.id), torrent_file.file_path))

            return json_resp(episode_dict)
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as error:
            raise error
        finally:
            SessionManager.Session.remove()
Exemple #40
0
    def list_bangumi(self, page, count, sort_field, sort_order, name, bangumi_type):
        try:
            session = SessionManager.Session()
            query_object = session.query(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                options(joinedload(Bangumi.created_by)).\
                options(joinedload(Bangumi.maintained_by)).\
                filter(Bangumi.delete_mark == None)

            if bangumi_type != -1:
                query_object = query_object.filter(Bangumi.type == bangumi_type)

            if name is not None:
                name_pattern = '%{0}%'.format(name.encode('utf-8'),)
                logger.debug(name_pattern)
                query_object = query_object.\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern)))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name.ilike(name_pattern), Bangumi.name_cn.ilike(name_pattern))).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            if sort_order == 'desc':
                query_object = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field)))
            else:
                query_object = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field)))

            # we now support query all method by passing count = -1
            if count == -1:
                bangumi_list = query_object.all()
            else:
                offset = (page - 1) * count
                bangumi_list = query_object.offset(offset).limit(count).all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm, Bangumi)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                utils.process_bangumi_dict(bgm, bangumi)
                self.__process_user_obj_in_bangumi(bgm, bangumi)
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
            # raise ClientError('something happened')
        finally:
            SessionManager.Session.remove()
Exemple #41
0
    def get_bangumi(self, id):
        try:
            session = SessionManager.Session()

            bangumi = session.query(Bangumi).\
                options(joinedload(Bangumi.episodes).joinedload(Episode.thumbnail_image)).\
                options(joinedload(Bangumi.cover_image)). \
                options(joinedload(Bangumi.created_by)). \
                options(joinedload(Bangumi.maintained_by)). \
                filter(Bangumi.id == id).\
                filter(Bangumi.delete_mark == None).\
                one()

            episodes = []

            for episode in bangumi.episodes:
                if episode.delete_mark is not None:
                    continue
                eps = row2dict(episode, Episode)
                eps['thumbnail'] = utils.generate_thumbnail_link(episode, bangumi)
                utils.process_episode_dict(episode, eps)
                episodes.append(eps)

            bangumi_dict = row2dict(bangumi, Bangumi)

            bangumi_dict['episodes'] = episodes
            utils.process_bangumi_dict(bangumi, bangumi_dict)
            self.__process_user_obj_in_bangumi(bangumi, bangumi_dict)
            bangumi_dict['cover'] = utils.generate_cover_link(bangumi)

            return json_resp({'data': bangumi_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()
Exemple #42
0
    def my_favorites(self, user_id, status=None):
        session = SessionManager.Session()
        try:
            q = session.query(Favorites, Bangumi).\
                join(Bangumi).\
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None).\
                filter(Favorites.user_id == user_id)

            if status is None:
                result = q.all()
            else:
                result = q.filter(Favorites.status == status).all()

            bangumi_id_list = [bangumi.id for favorite, bangumi in result]
            # print 'bangumi_id_list length: %d' % len(bangumi_id_list)
            if len(bangumi_id_list) == 0:
                return json_resp({'data': [], 'status': 0})

            # subquery for watch_progress
            watch_progress = session.query(WatchProgress.episode_id).\
                filter(WatchProgress.user_id == user_id).\
                filter(WatchProgress.bangumi_id.in_(bangumi_id_list))

            episode_count = session.query(func.count(Episode.id), Episode.bangumi_id).\
                filter(Episode.status == Episode.STATUS_DOWNLOADED).\
                filter(Episode.bangumi_id.in_(bangumi_id_list)).\
                filter(~Episode.id.in_(watch_progress)).\
                group_by(Episode.bangumi_id).\
                all()

            logger.debug(episode_count)
            bangumi_dict_list = []

            for fav, bgm in result:
                bangumi_dict = row2dict(bgm)
                bangumi_dict['favorite_status'] = fav.status
                bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
                utils.process_bangumi_dict(bgm, bangumi_dict)
                for unwatched_count, bangumi_id in episode_count:
                    if bangumi_id == bgm.id:
                        bangumi_dict['unwatched_count'] = unwatched_count
                        break
                bangumi_dict_list.append(bangumi_dict)

            return json_resp({'data': bangumi_dict_list, 'status': 0})

        finally:
            SessionManager.Session.remove()
Exemple #43
0
    def get_web_hook_by_id(self, web_hook_id):
        session = SessionManager.Session()
        try:
            web_hook = session.query(WebHook).\
                filter(WebHook.id == web_hook_id).\
                one()
            web_hook_dict = row2dict(web_hook, WebHook)
            web_hook_dict.pop('shared_secret', None)
            web_hook_dict.pop('created_by_uid', None)

            return json_resp({
                'data': web_hook_dict
            })
        finally:
            SessionManager.Session.remove()
Exemple #44
0
    def revive(self, web_hook_id, token_id_list, signature):
        session = SessionManager.Session()
        try:
            # reset its status
            web_hook = session.query(WebHook).\
                filter(WebHook.id == web_hook_id).\
                one()

            if signature != self.__get_hmac_hash(web_hook.shared_secret,
                                                 web_hook_id, token_id_list):
                raise ClientError('Authenticate Failed', 401)

            web_hook.status = WebHook.STATUS_IS_ALIVE
            session.commit()

            fav_dict_list = []
            if len(token_id_list) > 0:
                web_hook_token_list = session.query(WebHookToken).\
                    filter(WebHookToken.web_hook_id == web_hook_id).\
                    filter(WebHookToken.token_id.in_(token_id_list)).\
                    all()

                user_id_list = [
                    web_hook.user_id for web_hook in web_hook_token_list
                ]

                favorites_list = session.query(Favorites).\
                    filter(Favorites.user_id.in_(user_id_list)).\
                    group_by(Favorites.user_id, Favorites.id).\
                    all()

                for favorite in favorites_list:
                    fav_dict = row2dict(favorite, Favorites)
                    for web_hook in web_hook_token_list:
                        if fav_dict['user_id'] == web_hook.user_id:
                            fav_dict['token_id'] = web_hook.token_id
                            break
                    fav_dict.pop('user_id', None)
                    fav_dict_list.append(fav_dict)

            return json_resp({'data': fav_dict_list})
        except NoResultFound as error:
            logger.warn(error, exc_info=True)
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #45
0
    def get_episode(self, episode_id):
        try:
            session = SessionManager.Session()
            episode = session.query(Episode).\
                options(joinedload(Episode.thumbnail_image)).\
                filter(Episode.id == episode_id).\
                filter(Episode.delete_mark == None).\
                all()

            episode_dict = row2dict(episode)
            utils.process_episode_dict(episode, episode_dict)

            return json_resp({'data': episode_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #46
0
    def on_air_bangumi(self, user_id, type):
        session = SessionManager.Session()
        current_day = datetime.today()
        start_time = datetime(current_day.year, current_day.month, 1)
        if current_day.month == 12:
            next_year = current_day.year + 1
            next_month = 1
        else:
            next_year = current_day.year
            next_month = current_day.month + 1
        end_time = datetime(next_year, next_month, 1)

        try:
            result = session.query(distinct(Episode.bangumi_id), Bangumi).\
                join(Bangumi). \
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None). \
                filter(Bangumi.type == type).\
                filter(Episode.airdate >= start_time).\
                filter(Episode.airdate <= end_time). \
                order_by(desc(getattr(Bangumi, 'air_date')))

            bangumi_list = []
            bangumi_id_list = [bangumi_id for bangumi_id, bangumi in result]

            if len(bangumi_id_list) == 0:
                return json_resp({'data': []})

            favorites = session.query(Favorites).\
                filter(Favorites.bangumi_id.in_(bangumi_id_list)).\
                filter(Favorites.user_id == user_id).\
                all()

            for bangumi_id, bangumi in result:
                bangumi_dict = row2dict(bangumi, Bangumi)
                bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
                utils.process_bangumi_dict(bangumi, bangumi_dict)
                for fav in favorites:
                    if fav.bangumi_id == bangumi_id:
                        bangumi_dict['favorite_status'] = fav.status
                        break
                bangumi_list.append(bangumi_dict)

            return json_resp({'data': bangumi_list})
        finally:
            SessionManager.Session.remove()
Exemple #47
0
    def on_air_bangumi(self, user_id, type):
        session = SessionManager.Session()
        current_day = datetime.today()
        start_time = datetime(current_day.year, current_day.month, 1)
        if current_day.month == 12:
            next_year = current_day.year + 1
            next_month = 1
        else:
            next_year = current_day.year
            next_month = current_day.month + 1
        end_time = datetime(next_year, next_month, 1)

        try:
            result = session.query(distinct(Episode.bangumi_id), Bangumi).\
                join(Bangumi). \
                options(joinedload(Bangumi.cover_image)).\
                filter(Bangumi.delete_mark == None). \
                filter(Bangumi.type == type).\
                filter(Episode.airdate >= start_time).\
                filter(Episode.airdate <= end_time). \
                order_by(desc(getattr(Bangumi, 'air_date')))

            bangumi_list = []
            bangumi_id_list = [bangumi_id for bangumi_id, bangumi in result]

            if len(bangumi_id_list) == 0:
                return json_resp({'data': []})

            favorites = session.query(Favorites).\
                filter(Favorites.bangumi_id.in_(bangumi_id_list)).\
                filter(Favorites.user_id == user_id).\
                all()

            for bangumi_id, bangumi in result:
                bangumi_dict = row2dict(bangumi)
                bangumi_dict['cover'] = utils.generate_cover_link(bangumi)
                utils.process_bangumi_dict(bangumi, bangumi_dict)
                for fav in favorites:
                    if fav.bangumi_id == bangumi_id:
                        bangumi_dict['favorite_status'] = fav.status
                        break
                bangumi_list.append(bangumi_dict)

            return json_resp({'data': bangumi_list})
        finally:
            SessionManager.Session.remove()
Exemple #48
0
 def __add_bangumi_info(self, session, announce_dict_list):
     bangumi_id_list = []
     for announce_dict in announce_dict_list:
         if announce_dict['position'] == Announce.POSITION_BANGUMI:
             bangumi_id_list.append(announce_dict['content'])
     if len(bangumi_id_list) == 0:
         return
     bangumi_list = session.query(Bangumi).\
         options(joinedload(Bangumi.cover_image)).\
         filter(Bangumi.id.in_(bangumi_id_list)).\
         all()
     for bangumi in bangumi_list:
         for announce_dict in announce_dict_list:
             if announce_dict['content'] == str(bangumi.id):
                 announce_dict['bangumi'] = row2dict(bangumi, Bangumi)
                 utils.process_bangumi_dict(bangumi, announce_dict['bangumi'])
                 break
Exemple #49
0
    def get_episode(self, episode_id):
        try:
            session = SessionManager.Session()
            episode = session.query(Episode).\
                options(joinedload(Episode.thumbnail_image)).\
                filter(Episode.id == episode_id).\
                filter(Episode.delete_mark == None).\
                all()

            episode_dict = row2dict(episode, Episode)
            utils.process_episode_dict(episode, episode_dict)

            return json_resp({'data': episode_dict})
        except NoResultFound:
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #50
0
 def __add_bangumi_info(self, session, announce_dict_list):
     bangumi_id_list = []
     for announce_dict in announce_dict_list:
         if announce_dict['position'] == Announce.POSITION_BANGUMI:
             bangumi_id_list.append(announce_dict['content'])
     if len(bangumi_id_list) == 0:
         return
     bangumi_list = session.query(Bangumi).\
         options(joinedload(Bangumi.cover_image)).\
         filter(Bangumi.id.in_(bangumi_id_list)).\
         all()
     for bangumi in bangumi_list:
         for announce_dict in announce_dict_list:
             if announce_dict['content'] == str(bangumi.id):
                 announce_dict['bangumi'] = row2dict(bangumi)
                 utils.process_bangumi_dict(bangumi,
                                            announce_dict['bangumi'])
                 break
Exemple #51
0
    def query_user_favorite():
        session = SessionManager.Session()
        try:
            favorite_list = session.query(Favorites). \
                filter(Favorites.user_id == user_id). \
                all()

            fav_dict_list = []

            for favorite in favorite_list:
                fav_dict = row2dict(favorite, Favorites)
                fav_dict['token_id'] = token_id
                fav_dict.pop('user_id', None)
                fav_dict_list.append(fav_dict)

            return fav_dict_list
        finally:
            SessionManager.Session.remove()
Exemple #52
0
    def query_user_favorite():
        session = SessionManager.Session()
        try:
            favorite_list = session.query(Favorites). \
                filter(Favorites.user_id == user_id). \
                all()

            fav_dict_list = []

            for favorite in favorite_list:
                fav_dict = row2dict(favorite, Favorites)
                fav_dict['token_id'] = token_id
                fav_dict.pop('user_id', None)
                fav_dict_list.append(fav_dict)

            return fav_dict_list
        finally:
            SessionManager.Session.remove()
Exemple #53
0
    def revive(self, web_hook_id, token_id_list, signature):
        session = SessionManager.Session()
        try:
            # reset its status
            web_hook = session.query(WebHook).\
                filter(WebHook.id == web_hook_id).\
                one()

            if signature != self.__get_hmac_hash(web_hook.shared_secret, web_hook_id, token_id_list):
                raise ClientError('Authenticate Failed', 401)

            web_hook.status = WebHook.STATUS_IS_ALIVE
            session.commit()

            fav_dict_list = []
            if len(token_id_list) > 0:
                web_hook_token_list = session.query(WebHookToken).\
                    filter(WebHookToken.web_hook_id == web_hook_id).\
                    filter(WebHookToken.token_id.in_(token_id_list)).\
                    all()

                user_id_list = [web_hook.user_id for web_hook in web_hook_token_list]

                favorites_list = session.query(Favorites).\
                    filter(Favorites.user_id.in_(user_id_list)).\
                    group_by(Favorites.user_id, Favorites.id).\
                    all()

                for favorite in favorites_list:
                    fav_dict = row2dict(favorite, Favorites)
                    for web_hook in web_hook_token_list:
                        if fav_dict['user_id'] == web_hook.user_id:
                            fav_dict['token_id'] = web_hook.token_id
                            break
                    fav_dict.pop('user_id', None)
                    fav_dict_list.append(fav_dict)

            return json_resp({'data': fav_dict_list})
        except NoResultFound as error:
            logger.warn(error, exc_info=True)
            raise ClientError(ClientError.NOT_FOUND, 404)
        finally:
            SessionManager.Session.remove()
Exemple #54
0
    def list_pending_delete_banguimi(self):
        try:
            current = datetime.utcnow()
            session = SessionManager.Session()
            bangumi_list = session.query(Bangumi).\
                filter(Bangumi.delete_mark != None).\
                all()

            bgm_list = []
            for bangumi in bangumi_list:
                bgm = row2dict(bangumi, Bangumi)
                # noinspection PyTypeChecker
                delete_eta = int((bangumi.delete_mark + timedelta(minutes=self.delete_delay['bangumi']) - current).total_seconds() / 60)
                bgm['delete_eta'] = delete_eta
                bgm_list.append(bgm)

            return json_resp({'data': bgm_list, 'delete_delay': self.delete_delay['bangumi']})
        finally:
            SessionManager.Session.remove()
Exemple #55
0
    def list_bangumi(self, page, count, sort_field, sort_order, name):
        try:

            session = SessionManager.Session()
            query_object = session.query(Bangumi)

            if name is not None:
                name_pattern = '%{0}%'.format(name.encode('utf-8'), )
                logger.debug(name_pattern)
                query_object = query_object.\
                    filter(or_(Bangumi.name.like(name_pattern), Bangumi.name_cn.like(name_pattern)))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name.like(name_pattern), Bangumi.name_cn.like(name_pattern))).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            offset = (page - 1) * count

            if sort_order == 'desc':
                bangumi_list = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field))).\
                    offset(offset).limit(count).\
                    all()
            else:
                bangumi_list = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field))).\
                    offset(offset).limit(count).\
                    all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()
Exemple #56
0
    def list_web_hook_by_user(self, user_id):
        session = SessionManager.Session()
        try:
            web_hook_token_list = session.query(WebHookToken).\
                options(joinedload(WebHookToken.web_hook)).\
                filter(WebHookToken.user_id == user_id).\
                all()

            web_hook_dict_list = []
            for web_hook_token in web_hook_token_list:
                web_hook_dict = row2dict(web_hook_token.web_hook, WebHook)
                web_hook_dict.pop('shared_secret', None)
                web_hook_dict_list.append(web_hook_dict)

            return json_resp({
                'data': web_hook_dict_list,
                'total': len(web_hook_token_list)
            })
        finally:
            SessionManager.Session.remove()
Exemple #57
0
    def list_web_hook_by_user(self, user_id):
        session = SessionManager.Session()
        try:
            web_hook_token_list = session.query(WebHookToken).\
                options(joinedload(WebHookToken.web_hook)).\
                filter(WebHookToken.user_id == user_id).\
                all()

            web_hook_dict_list = []
            for web_hook_token in web_hook_token_list:
                web_hook_dict = row2dict(web_hook_token.web_hook, WebHook)
                web_hook_dict.pop('shared_secret', None)
                web_hook_dict_list.append(web_hook_dict)

            return json_resp({
                'data': web_hook_dict_list,
                'total': len(web_hook_token_list)
            })
        finally:
            SessionManager.Session.remove()
Exemple #58
0
    def list_web_hook(self):
        session = SessionManager.Session()
        try:
            web_hook_list = session.query(WebHook).\
                options(joinedload(WebHook.created_by)).\
                order_by(desc(getattr(WebHook, 'register_time'))).\
                all()
            web_hook_dict_list = []

            for web_hook in web_hook_list:
                web_hook_dict = row2dict(web_hook, WebHook)
                web_hook_dict.pop('shared_secret', None)
                self.__process_user_obj_in_web_hook(web_hook, web_hook_dict)
                web_hook_dict_list.append(web_hook_dict)

            return json_resp({
                'data': web_hook_dict_list,
                'total': len(web_hook_list)
            })
        finally:
            SessionManager.Session.remove()
Exemple #59
0
    def list_bangumi(self, page, count, sort_field, sort_order, name):
        try:

            session = SessionManager.Session()
            query_object = session.query(Bangumi)

            if name is not None:
                query_object = query_object.\
                    filter(or_(Bangumi.name==name, Bangumi.name_cn==name))
                # count total rows
                total = session.query(func.count(Bangumi.id)).\
                    filter(or_(Bangumi.name==name, Bangumi.name_cn==name)).\
                    scalar()
            else:
                total = session.query(func.count(Bangumi.id)).scalar()

            offset = (page - 1) * count

            if sort_order == 'desc':
                bangumi_list = query_object.\
                    order_by(desc(getattr(Bangumi, sort_field))).\
                    offset(offset).limit(count).\
                    all()
            else:
                bangumi_list = query_object.\
                    order_by(asc(getattr(Bangumi, sort_field))).\
                    offset(offset).limit(count).\
                    all()

            bangumi_dict_list = []
            for bgm in bangumi_list:
                bangumi = row2dict(bgm)
                bangumi['cover'] = utils.generate_cover_link(bgm)
                bangumi_dict_list.append(bangumi)

            return json_resp({'data': bangumi_dict_list, 'total': total})
        except Exception as exception:
            raise exception
        finally:
            SessionManager.Session.remove()