Exemple #1
0
 def get_tag_by_id(cls, tag_id):
     try:
         o_tag = cls.objects.get(pk=tag_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_TAG)
     return Ret(o_tag)
Exemple #2
0
 def get_msg_by_id(cls, msg_id):
     try:
         o_msg = cls.objects.get(pk=msg_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_MESSAGE)
     return Ret(o_msg)
def require_login_func(request):
    """需要登录

    并根据传入的token获取user
    """
    jwt_str = request.META.get('HTTP_TOKEN')
    if jwt_str is None:
        return Ret(Error.REQUIRE_LOGIN)
    from Base.jtoken import jwt_d

    ret = jwt_d(jwt_str)
    if ret.error is not Error.OK:
        return ret
    dict_ = ret.body

    try:
        user_id = dict_["user_id"]
    except KeyError as err:
        deprint(str(err))
        return Ret(Error.STRANGE)

    from User.models import User
    ret = User.get_user_by_id(user_id)
    if ret.error is not Error.OK:
        return ret
    o_user = ret.body
    if not isinstance(o_user, User):
        return Ret(Error.STRANGE)

    request.user = o_user
    return Ret()
Exemple #4
0
 def get_photo_by_id(cls, photo_id):
     try:
         o_photo = cls.objects.get(photo_id=photo_id)
     except Photo.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.PHOTO_NOT_FOUND)
     return Ret(Error.OK, o_photo)
Exemple #5
0
 def get_dr_by_date(cls, date_):
     try:
         o_dr = cls.objects.get(dat_e=date_)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_DAILYRECOMMEND)
     return Ret(o_dr)
Exemple #6
0
    def create(cls, name, singer, cover, total_comment, netease_id, o_user):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        ret = cls.get_music_by_netease_id(netease_id)
        if ret.error is Error.OK:
            return ret

        crt_time = datetime.datetime.now().timestamp()

        try:
            o_music = cls(
                name=name,
                singer=singer,
                cover=cover,
                total_comment=total_comment,
                netease_id=netease_id,
                re_user=o_user,
                create_time=crt_time,
                status=cls.STATUS_CONSIDER,
                last_update_time=crt_time,
                updated_total_comment=total_comment,
            )
            o_music.save()
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_CREATE_MUSIC)

        return Ret(o_music)
Exemple #7
0
 def get_music_by_netease_id(cls, netease_id):
     try:
         o_music = cls.objects.get(netease_id=netease_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_MUSIC)
     return Ret(o_music)
Exemple #8
0
 def update_status(self, status, consider_user):
     if self.status != self.STATUS_CONSIDER:
         return Ret(Error.ALREADY_CONSIDERED)
     self.status = self.STATUS_ACCEPTED if status else self.STATUS_REFUSED
     self.consider_user = consider_user
     self.save()
     return Ret()
Exemple #9
0
    def create(cls, qt_user_app_id, token):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        ret = cls.get_user_by_qt_user_app_id(qt_user_app_id)
        if ret.error is Error.OK:
            o_user = ret.body
            o_user.qtb_token = token
            o_user.save()
            return Ret(o_user)
        try:
            o_user = cls(
                qt_user_app_id=qt_user_app_id,
                qtb_token=token,
                port=cls.get_unique_port(),
                ss_pwd=get_random_string(length=8),
                ss_on=False,
                ss_change_time=0,
            )
            o_user.save()
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_CREATE_USER)

        o_user.do_ss_on()

        return Ret(o_user)
Exemple #10
0
 def create(cls, access_token):
     from Base.api import get_user_profile
     rtn = get_user_profile(access_token)
     if rtn is None:
         return Ret(Error.ERROR_GET_PROFILE)
     user_id = rtn.get('id')
     username = rtn.get('username')
     email = rtn.get('email')
     try:
         o_user = cls.objects.get(pk=user_id)
         o_user.username = username
         o_user.email = email
         o_user.access_token = access_token
         o_user.expired = False
     except:
         o_user = cls(
             user_id=user_id,
             username=username,
             access_token=access_token,
             email=email,
             expired=False,
         )
     try:
         o_user.save()
         return Ret(Error.OK, o_user)
     except:
         return Ret(Error.USER_SAVE_ERROR)
Exemple #11
0
 def get_user_by_str_id(cls, str_id):
     try:
         o_user = cls.objects.get(str_id=str_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Exemple #12
0
    def code2session(code):
        url = Weixin.CODE2SESSION_URL % code

        data = requests.get(url).json()

        if 'openid' not in data:
            return Ret(Error.ERROR_JSCODE)
        return Ret(data)
Exemple #13
0
 def get_user_by_qt_user_app_id(qt_user_app_id):
     """根据齐天用户-应用ID获取用户对象"""
     try:
         o_user = User.objects.get(qt_user_app_id=qt_user_app_id)
     except User.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Exemple #14
0
 def get_user_by_id(cls, user_id):
     """根据用户ID获取用户对象"""
     try:
         o_user = cls.objects.get(pk=user_id)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Exemple #15
0
 def get_value_by_key(cls, key, default=__ConfigNone()):
     ret = cls.get_config_by_key(key)
     if ret.error is not Error.OK:
         if isinstance(default, cls.__ConfigNone):
             return ret
         else:
             return Ret(default)
     return Ret(ret.body.value)
Exemple #16
0
 def get_user_by_port(cls, port):
     """根据用户分配的port获取用户对象"""
     try:
         o_user = cls.objects.get(port=port)
     except cls.DoesNotExist as err:
         deprint(str(err))
         return Ret(Error.NOT_FOUND_USER)
     return Ret(o_user)
Exemple #17
0
def match(o_phrase, cluster=clusters['NORMAL'], min_max_match=0, phrase_len=0):
    """
    词语匹配
    :param phrase_len: 匹配的词语长度 0 表示所有长度
    :param min_max_match: 最小匹配的最大长度 -1 表示所能达到的最大长度
    :param o_phrase: 拼音列表 如羽毛球 则 qiu2 mao2 yu3
    :param cluster: 使用聚类名称 默认为 NORMAL 还有
    :return: Ret类 如果成功则返回匹配词典
    """
    result = dict()
    for phonetic in o_phrase:
        if phonetic['p'] not in groups.keys():
            return Ret(Error.NOT_FOUND_PHONETIC, phonetic['p'])

    if min_max_match > len(o_phrase):
        min_max_match = len(o_phrase)

    for _phrase in phrases:  # 遍历所有的词语进行匹配
        phrase = _phrase[::-1]  # 词语反转
        max_match = 0  # 当前词语的匹配度为 0

        if phrase_len != len(phrase) and phrase_len != 0:
            continue
        if min_max_match > len(phrase):
            continue

        for i in range(min(len(phrase), len(o_phrase))):  # 开始匹配
            word = phrase[i]  # 匹配第i个字
            if word not in words:  # 不存在这个字
                break
            single_match = False
            for phonetic in words[word]:  # 遍历这个字的所有拼音
                if o_phrase[i]['t'] != '' and o_phrase[i]['t'] != phonetic['t']:
                    continue
                g1 = groups[o_phrase[i]['p']]  # 获取拼音所在组
                # print(phonetic)
                if phonetic['p'] not in groups.keys():
                    continue
                g2 = groups[phonetic['p']]  # 获取当前字的拼音所在组
                # 判断 g1 和 g2 是否在一个cluster
                for c in cluster:
                    if g1 in c and g2 in c:
                        single_match = True
                        break
                if single_match:
                    break
            if single_match:
                max_match += 1
            else:  # 当前字无法匹配,匹配终止
                break
        if min_max_match > max_match or max_match < 1:
            continue

        max_match = str(max_match)
        if max_match not in result.keys():
            result[max_match] = list()
        result[max_match].append(_phrase)
    return Ret(Error.OK, result)
Exemple #18
0
    def get_comment(cls, netease_id):
        comment_url = cls.COMMENT_URL % netease_id

        try:
            data = abstract_grab(comment_url)
            total_comment = json.loads(data)['total']
        except Exception as err:
            deprint(str(err))
            return Ret(Error.ERROR_GRAB_MUSIC, append_msg=',评论获取错误')
        return Ret(total_comment)
Exemple #19
0
def field_validator(dict_, cls, allow_none=False):
    """
    针对model的验证函数
    事先需要FIELD_LIST存放需要验证的属性
    需要L字典存放CharField类型字段的最大长度
    可选MIN_L字典存放CharField字段最小长度
    可选创建_valid_<param>函数进行自校验
    """
    field_list = getattr(cls, 'FIELD_LIST', None)
    if field_list is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不存在FIELD_LIST')
    _meta = getattr(cls, '_meta', None)
    if _meta is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不是Django的models类')
    len_list = getattr(cls, 'L', None)
    if len_list is None:
        return Ret(Error.ERROR_VALIDATION_FUNC, append_msg=',不存在长度字典L')
    min_len_list = getattr(cls, 'MIN_L', None)

    for k in dict_.keys():
        if k in getattr(cls, 'FIELD_LIST'):
            if allow_none and dict_[k] is None:
                continue
            if isinstance(_meta.get_field(k), models.CharField):
                try:
                    if len(dict_[k]) > len_list[k]:
                        return Ret(Error.ERROR_PARAM_FORMAT,
                                   append_msg=',%s的长度不应超过%s个字符' %
                                   (k, len_list[k]))
                    if min_len_list and k in min_len_list and len(
                            dict_[k]) < min_len_list[k]:
                        return Ret(Error.ERROR_PARAM_FORMAT,
                                   append_msg=',%s的长度不应少于%s个字符' %
                                   (k, min_len_list[k]))
                except TypeError as err:
                    deprint(str(err))
                    return Ret(Error.ERROR_PARAM_FORMAT,
                               append_msg=",%s不是字符串" % k)

        tuple_name = '%s_TUPLE' % k.upper()
        tuple_ = getattr(cls, tuple_name, None)
        if tuple_ is not None and isinstance(tuple_, tuple):
            flag = False
            for item in tuple_:
                if not isinstance(item, tuple):
                    return Ret(Error.ERROR_TUPLE_FORMAT,
                               append_msg='(%s)' % tuple_name)
                if dict_[k] == item[0]:
                    flag = True
            if not flag:
                return Ret(Error.ERROR_PARAM_FORMAT,
                           append_msg=',%s的值应该在%s之中' % (k, tuple_name))
        valid_func = getattr(cls, '_valid_%s' % k, None)
        if valid_func is not None and callable(valid_func):
            # print('_valid_', k)
            ret = valid_func(dict_[k])
            if ret.error is not Error.OK:
                return ret
    return Ret()
Exemple #20
0
def aes_encrypt(data):
    try:
        key = SECRET_KEY[:16]
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(key, AES.MODE_CFB, iv)
        encrypted_data = iv + cipher.encrypt(data)
        encrypted_data = base64.b64encode(encrypted_data).decode()
    except Exception as err:
        deprint(str(err))
        return Ret(Error.AES_ENCRYPT_ERROR)
    return Ret(encrypted_data)
Exemple #21
0
    def get_phrase_by_phrase(cls, phrase):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_phrase = cls.objects.get(phrase=phrase)
        except cls.DoesNotExist as err:
            deprint(str(err))
            return Ret(Error.NOT_FOUND_PHRASE)
        return Ret(o_phrase)
Exemple #22
0
    def get_config_by_key(cls, key):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_config = cls.objects.get(key=key)
        except Exception as err:
            deprint(str(err))
            return Ret(Error.NOT_FOUND_CONFIG)
        return Ret(o_config)
Exemple #23
0
def aes_decrypt(encrypted_data):
    try:
        encrypted_data = base64.b64decode(encrypted_data)
        key = SECRET_KEY[:16]
        iv = encrypted_data[:16]
        encrypted_data = encrypted_data[16:]
        cipher = AES.new(key, AES.MODE_CFB, iv)
        data = cipher.decrypt(encrypted_data).decode()
    except Exception as err:
        deprint(str(err))
        return Ret(Error.AES_DECRYPT_ERROR)
    return Ret(data)
Exemple #24
0
 def do_ss_off(self):
     if not self.ss_on:
         return Ret()
     import datetime
     crt_time = datetime.datetime.now().timestamp()
     if crt_time - self.ss_change_time < self.SS_CHANGE_INTERVAL:
         return Ret(Error.SS_OPERATION_FAST)
     Dealer.remove_port(self.port)
     self.ss_on = False
     self.ss_change_time = crt_time
     self.save()
     return Ret()
Exemple #25
0
 def do_ss_on(self):
     if self.ss_on:
         return Ret()
     import datetime
     crt_time = datetime.datetime.now().timestamp()
     if crt_time - self.ss_change_time < self.SS_CHANGE_INTERVAL:
         return Ret(Error.SS_OPERATION_FAST)
     Dealer.add_port(self.port, self.ss_pwd)
     self.ss_on = True
     self.ss_change_time = crt_time
     self.save()
     return Ret()
def require_root_func(request):
    """decorator, require root login"""
    ret = require_login_func(request)
    if ret.error is not Error.OK:
        return ret
    o_user = request.user
    from User.models import User
    if not isinstance(o_user, User):
        return Ret(Error.STRANGE)
    if o_user.pk != User.ROOT_ID:
        return Ret(Error.REQUIRE_ROOT)
    return Ret()
Exemple #27
0
def require_consider_func(request):
    ret = require_login_func(request)
    if ret.error is not Error.OK:
        return ret
    o_user = request.user

    from User.models import User
    if not isinstance(o_user, User):
        return Ret(Error.STRANGE)
    if not o_user.reviewer:
        return Ret(Error.REQUIRE_REVIEWER)

    return Ret()
Exemple #28
0
 def get_value_by_key(cls, key, default=__ConfigNone()):
     ret = cls._validate(locals())
     if ret.error is not Error.OK:
         return ret
     try:
         o_config = cls.objects.get(key=key)
     except Exception as err:
         deprint(str(err))
         if isinstance(default, cls.__ConfigNone):
             return Ret(Error.NOT_FOUND_CONFIG)
         else:
             return Ret(default)
     return Ret(o_config.value)
Exemple #29
0
    def create(cls, key):
        ret = cls._validate(locals())
        if ret.error is not Error.OK:
            return ret

        try:
            o_image = cls(
                key=key,
            )
            o_image.save()
        except Exception as err:
            deprint('Image-create', str(err))
            return Ret(Error.ERROR_CREATE_IMAGE, append_msg=str(err))
        return Ret(o_image)
Exemple #30
0
    def do_ss_reset(self):
        import datetime
        crt_time = datetime.datetime.now().timestamp()
        if crt_time - self.ss_change_time < self.SS_CHANGE_INTERVAL:
            return Ret(Error.SS_OPERATION_FAST)

        if self.ss_on:
            Dealer.remove_port(self.port)
        self.port = self.get_unique_port()
        self.ss_pwd = get_random_string(length=8)
        Dealer.add_port(self.port, self.ss_pwd)

        self.ss_on = True
        self.ss_change_time = crt_time
        self.save()
        return Ret()