Пример #1
0
    def func_change_mobile(self):
        """
        修改手机号码时更改手机号
        @return:
        """
        user = g.user
        if not user:
            raise response_code.UserERR(errmsg='用户未登录')
        mobile = self.extra_data.get("new_mobile", "")
        code = self.extra_data.get('code', "")
        token = self.extra_data.get('token', "")
        if mobile == "" or code == "" or token == "":
            raise response_code.ParamERR(errmsg="Parameter is not complete")
        elif not mobile_re.match('{}'.format(mobile)):
            raise response_code.ParamERR(errmsg="手机号码不正确")
        elif mobile == user['mobile']:
            raise response_code.ParamERR(
                errmsg="The phone number hasn't changed")
        # 手机验证码验证
        sms_verify(mobile, code)
        real_token = redis_conn.get("verify_mobile_%s" % mobile)
        if token != real_token:
            raise response_code.ParamERR(errmsg="token is incorrect ")
        else:
            mongo.db.user.update_one(user, {"$set": {"mobile": mobile}})

        return set_resjson()
Пример #2
0
 def func_end_watch_history(self):
     """
     观看播放历史
     """
     user = g.user
     if not user:
         raise response_code.ParamERR(errmsg="用户未登陆")
     user_id = user["_id"]
     video_id = self.extra_data.get("video_id", "")
     end_time = self.extra_data.get("end_time", "")
     if end_time == "" or video_id == "":
         raise response_code.ParamERR(
             errmsg="video_id, end_time must be provide")
     try:
         time.strptime(end_time, "%H:%M:%S")
     except Exception as e:
         raise response_code.ParamERR("end_time format incorrect")
     video_info = mongo.db.video.find_one({"_id": video_id})
     if not video_info:
         raise response_code.ParamERR(errmsg="video_id 不存在")
     else:
         mongo.db.video_history.insert_one({
             "_id": create_uuid(),
             "time": time.time(),
             "video_id": video_id,
             "user_id": user_id,
             "record": {
                 "action": "end_watch",
                 "end_time": end_time
             }
         })
     return set_resjson()
Пример #3
0
 def func_read_message(self):
     """
     阅读消息
     @return:
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     message_id_list = self.extra_data.get("message_id")
     date_type = self.extra_data.get("type")
     if type(message_id_list) != list:
         raise response_code.ParamERR(errmsg="message_id must be list")
     elif date_type not in ["like", "subscription", "system"]:
         raise response_code.ParamERR(errmsg="type is Incorrect")
     if date_type == "like":
         mongo.db.like.update({"_id": {
             "$in": message_id_list
         }}, {"$set": {
             "read_state": 1
         }},
                              multi=True)
     elif date_type == "subscription":
         mongo.db.subscription.update({"_id": {
             "$in": message_id_list
         }}, {"$set": {
             "read_state": 1
         }},
                                      multi=True)
     else:
         return set_resjson(errmsg="这个功能暂时没做")
     return set_resjson(errmsg="200")
Пример #4
0
def upload_document():
    """
    上传课件
    @return:
    """
    user = g.user
    if not user:
        raise response_code.UserERR(errmsg='用户未登录')
    document_type = request.form.get('type', "")
    try:
        file = request.files['file']
    except Exception as e:
        raise response_code.ParamERR(errmsg="{}".format(e))
    if not all([document_type, file]):
        raise response_code.ParamERR(errmsg="Parameter is not complete")
    elif not allowed_document_file(file):
        raise response_code.ParamERR(errmsg="The document type is incorrect")
    filename = file.filename.rsplit(".")[0]
    file_path = 'static/document/{}'.format(allowed_document_file(file))
    file.save(file_path)

    return set_resjson(res_array={
        "file_path": file_path,
        "file_name": filename
    })
Пример #5
0
def upload_file():
    """
    上传图片
    @return:
    """
    user = g.user
    if not user:
        raise response_code.UserERR(errmsg='用户未登录')
    image_type = request.form.get('type', "")
    try:
        file = request.files['file']
    except Exception as e:
        raise response_code.ParamERR(errmsg="{}".format(e))
    if not all([image_type, file]):
        raise response_code.ParamERR(errmsg="Parameter is not complete")
    elif not allowed_image_file(file):
        raise response_code.ParamERR(errmsg="The image type is incorrect")
    if image_type == "background":
        file_path = 'static/background/{}'.format(allowed_image_file(file))
        res_url = "http://api.haetek.com:8181/" + file_path
    elif image_type == "headshot":
        file_path = 'static/headershot/{}'.format(allowed_image_file(file))
        res_url = "http://api.haetek.com:8181/" + file_path
    elif image_type in ["video_image", "series_image"]:
        file_path = 'static/image/{}'.format(allowed_image_file(file))
        res_url = file_path
    elif image_type == "document":
        file_path = 'static/document/{}'.format(allowed_image_file(file))
        res_url = file_path
    else:
        raise response_code.ParamERR(errmsg="type is incorrect")
    file.save(file_path)
    return set_resjson(res_array=[res_url])
Пример #6
0
    def func_quick_login(self):
        """
        手机一键登陆
        """
        login_token = self.extra_data.get("login_token", "")
        if login_token == "":
            raise response_code.ParamERR(
                errmsg="[ login_token ] must be provided")

        curl = 'https://api.verification.jpush.cn/v1/web/loginTokenVerify'
        dict_body = {"loginToken": login_token}
        json_body = json.dumps(dict_body)
        encrypt_phone = get_phone(curl, json_body)
        if not encrypt_phone:
            raise response_code.ParamERR(errmsg="登陆失败")
        phone = get_num(encrypt_phone, config.JI_GUANG_PRIKEY)
        user_info = mongo.db.user.find_one({"mobile": phone}, {
            "headshot": 1,
            "name": 1
        })
        now_time = time.time()
        if not user_info:
            _id = get_user_id("id")
            try:

                mongo.db.user.insert_one({
                    "gender": "男",
                    "birthday": str(datetime.date.today()),
                    "name": ranstr(16),
                    "mobile": '{}'.format(phone),
                    "_id": _id,
                    "headershot": self.head_shot_path,
                    "create_time": now_time,
                    "login_time": now_time,
                    "background": self.background_path,
                    "introduction": self.introduction
                })
            except Exception as error:
                current_app.logger.error(error)
                raise response_code.DatabaseERR(errmsg='{}'.format(error))
            user_info = {"name": ranstr(16), "headshot": self.head_shot_path}
        else:
            _id = user_info.pop("_id")
            try:
                mongo.db.user.update_one({"mobile": '{}'.format(phone)},
                                         {"$set": {
                                             "login_time": now_time
                                         }})
            except Exception as err:
                current_app.logger.error(err)
                raise response_code.DatabaseERR(errmsg='{}'.format(err))
        # set the token information in the response
        response = make_response(set_resjson(res_array=[user_info]))
        response.headers["Authorization"] = encode_auth_token(_id)
        return response
Пример #7
0
 def func_third_login(self):
     resp = None
     mode = self.extra_data.get('type', "")
     code = self.extra_data.get('code', '')
     if code == '':
         raise response_code.ParamERR(errmsg='code can be not empty')
     elif mode not in ["microblog", "qq", "wechat"]:
         raise response_code.ParamERR(errmsg="type is incorrect")
     elif mode == "qq":
         resp = qq_login(code)
     elif mode == 'wechat':
         resp = wehcat_login(code)
     elif mode == 'microblog':
         resp = weibo_login(code)
     return resp
Пример #8
0
    def get_access_token(self, code):
        """向QQ服务器获取access token"""

        url = "https://graph.qq.com/oauth2.0/token?"
        params = {
            "grant_type": "authorization_code",
            "code": code,
            "client_id": self.client_id,
            "redirect_uri": self.redirect_uri,
            "client_secret": self.client_secret
        }

        url += urllib.parse.urlencode(params)

        # 向QQ服务器发送请求 access_token
        # access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14

        try:
            resp = urlopen(url)
            resp_byte = resp.read()  # 为 byte 类型
            resp_str = resp_byte.decode()  # 转化为 str 类型
            resp_dict = urllib.parse.parse_qs(resp_str)
        except Exception as e:
            current_app.logger.error('获取access_token异常: %s' % e)
            raise response_code.ThirdERR(errmsg="{}".format(e))

        else:
            if not resp_dict:
                raise response_code.ParamERR(errmsg='code 失效')
            # access_token取出是一个列表
            access_token_list = resp_dict.get('access_token')
            access_token = access_token_list[0]

        return access_token
Пример #9
0
 def func_get_like(self):
     """
     查看点赞
     @return:
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     res_list = []
     try:
         for like in mongo.db.like.find(
                 {"user_id": user["_id"], "type": "video"}).sort("time", -1):
             video_info = mongo.db.video.find_one(
                 {"_id": like["relation_id"]},
                 {"title": 1, "upload_time": 1,
                  "video_time": 1,
                  "image_path": 1})
             if not video_info:
                 continue
             video_id = video_info.pop("_id")
             video_info["video_id"] = video_id
             video_info["like_counts"] = mongo.db.like.find(
                 {"relation_id": video_id}).count()
             res_list.append(deepcopy(video_info))
     except Exception as e:
         current_app.log.error(e)
         raise response_code.ParamERR(errmsg="{}".format(e))
     return set_resjson(res_array=res_list)
Пример #10
0
    def func_enquiry_qrcode(self):
        """
        web 询问接口
        :return:
        """

        qrcode = self.extra_data.get('qrcode', '')
        if qrcode == "":
            raise response_code.ParamERR(errmsg='qrcode can not be empty!')
        try:
            qr_state = (redis_conn.get('{}'.format(qrcode)))
        except Exception as e:
            raise response_code.DatabaseERR(errmsg='{}'.format(e))

        if qr_state == "0":
            resp = set_resjson(err=1, errmsg='未扫描')
        elif qr_state == "1":
            resp = set_resjson(err=-2, errmsg='已扫描未登录')
        elif qr_state is None:
            resp = set_resjson(err=-4, errmsg='验证码已过期')
        else:
            try:
                user_info = mongo.db.user.find_one({"_id": qr_state}, {
                    "name": 1,
                    "headshot": 1,
                    "_id": 0
                })
            except Exception as e:
                raise response_code.DatabaseERR(errmsg="{}".format(e))
            resp = make_response(set_resjson(res_array=[user_info]))
            resp.headers["Authorization"] = encode_auth_token(qr_state)
        return resp
Пример #11
0
    def func_code_login(self):
        """
        login
        :return:
        """
        _id = None
        mobile = self.extra_data.get("mobile", "")
        code = self.extra_data.get('code', "")
        if not mobile_re.match('{}'.format(mobile)):
            raise response_code.ParamERR(errmsg="手机号码不正确")
        # 手机验证码验证
        sms_verify(mobile, code)

        try:
            user_info = mongo.db.user.find_one({"mobile": '{}'.format(mobile)},
                                               {
                                                   "headshot": 1,
                                                   "name": 1
                                               })
        except Exception as error:
            current_app.logger.error(error)
            raise response_code.DatabaseERR(errmsg='{}'.format(error))
        now_time = time.time()
        if not user_info:
            _id = get_user_id("id")
            try:

                mongo.db.user.insert_one({
                    "gender": "男",
                    "birthday": str(datetime.date.today()),
                    "name": ranstr(16),
                    "mobile": '{}'.format(mobile),
                    "_id": _id,
                    "headshot": self.head_shot_path,
                    "create_time": now_time,
                    "login_time": now_time,
                    "background": self.background_path,
                    "introduction": self.introduction
                })
            except Exception as error:
                current_app.logger.error(error)
                raise response_code.DatabaseERR(errmsg='{}'.format(error))
            user_info = {"name": ranstr(16), "headshot": self.head_shot_path}
        else:
            _id = user_info.pop("_id")
            try:
                mongo.db.user.update_one({"mobile": '{}'.format(mobile)},
                                         {"$set": {
                                             "login_time": now_time
                                         }})
            except Exception as err:
                current_app.logger.error(err)
                raise response_code.DatabaseERR(errmsg='{}'.format(err))
        # set the token information in the response
        response = make_response(set_resjson(res_array=[user_info]))
        response.headers["Authorization"] = encode_auth_token(_id)
        return response
Пример #12
0
def edit_video(res_list, video_id, style, lang):
    """
    编辑视频
    """
    try:
        subtitle = Subtitle(video_id)
        subtitle.update_video(res_list, video_id, style, lang)
    except Exception as e:
        raise response_code.ParamERR(errmsg='{}'.format(e))
Пример #13
0
    def func_get_information(self):
        """
        获取个人信息
        @return:
        """
        user = g.user
        res_dict = {}
        if not user:
            raise response_code.ParamERR(errmsg="用户未登陆")
        try:
            subscription_counts = mongo.db.subscription.find({
                "user_id":
                user["_id"],
                "state":
                0
            }).count()
            fans_counts = mongo.db.subscription.find({
                "relation_id": user["_id"],
                "state": 0
            }).count()

            video_id_list = [
                video.get("_id") for video in mongo.db.video.find(
                    {"user_id": user["_id"]}, {"_id": 1})
            ]
            like_counts = mongo.db.like.find({
                "user_id": user["_id"],
                "relation_id": {
                    "$in": video_id_list
                }
            }).count()

        except Exception as e:
            raise response_code.DatabaseERR(errmsg="{}".format(e))
        res_dict["user_name"] = user["name"]
        res_dict["user_id"] = user["_id"]
        res_dict["birthday"] = user.get(
            "birthday",
            time.strftime("%Y-%m-%d", time.localtime(user["create_time"])))
        res_dict["gender"] = user.get("gender", "男")
        res_dict["introduction"] = user["introduction"]
        res_dict["headshot"] = user["headshot"]
        res_dict["background"] = user["background"]
        res_dict["like_counts"] = like_counts
        res_dict["video_counts"] = len(video_id_list)
        res_dict["user_name"] = user["name"]
        res_dict["binding_webchat"] = 1 if user.get("wechat_unionid",
                                                    None) else 0
        res_dict["binding_qq"] = 1 if user.get("qq_unionid", None) else 0
        res_dict["binding_microblog"] = 1 if user.get("microblog_unionid",
                                                      None) else 0
        res_dict["subscription_counts"] = subscription_counts
        res_dict["fans_counts"] = fans_counts
        return set_resjson(res_array=[res_dict])
Пример #14
0
    def func_add_subscription(self):
        """
        订阅
        @return:
        """
        user = g.user
        if not user:
            raise response_code.UserERR(errmsg='用户未登录')
        sub_type = self.extra_data.get("type", "")
        relation_id = self.extra_data.get("relation_id", "")
        value = self.extra_data.get("value", "")
        if value not in [0, 1]:
            raise response_code.ParamERR(errmsg="value must be 1 or 0")
        elif relation_id == "":
            raise response_code.ParamERR(errmsg="relation_id must be provide")
        elif sub_type != "author":
            raise response_code.ParamERR(errmsg="mode must be author")
        author_info = mongo.db.user.find_one({"_id": relation_id})
        if not author_info:
            raise response_code.ParamERR(errmsg="relation_id 不存在")
        else:
            sub_info = mongo.db.subscription.find_one({
                "relation_id": relation_id,
                "user_id": user["_id"]
            })
            if value == 1:
                if not sub_info:
                    mongo.db.subscription.insert_one({
                        "_id": create_uuid(),
                        "user_id": user["_id"],
                        "relation_id": relation_id,
                        "read_state": 0,
                        "time": time.time(),
                        "type": sub_type,
                        "state": 0
                    })
                elif sub_info["state"] == -1:
                    mongo.db.subscription.update_one({"_id": sub_info["_id"]},
                                                     {"$set": {
                                                         "state": 0
                                                     }})
                else:
                    raise response_code.ParamERR(errmsg="此作者已经订阅")
            else:
                if sub_info:
                    if sub_info["state"] == 0:
                        mongo.db.subscription.update_one(
                            {"_id": sub_info["_id"]}, {"$set": {
                                "state": -1
                            }})
                    else:
                        raise response_code.ParamERR(errmsg="此作者还没有订阅")
                else:
                    raise response_code.ParamERR(errmsg="此作者还没有订阅")

        return set_resjson()
Пример #15
0
    def func_generate_code(self):
        """
         Send SMS verification code
        :return:
        """

        mobile = self.extra_data.get("mobile", "")
        if not mobile_re.match('{}'.format(mobile)):
            raise response_code.ParamERR(errmsg="手机号码不正确")

        send_flag = redis_conn.get("send_flag_{}".format(mobile))
        if send_flag:
            raise response_code.ReqERR(errmsg="请求次数过于频繁")

        # sms_code = "%04d" % random.randint(0, 9999)
        sms_code = "6666"

        # encrypted message
        hash1 = hashlib.sha256()
        hash1.update(bytes(sms_code, encoding="utf-8"))
        hash_sms_code = hash1.hexdigest()
        # Using redis transactions, save SMS and flag to redis,
        # SMS expiration time is 300 seconds, flag expiration time is 60 seconds
        try:
            pl = redis_conn.pipeline()
            pl.set("sms_code_%s" % mobile, sms_code,
                   constants.SMS_CODE_REDIS_EXPIRES)
            pl.set("send_flag_%s" % mobile, sms_code,
                   constants.SEND_SMS_CODE_INTERVAL)
            pl.execute()
        except Exception as error:
            current_app.logger.error(error)
            raise response_code.DatabaseERR(errmsg='{}'.format(error))
        # try:
        #
        #     resp = send_sms(mobile, constants.SMS_LOGIN_TEMPLATE_ID, constants.SMS_SIGN, sms_code)
        # except Exception as e:
        #     current_app.logger.error('[send_verification_code] {}'.format(e))
        #     raise response_code.ThirdERR(errmsg='{}'.format(e))
        # resp_dict = json.loads(resp.decode('utf-8'))
        # resp_code = resp_dict.get('Code', 'OK')
        # if resp_code != 'OK':
        #     redis_conn.delete("send_flag_{}".format(mobile))
        #     message = resp_dict.get('Message', '')
        #     current_app.logger.error(message)
        #     raise response_code.ThirdERR(errmsg=message)
        response = make_response(
            set_resjson(res_array=[{
                "code": hash_sms_code,
                'real_code': sms_code
            }]))
        return response
Пример #16
0
 def func_change_information(self):
     """
     编辑个人信息
     @return:
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     gender = self.extra_data.get('gender')
     user_name = self.extra_data.get('user_name')
     birthday = self.extra_data.get('birthday')
     introduction = self.extra_data.get('introduction')
     background = self.extra_data.get('background')
     headshot = self.extra_data.get('headshot')
     if not all(
         [gender, user_name, birthday, introduction, background, headshot]):
         raise response_code.ParamERR(errmsg="Parameter is not complete")
     elif not name_re.match('{}'.format(user_name)):
         raise response_code.ParamERR(errmsg="Incorrect user name format")
     elif not url_re.match(background) or not url_re.match(headshot):
         raise response_code.ParamERR(errmsg="The image url is incorrect")
     elif gender not in ["男", "女", "保密"]:
         response_code.ParamERR(errmsg="gender must be 男 or 女 or 保密")
     is_birthday = verify_date_str_lawyer(birthday)
     if not is_birthday:
         raise response_code.ParamERR(errmsg="birthday Incorrect format")
     user_update_info = {
         "gender": gender,
         "name": user_name,
         "birthday": birthday,
         "introduction": introduction,
         "background": background,
         "data_type": "user",
         "headshot": headshot,
         "_id": user["_id"]
     }
     mongo.db.audit.insert_one(user_update_info)
     return set_resjson()
Пример #17
0
 def func_search_history(self):
     """
     局部搜索历史记录
     @return:
     """
     user = g.user
     if not user:
         raise response_code.ParamERR(errmsg="用户未登陆")
     user_id = user["_id"]
     video_id = self.extra_data.get("video_id", "")
     query_string = self.extra_data.get("query_string", "")
     end_time = self.extra_data.get("end_time", "")
     if end_time == "" or video_id == "" or query_string == "":
         raise response_code.ParamERR(
             errmsg="video_id, end_time, query_string must be provide")
     try:
         time.strptime(end_time, "%H:%M:%S")
     except Exception as e:
         current_app.logger.info(e)
         raise response_code.ParamERR("end_time format incorrect")
     video_info = mongo.db.video.find_one({"_id": video_id})
     if not video_info:
         raise response_code.ParamERR(errmsg="video_id 不存在")
     else:
         mongo.db.video_history.insert_one({
             "_id": create_uuid(),
             "time": time.time(),
             "video_id": video_id,
             "user_id": user_id,
             "record": {
                 "action": "search",
                 "query_string": query_string,
                 "end_time": end_time
             }
         })
     return set_resjson()
Пример #18
0
 def handle_model(self):
     func_name = 'func_{}'.format(self.model_action)
     func_name = func_name.lower()
     try:
         handle_function = getattr(SeriesHandler, func_name)
         if self.model_action not in ["get_series"]:
             if self.extra_data == '':
                 raise response_code.ParamERR(
                     errmsg="[ extra_data ] must be provided ")
         resp = handle_function(self)
     except AttributeError as e:
         resp = set_resjson(err=-4,
                            errmsg="{} is incorrect !".format(
                                self.model_action))
     return resp
Пример #19
0
    def get_user_info(access_token):

        url = 'https://api.weibo.com/2/users/show.json?'
        params = {
            "access_token": access_token,
            "screen_name": "screen_name"}

        url += urllib.parse.urlencode(params)
        print(url)
        try:
            resp = urlopen(url)
            resp_byte = resp.read()
            resp_json = json.loads(resp_byte.decode())
        except Exception as e:
            raise response_code.ParamERR(errmsg="{}".format(e))
        return resp_json
Пример #20
0
    def get_user_info(self, access_token, openid):

        url = 'https://graph.qq.com/user/get_user_info?'
        params = {
            "access_token": access_token,
            "oauth_consumer_key": self.client_id,
            "openid": openid
        }

        url += urllib.parse.urlencode(params)
        try:
            resp = urlopen(url)
            resp_byte = resp.read()
            resp_json = json.loads(resp_byte.decode())
        except Exception as e:
            raise response_code.ParamERR(errmsg="{}".format(e))
        return resp_json
Пример #21
0
    def func_check_mobile(self):
        """
        查看手机号码重复
        @return:
        """
        mobile = self.extra_data.get('mobile', '')
        if not mobile_re.match('{}'.format(mobile)):
            raise response_code.ParamERR(errmsg="手机号码不正确")

        try:
            user_info = mongo.db.user.find_one({"mobile": '{}'.format(mobile)})
        except Exception as error:
            current_app.logger.error(error)
            raise response_code.DatabaseERR(errmsg='{}'.format(error))
        if user_info:
            resp = set_resjson(err=-1, errmsg='This mobile is already exist!')
        else:
            resp = set_resjson(err=0, errmsg="This mobile can be registered!")
        return resp
Пример #22
0
    def func_generate_third_qrcode(self):
        """ 生成 url 连接  """
        mode = self.extra_data.get('type', "")
        next1 = self.extra_data.get('next', "")
        display = self.extra_data.get('display', "")
        log_url = None
        if mode not in ["microblog", "qq", "wechat"]:
            raise response_code.ParamERR(errmsg="type is incorrect")
        elif mode == "qq":
            oauth_qq = OAuthQQ(state=next1, display=display)
            log_url = oauth_qq.get_qq_login_url()
        elif mode == "wechat":
            wechat = WeChat(state=next1)
            log_url = wechat.get_wechat_url()
        elif mode == "microblog":
            weibo = WeiBo(state=next1)
            log_url = weibo.get_weibo_login_url()

        return set_resjson(res_array=[{"url": log_url}])
Пример #23
0
 def func_verify_mobile(self):
     """
     修改手机号码时验证手机号
     @return:
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     mobile = self.extra_data.get("mobile", "")
     code = self.extra_data.get('code', "")
     if '{}'.format(mobile) != user["mobile"]:
         raise response_code.ParamERR(errmsg="不是原手机号码")
     # 手机验证码验证
     sms_verify(mobile, code)
     token = str(uuid1())
     redis_conn.set("verify_mobile_%s" % mobile, token,
                    constants.VERIFY_MOBILE_REDIS_EXPIRES)
     res_dict = {"token": token}
     return set_resjson(res_array=[res_dict])
Пример #24
0
 def func_get_series(self):
     """
     获得系列信息
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     try:
         series_cursor = mongo.db.series.find({'user_id': user["_id"]}, {
             "title": 1,
             "_id": 0
         })
     except Exception as e:
         raise response_code.ParamERR(errmsg="{}".format(e))
     # res_data = []
     # for result in results:
     #     data_dict = {'title': result['title']}
     #     res_data.append(data_dict)
     res_list = [i for i in series_cursor]
     return set_resjson(res_array=res_list)
Пример #25
0
 def func_remove_binding(self):
     """
     解除第三方绑定
     @return:
     """
     user = g.user
     if not user:
         raise response_code.UserERR(errmsg='用户未登录')
     third_type = self.extra_data.get("type", "")
     if third_type not in ["microblog", "wechat", "qq"]:
         raise response_code.ParamERR(errmsg="type is incorrect")
     elif third_type.lower() == "microblog":
         mongo.db.user.update_one(user, {"$unset": {"wechat_unionid": ""}})
     elif third_type.lower() == "wechat":
         mongo.db.user.update_one(user,
                                  {"$unset": {
                                      "microblog_unionid": ""
                                  }})
     elif third_type.lower() == "qq":
         mongo.db.user.update_one(user, {"$unset": {"qq_unionid": ""}})
     raise set_resjson()
Пример #26
0
    def func_scan_qrcode(self):
        """
        移动端扫描二维码
        :return:
        """
        user = g.user
        if not user:
            raise response_code.UserERR(errmsg='用户未登录')
        qrcode = self.extra_data.get('qrcode', '')
        try:
            qr_state_byte = redis_conn.get('{}'.format(qrcode))
        except Exception as e:
            raise response_code.DatabaseERR(errmsg='{}'.format(e))
        if not qr_state_byte:
            raise response_code.ParamERR(errmsg='验证码过期')
        try:
            redis_conn.set(qrcode, user['_id'],
                           constants.QR_CODE_REDIS_EXPIRES)
        except Exception as e:
            raise response_code.DatabaseERR(errmsg='{}'.format(e))

        return set_resjson()
Пример #27
0
    def func_get_history(self):
        """
        获取历史记录
        @return:
        """
        user = g.user
        if not user:
            raise response_code.ParamERR(errmsg="用户未登陆")
        results = mongo.db.video_history.find({
            'user_id': user["_id"],
            "record.action": "end_watch"
        }).sort('time', -1)
        temp_dict = {}
        result_data = []
        for result in results:
            temp_dict[result['video_id']] = {
                'video_id': result['video_id'],
                'time': result['time'],
                'record': result['record']
            }

        video_ids = sorted(temp_dict,
                           key=lambda v: (temp_dict[v]['time']),
                           reverse=True)

        for video_id in video_ids:
            video_data = mongo.db.video.find_one({'_id': video_id}, {
                'image_path': 1,
                'video_time': 1,
                '_id': 0
            })
            # Merge(temp_dict[video_id], video_data)
            video_data.update(temp_dict[video_id])
            result_data.append(video_data)

        # return result_data

        return set_resjson(res_array=result_data)
Пример #28
0
    def func_download_file(self):
        """
        课件下载
        @return:
        """
        res_list = []
        file_id = self.extra_data.get("file_id", "")
        if file_id == "" or type(file_id) != list:
            raise response_code.ParamERR(
                errmsg="file_id be provide or type must array")
        for document_id in file_id:
            try:
                video_document = mongo.db.document.find_one(
                    {"_id": document_id}, {
                        "_id": 0,
                        "file_path": 1,
                        "download_counts": 1
                    })

                if not video_document:
                    video_document = {document_id: "此ID不存在"}
                else:
                    if "download_counts" in video_document.keys():
                        download_counts = video_document.pop("download_counts")
                    else:
                        download_counts = 0
                    mongo.db.document.update_one(
                        {"_id": document_id},
                        {"$set": {
                            "download_counts": download_counts + 1
                        }})

                res_list.append(deepcopy(video_document))
            except Exception as e:
                raise response_code.DatabaseERR(errmsg="{}".format(e))

        return set_resjson(res_array=res_list)
Пример #29
0
    def get_access_token(self, code):
        """向weibo服务器获取access token"""

        url = "https://api.weibo.com/oauth2/access_token?"
        params = {
            "client_id": self.appid,
            "client_secret": self.secret_key,
            "grant_type": "authorization_code",
            "redirect_uri": self.redirect_uri,
            "code": code
        }
        url += urllib.parse.urlencode(params)
        try:
            resp = requests.post(url).content.decode()
            resp_dict = json.loads(resp)
        except Exception as e:
            current_app.logger.error('获取access_token异常: %s' % e)
            raise response_code.ThirdERR(errmsg="{}".format(e))
        else:
            if not resp_dict or resp_dict.get("error"):
                raise response_code.ParamERR(errmsg='code 失效 {}'.format(
                    resp_dict.get("error_description")))
            access_token = resp_dict.get('access_token')
        return access_token
Пример #30
0
    def func_get_series_details(self):
        """
        系列详情页
        @return:
        """
        user = g.user
        res_dict = {}
        video_dict = {}
        document_dict = {}
        document_list = []
        res_list = []
        video_list = []
        series_id = self.extra_data.get("series_id", "")
        if series_id == "":
            raise response_code.ParamERR(errmsg="[series_id] must be provide")
        series_info = mongo.db.series.find_one({"_id": series_id})
        if not series_info:
            raise response_code.ParamERR(errmsg="series_id is incorrect")
        collect = None
        subscription = None
        if user:
            collect = mongo.db.collection.find_one({
                "user_id": user["_id"],
                "relation_id": series_id,
                "state": 0,
                "type": "series"
            })
            subscription = mongo.db.subscription.find_one({
                'relation_id':
                series_info["user_id"],
                'type':
                'author',
                'user_id':
                user["_id"],
                "state":
                0
            })
        document_counts = 0
        like_counts = mongo.db.like.find({"relation_id": series_id}).count()
        collection_counts = mongo.db.collection.find({
            "relation_id": series_id,
            "type": "series"
        }).count()
        author_info = mongo.db.user.find_one({"_id": series_info["user_id"]})
        res_dict["title"] = series_info["title"]
        res_dict["image_path"] = series_info["image_path"]
        res_dict["update_time"] = series_info["time"]
        res_dict["fans_counts"] = mongo.db.subscription.find({
            "relation_id":
            author_info["_id"],
            "state":
            0
        }).count()
        res_dict["description"] = series_info["description"]
        res_dict["author_id"] = series_info["user_id"]
        res_dict["is_collect"] = 1 if collect else 0
        res_dict["is_subscription"] = 1 if subscription else 0
        res_dict["video_counts"] = series_info.get(
            "video_counts", None) if series_info.get(
                "video_counts", None) else mongo.db.video.find({
                    "series": series_id,
                    "state": 2
                }).count()
        res_dict["author_name"] = author_info["name"]
        res_dict["headshot"] = author_info["headshot"]
        # TODO 视频分享没做
        res_dict["share_counts"] = 0
        video_cursor = mongo.db.video.find({
            "series": series_id,
            "state": 2
        }).sort([("number", 1), ("upload_time", -1)])
        video_id_list = []
        for video in video_cursor:
            video_id_list.append(video["_id"])
            video_like_counts = mongo.db.like.find({
                "relation_id": video["_id"],
                "type": "video"
            }).count()
            like_counts += video_like_counts
            video_dict["video_id"] = video["_id"]
            video_dict["video_title"] = video["title"]
            video_dict["description"] = video["description"]
            video_dict["video_time"] = video["video_time"]
            video_dict["upload_time"] = video["upload_time"]
            video_dict["image_path"] = video["image_path"]
            video_dict["view_counts"] = video["view_counts"]
            video_dict["like_counts"] = video_like_counts
            video_dict["comment_counts"] = mongo.db.comment.find({
                "state":
                2,
                "video_id":
                video["_id"]
            }).count()
            video_list.append(deepcopy(video_dict))
            document_cursor = mongo.db.document.find(
                {"video_id": video["_id"]})
            if document_cursor.count() > 0:
                for document in document_cursor:
                    document_counts += 1
                    document_dict["file_id"] = document["_id"]
                    document_dict["file_name"] = document["file_name"]
                    document_dict["file_type"] = document["type"]
                    document_dict["price"] = document["price"]
                    document_dict["image_path"] = document["image_path"]
                    document_dict["download_counts"] = document[
                        "download_counts"]
                    document_list.append(deepcopy(document_dict))
        res_dict["document_counts"] = document_counts

        collection_counts += mongo.db.collection.find({
            "state": 0,
            "relation_id": {
                "$in": video_id_list
            }
        }).count()
        res_dict["collection_counts"] = collection_counts
        res_dict["video_data"] = video_list
        res_dict["document_data"] = document_list
        res_dict["like_counts"] = like_counts
        res_list.append(res_dict)
        return set_resjson(res_array=res_list)