def get_likes(cls, match_status: MatchStatus) -> SelectQuery:
     """
     获取点赞用户列表
     :param match_status:
     :return:
     """
     return match_status.get_likes()
    def post(self, match_id, status_id):
        match = Match.get_or_404(id=match_id)
        status = MatchStatus.get_or_404(id=status_id)
        delete_photo_keys = self.get_argument("delete-photo-keys", "")

        form = MatchStatusForm(self.arguments)

        if not form.validate():
            self.render("match/statuses_edit.html",
                        match=match,
                        status=status,
                        form=form)
        else:
            if delete_photo_keys:
                delete_photo_keys_list = delete_photo_keys.split(",")
            else:
                delete_photo_keys_list = []

            if "photos" in self.request.files:
                photo_keys_list = self.upload_photos(match_id)
            else:
                photo_keys_list = []

            new_photos_set = set(status.photos) ^ set(delete_photo_keys_list)
            new_photos_set = new_photos_set.union(set(photo_keys_list))

            form.populate_obj(status)
            status.photos = list(new_photos_set)
            status.save()

            self.redirect(self.reverse_url("admin_match_statuses", match_id))
 def undo_like(cls, user_id: int, match_status: MatchStatus)\
         -> MatchStatus:
     """
     取消点赞
     :param user_id:
     :param match_status:
     :return:
     """
     return match_status.undo_like(user_id=user_id)
    def get(self, match_id, status_id):
        match = Match.get_or_404(id=match_id)
        status = MatchStatus.get_or_404(id=status_id)

        form = MatchStatusForm(obj=status)
        self.render("match/statuses_edit.html",
                    match=match,
                    status=status,
                    form=form)
    def post(self, match_id):
        match = Match.get_or_404(id=match_id)
        form = MatchStatusForm(self.arguments)

        if not form.validate():
            self.render("match/statuses_add.html", match=match, form=form)
        else:
            status = MatchStatus(match_id=match_id)
            form.populate_obj(status)

            if "photos" in self.request.files:
                photo_keys_list = self.upload_photos(match_id)
            else:
                photo_keys_list = []

            status.photos = photo_keys_list
            status.save()

            self.redirect(self.reverse_url("admin_match_statuses", match_id))
 def delete(self, match_status_id):
     """
     用户取消点赞,
     该方法会取消当前登录用户对本动态的所有点赞
     :param match_status_id:
     :return:
     """
     match_status = MatchStatus.get_or_404(id=match_status_id)
     status = MatchStatusService.undo_like(user_id=self.current_user.id,
                                           match_status=match_status)
     self.write(MatchStatusSimpleSerializer(status).data)
    def get(self, match_id):

        match = Match.get_or_404(id=match_id)

        query = MatchStatus.select(
            MatchStatus, ).where(MatchStatus.match_id == match.id).order_by(
                MatchStatus.created.desc())

        statuses = self.paginate_query(query)

        self.render("match/statuses.html", statuses=statuses, match=match)
    def get(self, match_id):
        """ 获取赛事动态列表
        """

        # 显示最近 n 条评论
        comments_count = self.get_query_argument("comments_count", 2)
        # 显示最近 n 个点赞
        likes_count = self.get_query_argument("likes_count", 5)

        query = MatchStatus.select()\
            .where(MatchStatus.match_id == match_id)\
            .order_by(MatchStatus.created.desc(), MatchStatus.id.desc())

        CommentAlias = MatchComment.alias()  # type: MatchComment
        subquery = CommentAlias.select(fn.COUNT(CommentAlias.id))\
            .where(CommentAlias.status == MatchComment.status,
                   CommentAlias.id >= MatchComment.id)
        comments = MatchComment.select().where(subquery <= comments_count)\
            .order_by(MatchComment.created.desc(), MatchComment.id.desc())

        likes = MatchStatusLike\
            .select(MatchStatusLike.status, MatchStatusLike.user_id)\
            .order_by(-MatchStatusLike.create_at, -MatchStatusLike.id)\
            .limit(likes_count)\
            .distinct()

        status_with_comments = prefetch(query, comments, likes)

        page = self.paginate_query(status_with_comments)

        _uids = set()
        for row in page:
            for like in row.likes_prefetch:
                _uids.add(like.user_id)
            for comments in row.comments_prefetch:
                _uids.add(comments.user_id)

        parteam_users = dict()
        if _uids:
            pt = Parteam(self.settings["parteam_api_url"])
            parteam_users = pt.parteam_user(list(_uids))

        serializer_kwargs = {"parteam_users": parteam_users}

        data = self.get_paginated_data(page=page,
                                       alias="match_status",
                                       serializer=MatchStatusSerializer,
                                       serializer_kwargs=serializer_kwargs)
        self.write(data)
    def get(self, match_status_id):
        match_status = MatchStatus.get_or_404(id=match_status_id)
        query = MatchStatusService.get_likes(match_status)
        page = self.paginate_query(query)

        data = self.render_page_info(page)

        users = set([like.user_id for like in page])
        likes = []
        if users:
            parteam = Parteam(self.settings["parteam_api_url"])
            users = parteam.parteam_user(list(users))
            likes = [
                users[uid].secure_info for uid in users if uid in users.keys()
            ]
        data.update({"likes": likes})
        self.write(data)
    def post(self, match_status_id):
        form = self.validated_arguments
        match_status = MatchStatus.get_or_404(id=match_status_id)
        inst = MatchComment.create(user_id=self.current_user.id,
                                   status=match_status,
                                   match=match_status.match_id,
                                   **form)

        self.set_status(201, reason="提交评论成功")

        if isinstance(self.current_user, Storage):
            parteam_users = {
                self.current_user.id: ParteamUser(self.current_user)
            }
        else:
            parteam_users = {}

        self.write(
            MatchCommentSerializer(inst, parteam_users=parteam_users).data)
    def get(self, match_status_id):
        match_status = MatchStatus.get_or_404(id=match_status_id)

        # 显示最近 n 条评论
        comments_count = self.get_query_argument("comments_count", 2)
        # 显示最近 n 个点赞
        likes_count = self.get_query_argument("likes_count", 5)

        comments = MatchComment.select()\
            .where(MatchComment.status == match_status_id)\
            .order_by(-MatchComment.created, -MatchComment.id)\
            .limit(comments_count)

        likes = MatchStatusLike\
            .select(MatchStatusLike.status, MatchStatusLike.user_id)\
            .where(MatchStatusLike.status == match_status_id)\
            .order_by(-MatchStatusLike.create_at, -MatchStatusLike.id)\
            .limit(likes_count)\
            .distinct()

        setattr(match_status, "comments_prefetch", comments)
        setattr(match_status, "likes_prefetch", likes)

        _uids = set()
        for like in likes:
            _uids.add(like.user_id)
        for comments in comments:
            _uids.add(comments.user_id)

        parteam_users = dict()
        if _uids:
            pt = Parteam(self.settings["parteam_api_url"])
            parteam_users = pt.parteam_user(list(_uids))

        serializer = MatchStatusSerializer(match_status,
                                           parteam_users=parteam_users)
        self.write(serializer.data)
def main():

    settings = setting_from_object(local_settings)
    if settings.get('debug', False):
        options.logging = "debug"

    tornado.options.parse_command_line()

    if options.debug:
        settings['debug'] = True

    if options.cmd == 'createall':
        """Create all database tables"""

        create_app(settings)

        if not Sport.table_exists():
            Sport.create_table()

        if not User.table_exists():
            User.create_table()

        if not Team.table_exists():
            Team.create_table()

        if not TeamMemberGroup.table_exists():
            TeamMemberGroup.create_table()

        if not TeamMember.table_exists():
            TeamMember.create_table()

        if not Activity.table_exists():
            Activity.create_table()

        if not Admin.table_exists():
            Admin.create_table()

        if not Match.table_exists():
            Match.create_table()

        if not MatchStatus.table_exists():
            MatchStatus.create_table()

        models = find_subclasses(BaseModel)
        for model in models:
            if model._meta.db_table.startswith("__"):
                print(("table skip: " + model._meta.db_table))
            elif model.table_exists():
                print(('table exist: ' + model._meta.db_table))
            else:
                model.create_table()
                print(('table created: ' + model._meta.db_table))

        print('create all [ok]')

    elif options.cmd == 'createadmin':
        app = create_app(settings)
        Admin.create(username="******",
                     password=Admin.create_password("admin"),
                     mobile="17088888888",
                     email="*****@*****.**",
                     name="Admin",
                     is_superadmin=True,
                     state=1)

    elif options.cmd == 'createclient':
        app = create_app(settings)
        Client.create(name="ios",
                      key=create_token(32),
                      secret=create_token(32))

    elif options.cmd == 'run_as_wsgi':
        logging.info('server started. port %s' % options.port)

        import gevent.wsgi

        app = create_app(settings)

        # 转换成wsgi实例
        wsgi_app = tornado.wsgi.WSGIAdapter(app)

        http_server = gevent.wsgi.WSGIServer(('', options.port), wsgi_app)
        http_server.serve_forever()

    elif options.cmd == 'runserver':

        tornado.platform.asyncio.AsyncIOMainLoop().install()
        ioloop = asyncio.get_event_loop()

        app = create_app(settings)
        app.listen(options.port, xheaders=True)

        print("running...")
        ioloop.run_forever()
    elif options.cmd == "fix_notify":
        from fix_script.fix_match_start_nofity import fix_match_start_notify
        fix_match_start_notify()
 def _delete(self, id):
     MatchStatus.delete()\
         .where(MatchStatus.id == id)\
         .execute()
     self.write_success()
 def post(self, match_status_id):
     match_status = MatchStatus.get_or_404(id=match_status_id)
     liked = MatchStatusService.do_like(user_id=self.current_user.id,
                                        match_status=match_status)
     self.set_status(204, reason="点赞成功")