Пример #1
0
class TagMap(models.Model):
    phrase = models.ForeignKey(
        Phrase,
        verbose_name='关联词语',
        on_delete=models.CASCADE,
    )

    tag = models.ForeignKey(
        Tag,
        verbose_name='关联标签',
        on_delete=models.CASCADE,
    )

    match = models.NullBooleanField(verbose_name='是否匹配',
                                    help_text='null未知 true匹配 false相反')

    class Meta:
        unique_together = ('phrase', 'tag')

    @classmethod
    def get(cls, phrase: Phrase, tag: Tag):
        try:
            return cls.objects.get(phrase=phrase, tag=tag)
        except cls.DoesNotExist:
            raise PhraseError.TAGMAP_NOT_FOUND(phrase.cy, tag.name)
        except Exception as err:
            raise PhraseError.GET_TAGMAP(phrase.cy,
                                         tag.name,
                                         debug_message=err)

    @classmethod
    def new_or_put(cls, phrase, tag, match=True):
        try:
            tagmap = cls.get(phrase, tag)
            tagmap.match = match
            tagmap.save()
        except E as e:
            if e.eis(PhraseError.TAGMAP_NOT_FOUND):
                try:
                    tagmap = cls(
                        phrase=phrase,
                        tag=tag,
                        match=match,
                    )
                    tagmap.save()
                except Exception as err:
                    raise PhraseError.CREATE_TAGMAP(phrase.cy,
                                                    tag.name,
                                                    debug_message=err)
            else:
                return e
        return tagmap

    def _readable_phrase(self):
        return self.phrase.d()

    def d(self):
        return self.dictor('phrase', 'match')
Пример #2
0
class Comment(models.Model):
    article = models.ForeignKey(
        'Article.Article',
        on_delete=models.CASCADE,
    )

    user = models.ForeignKey(
        'User.MiniUser',
        on_delete=models.CASCADE,
    )

    content = models.TextField()

    create_time = models.DateTimeField(auto_now_add=True, )

    reply_to = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        default=None,
    )

    selected = models.NullBooleanField(
        verbose_name='精选评论',
        default=None,
    )

    @classmethod
    def get(cls, cid):
        try:
            return cls.objects.get(pk=cid)
        except cls.DoesNotExist:
            raise ArticleError.NOT_FOUND_COMMENT

    @classmethod
    def create(cls, article, user, content):
        try:
            return cls.objects.create(
                article=article,
                user=user,
                content=content,
                reply_to=None,
                selected=False,
            )
        except Exception as err:
            raise ArticleError.CREATE_COMMENT(debug_message=err)

    def reply(self, user, content):
        reply_to = self.reply_to or self
        if reply_to and not self.article.allow_open_reply:
            if user not in [self.article.user, reply_to.user]:
                raise ArticleError.DENY_OPEN_REPLY

        try:
            return Comment.objects.create(
                article=self.article,
                user=user,
                content=content,
                reply_to=reply_to,
                selected=False,
            )
        except Exception as err:
            raise ArticleError.CREATE_COMMENT(debug_message=err)

    def assert_belongs_to(self, owner: Union[Article, User]):
        if isinstance(owner, Article):
            if self.article != owner:
                raise ArticleError.NOT_MATCH
        else:
            if owner not in [self.user, self.article.user]:
                raise ArticleError.NOT_OWNER

    def remove(self):
        self.delete()

    def _readable_create_time(self):
        return self.create_time.timestamp()

    def _readable_user(self):
        return self.user.d()

    def d(self):
        return self.dictify('content', 'create_time', 'user', 'pk->cid')

    def d_replies(self, show_all=False):
        replies = self.comment_set.all()
        if self.article.require_review and not show_all:
            replies = replies.filter(selected=True)
        d = dict(replies=replies.dict(Comment.d))
        d.update(self.d())
        return d
Пример #3
0
class Scope(models.Model):
    """权限类"""
    name = models.CharField(
        verbose_name='权限英文简短名称',
        max_length=20,
        unique=True,
    )
    desc = models.CharField(
        verbose_name='权限介绍',
        max_length=20,
    )
    always = models.NullBooleanField(
        verbose_name="Null 可有可无 True 一直可选 False 一直不可选",
        default=None,
    )
    detail = models.CharField(
        verbose_name='权限详细说明',
        max_length=100,
        default=None,
    )

    @classmethod
    def get_by_id(cls, sid):
        try:
            return cls.objects.get(pk=sid)
        except cls.DoesNotExist:
            raise AppError.SCOPE_NOT_FOUND

    @classmethod
    def get_by_name(cls, name):
        try:
            return cls.objects.get(name=name)
        except Exception:
            raise AppError.SCOPE_NOT_FOUND

    @classmethod
    def create(cls, name, desc, detail):
        try:
            scope = cls(
                name=name,
                desc=desc,
                detail=detail,
                always=None,
            )
            scope.save()
        except Exception:
            raise AppError.CREATE_SCOPE
        return scope

    def d(self):
        return self.dictify('name', 'desc', 'always', 'detail')

    @classmethod
    def list_to_scope_list(cls, scopes):
        scope_list = []
        if not isinstance(scopes, list):
            return []
        for scope_name in scopes:
            try:
                scope = cls.get_by_name(scope_name)
                if scope.always != False:  # 此处不能将 != False 删除 因为要考虑None的情况
                    scope_list.append(scope)
            except Exception:
                pass

        # 仍然存在always是True的但没有被添加的情况 于是double_check
        return cls.double_check(scope_list)

    @classmethod
    def double_check(cls, scope_list):
        final_list = []
        for scope in cls.objects.all():
            if scope.always:
                final_list.append(scope)
        for scope in scope_list:
            if scope.always is None:  # false被忽略,true已经添加
                final_list.append(scope)
        return final_list
Пример #4
0
class Resource(models.Model):
    """
    资源类
    根资源文件夹id=1
    一旦新增用户,就在根目录创建一个属于新增用户的文件夹
    """
    ROOT_ID = 1

    rname = models.CharField(
        verbose_name='resource name',
        max_length=256,
    )
    rtype = models.IntegerField(
        verbose_name='file or folder',
        choices=RtypeChoice.list(),
    )
    rsize = models.IntegerField(default=0, )
    sub_type = models.IntegerField(
        verbose_name='sub type',
        choices=StypeChoice.list(),
        default=StypeChoice.FOLDER.value,
    )
    mime = models.CharField(
        verbose_name='资源类型',
        null=True,
        default=True,
        max_length=100,
    )
    description = models.TextField(
        verbose_name='description in Markdown',
        null=True,
        blank=True,
        default=None,
    )
    cover = models.CharField(
        null=True,
        blank=True,
        default=None,
        max_length=1024,
    )
    owner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
    )
    parent = models.ForeignKey(
        'Resource',
        null=True,
        blank=True,
        default=0,
        on_delete=models.CASCADE,
    )
    dlpath = models.CharField(
        verbose_name='download relative path to res.6-79.cn',
        max_length=1024,
        default=None,
        null=True,
        blank=True,
    )
    status = models.IntegerField(
        choices=StatusChoice.list(),
        verbose_name='加密状态 0公开 1仅自己可见 2需要密码',
        default=StatusChoice.PUBLIC.value,
    )
    visit_key = models.CharField(
        max_length=16,
        min_length=3,
        verbose_name='当status为2时有效',
    )
    vk_change_time = models.FloatField(
        null=True,
        blank=True,
        default=0,
    )
    create_time = models.DateTimeField()
    dlcount = models.IntegerField(
        verbose_name='download number',
        default=0,
    )
    res_str_id = models.CharField(
        verbose_name='唯一随机资源ID,弃用res_id',
        default=None,
        null=True,
        blank=True,
        max_length=6,
        unique=True,
    )
    right_bubble = models.NullBooleanField(
        verbose_name='读取权限向上冒泡',
        default=True,
    )
    cover_type = models.IntegerField(
        choices=CoverChoice.list(),
        verbose_name='封面类型 0 上传图片 1 与父资源相同 2 与指定资源相同 3 外部URI链接',
        default=CoverChoice.RANDOM.value,
        null=0,
        blank=0,
    )

    @classmethod
    def get_unique_id(cls):
        while True:
            res_str_id = get_random_string(length=6)
            try:
                cls.get_by_id(res_str_id)
            except E as ret:
                if ret.eis(ResourceError.RESOURCE_NOT_FOUND):
                    return res_str_id

    @staticmethod
    def _valid_rname(rname):
        """验证rname属性"""
        invalid_chars = '\\/*:\'"|<>?'
        for char in invalid_chars:
            if char in rname:
                raise ResourceError.INVALID_RNAME

    @staticmethod
    def _valid_res_parent(parent):
        """验证parent属性"""
        if not isinstance(parent, Resource):
            raise BaseError.STRANGE
        if parent.rtype != RtypeChoice.FOLDER.value:
            raise ResourceError.FILE_PARENT

    @classmethod
    def create_abstract(cls, rname, rtype, desc, user, parent, dlpath, rsize,
                        sub_type, mime):
        crt_time = datetime.datetime.now()

        return cls(
            rname=rname,
            rtype=rtype,
            mime=mime,
            description=desc,
            cover=None,
            cover_type=CoverChoice.SELF.value if sub_type
            == StypeChoice.IMAGE.value else CoverChoice.RANDOM.value,
            owner=user,
            parent=parent,
            dlpath=dlpath,
            status=StatusChoice.PRIVATE.value,
            visit_key=get_random_string(length=4),
            create_time=crt_time,
            vk_change_time=crt_time.timestamp(),
            rsize=rsize,
            sub_type=sub_type,
            res_str_id=cls.get_unique_id(),
            dlcount=0,
            right_bubble=True,
        )

    @classmethod
    def create_file(cls, rname, user, res_parent, dlpath, rsize, sub_type,
                    mime):
        """ 创建文件对象

        :param mime: 七牛返回的资源类型
        :param rname: 文件名
        :param user: 所属用户
        :param res_parent: 所属目录
        :param dlpath: 七牛存储的key
        :param rsize: 文件大小
        :param sub_type: 文件分类
        :return: Ret对象,错误返回错误代码,成功返回文件对象
        """
        try:
            res = cls.create_abstract(
                rname=rname,
                rtype=RtypeChoice.FILE.value,
                desc=None,
                user=user,
                parent=res_parent,
                dlpath=dlpath,
                rsize=rsize,
                sub_type=sub_type,
                mime=mime,
            )
            res.save()
        except Exception:
            raise ResourceError.CREATE_FILE
        return res

    @classmethod
    def create_folder(cls, rname, user, res_parent, desc=None):
        """ 创建文件夹对象

        :param rname: 文件夹名
        :param user: 所属用户
        :param res_parent: 所属目录
        :param desc: 描述说明
        :return: Ret对象,错误返回错误代码,成功返回文件夹对象
        """
        try:
            res = cls.create_abstract(
                rname=rname,
                rtype=RtypeChoice.FOLDER.value,
                desc=desc,
                user=user,
                parent=res_parent,
                dlpath=None,
                rsize=0,
                sub_type=StypeChoice.FOLDER.value,
                mime=None,
            )
            res.save()
        except Exception:
            raise ResourceError.CREATE_FOLDER
        return res

    @classmethod
    def create_link(cls, rname, user, res_parent, dlpath):
        """ 创建链接对象

        :param rname: 链接名称
        :param user: 所属用户
        :param res_parent: 所在目录
        :param dlpath: 链接地址
        :return: Ret对象,错误返回错误代码,成功返回链接对象
        """
        try:
            res = cls.create_abstract(
                rname=rname,
                rtype=RtypeChoice.LINK,
                desc=None,
                user=user,
                parent=res_parent,
                dlpath=dlpath,
                rsize=0,
                sub_type=StypeChoice.LINK.value,
                mime=None,
            )
            res.save()
        except Exception:
            raise ResourceError.CREATE_LINK
        return res

    """
    查询方法
    """

    @classmethod
    def get_by_id(cls, res_str_id):
        try:
            res = cls.objects.get(res_str_id=res_str_id)
        except cls.DoesNotExist:
            raise ResourceError.RESOURCE_NOT_FOUND
        return res

    @classmethod
    def get_by_pk(cls, res_id):
        """根据资源id获取资源对象"""
        try:
            res = cls.objects.get(pk=res_id)
        except cls.DoesNotExist:
            raise ResourceError.RESOURCE_NOT_FOUND
        return res

    def belong(self, user):
        """判断资源是否属于用户"""
        return self.owner.pk == user.pk

    def is_home(self):
        return self.parent.pk == Resource.ROOT_ID

    def get_cover_urls(self):
        """获取封面链接"""
        res = self
        cover = None
        while res.pk != Resource.ROOT_ID:
            if res.cover_type == CoverChoice.PARENT.value:
                res = res.parent
            elif res.cover_type == CoverChoice.RESOURCE.value:
                try:
                    res = Resource.get_by_id(res.cover)
                except E:
                    return None, None
                if not res.belong(self.owner):
                    return None, None
            else:
                cover = res.cover
                break
        if res.cover_type == CoverChoice.SELF.value:
            if res.sub_type == StypeChoice.IMAGE.value:
                from Base.qn_manager import qn_res_manager
                return (qn_res_manager.get_resource_url(res.dlpath),
                        qn_res_manager.get_resource_url("%s-small" %
                                                        res.dlpath))
        if cover is None:
            return None, None
        if res.cover_type == CoverChoice.UPLOAD.value:
            from Base.qn_manager import qn_res_manager
            return (qn_res_manager.get_resource_url(cover),
                    qn_res_manager.get_resource_url("%s-small" % cover))
        else:
            return cover, cover

    """
    字典方法
    """

    def _readable_owner(self):
        return self.owner.d()

    def _readable_create_time(self):
        return self.create_time.timestamp()

    def _readable_visit_key(self):
        return self.visit_key if self.status == StatusChoice.PROTECT.value else None

    def _readable_is_home(self):
        return self.is_home()

    def _readable_secure_env(self):
        if self.pk == Resource.ROOT_ID or \
                not self.right_bubble or \
                self.status == StatusChoice.PUBLIC.value:
            return True
        res = self.parent
        while res.pk != Resource.ROOT_ID:
            if res.status == StatusChoice.PUBLIC.value:
                return res.rname
            if not res.right_bubble:
                break
            res = res.parent
        return True

    def _readable_raw_cover(self):
        return self.cover

    def _readable_parent_str_id(self):
        return self.parent.res_str_id

    def d(self):
        dict_ = self.dictify('res_str_id', 'rname', 'rtype', 'rsize',
                             'sub_type', 'description', 'cover_type', 'owner',
                             'parent_str_id', 'status', 'create_time',
                             'dlcount', 'visit_key', 'is_home', 'right_bubble',
                             'secure_env', 'raw_cover')
        cover_urls = self.get_cover_urls()
        dict_.update(dict(
            cover=cover_urls[0],
            cover_small=cover_urls[1],
        ))
        return dict_

    def d_base(self):
        dict_ = self.dictify('status', 'is_home', 'owner', 'create_time',
                             'right_bubble')
        cover_urls = self.get_cover_urls()
        dict_.update(dict(
            cover=cover_urls[0],
            cover_small=cover_urls[1],
        ))
        return dict_

    def d_child(self):
        dict_ = self.dictify('res_str_id', 'rname', 'rtype', 'status',
                             'create_time', 'sub_type', 'dlcount')
        cover_urls = self.get_cover_urls()
        dict_.update(dict(cover_small=cover_urls[1], ))
        return dict_

    def d_layer(self):
        child_list = Resource.objects.filter(parent=self).dict(
            Resource.d_child)
        return dict(
            info=self.d(),
            child_list=child_list,
        )

    def d_child_selector(self):
        return self.dictify('res_str_id', 'rname', 'rtype', 'sub_type')

    def d_selector_layer(self):
        child_list = Resource.objects.filter(parent=self).dict(
            Resource.d_child_selector)
        info = self.dictify('is_home', 'res_str_id', 'rname', 'parent_str_id')
        return dict(
            info=info,
            child_list=child_list,
        )

    """
    查询方法
    """

    @classmethod
    def get_root_folder(cls, user):
        """获取当前用户的根目录"""
        try:
            res = cls.objects.get(owner=user,
                                  parent=1,
                                  rtype=RtypeChoice.FOLDER.value)
        except cls.DoesNotExist:
            raise ResourceError.GET_ROOT_FOLDER
        return res

    def readable(self, user, visit_key):
        """判断当前资源是否被当前用户可读"""
        res = self
        while res.pk != Resource.ROOT_ID:
            if res.owner == user or res.status == StatusChoice.PUBLIC.value:
                return True
            if res.status == StatusChoice.PROTECT.value and res.visit_key == visit_key:
                if user:
                    UserRight.update(user, res)
                return True
            if res.status == StatusChoice.PROTECT.value and UserRight.verify(
                    user, res):
                return True
            if not res.right_bubble:
                break
            res = res.parent
            visit_key = None
        return False

    def get_dl_url(self):
        """获取当前资源的下载链接"""
        self.dlcount += 1
        self.save()
        if self.rtype == RtypeChoice.LINK:
            return self.dlpath
        from Base.qn_manager import qn_res_manager
        return qn_res_manager.get_resource_url(self.dlpath)

    def get_visit_key(self):
        """获取当前资源的访问密码"""
        if self.status == StatusChoice.PROTECT.value:
            return self.visit_key
        return None

    """
    修改方法
    """

    def modify_rname(self, rname):
        key = self.dlpath
        new_key = '%s/%s' % (key[:key.rfind('/')], rname)
        from Base.qn_manager import qn_res_manager
        qn_res_manager.move_res(key, new_key)
        self.rname = rname
        self.dlpath = new_key
        self.save()

    def modify_info(self, rname, description, status, visit_key, right_bubble,
                    parent):
        """ 修改资源属性

        :param rname: 资源名称
        :param description: 资源介绍
        :param status: 资源分享类型(公开、私有、加密)
        :param visit_key: 资源加密密钥
        :param right_bubble: 资源读取权限是否向上查询
        :param parent: 移动后的新父目录
        :return: Ret对象,错误返回错误代码,成功返回资源对象
        """
        if rname is None:
            rname = self.rname
        if description is None:
            description = self.description or ''
        if status is None:
            status = self.status
        if visit_key is None:
            visit_key = self.visit_key
        if right_bubble is None:
            right_bubble = self.right_bubble
        if parent is None:
            parent = self.parent

        if self.rname != rname:
            if self.rtype == RtypeChoice.FILE.value:
                self.modify_rname(rname)
            else:
                self.rname = rname
        self.description = description
        self.status = status
        self.right_bubble = right_bubble
        self.parent = parent
        if status == StatusChoice.PROTECT.value:
            if self.visit_key != visit_key:
                self.visit_key = visit_key
                self.vk_change_time = datetime.datetime.now().timestamp()
        self.save()

    def modify_cover(self, cover, cover_type):
        """修改资源封面"""
        from Base.qn_manager import qn_res_manager
        if self.cover_type == CoverChoice.UPLOAD.value:
            try:
                qn_res_manager.delete_res(self.cover)
            except:
                pass
        self.cover = cover
        self.cover_type = cover_type
        self.save()
        return self

    def is_empty(self):
        """ 资源是否为空(针对文件夹资源) """
        res_list = Resource.objects.filter(parent=self)
        if res_list:
            return False
        return True

    def remove(self):
        """ 删除资源 """
        if self.rtype == RtypeChoice.FOLDER.value:
            if not self.is_empty():
                raise ResourceError.REQUIRE_EMPTY_FOLDER
        from Base.qn_manager import qn_res_manager
        if self.cover and self.cover_type == CoverChoice.UPLOAD.value:
            qn_res_manager.delete_res(self.cover)
            self.cover = None
            self.save()
        if self.rtype == RtypeChoice.FILE.value:
            qn_res_manager.delete_res(self.dlpath)
        self.delete()
Пример #5
0
class User(models.Model):
    """
    用户类
    根超级用户id=1
    """
    ROOT_ID = 1

    VERIFY_STATUS_UNVERIFIED = 0
    VERIFY_STATUS_UNDER_AUTO = 1
    VERIFY_STATUS_UNDER_MANUAL = 2
    VERIFY_STATUS_DONE = 3
    VERIFY_STATUS_TUPLE = (
        (VERIFY_STATUS_UNVERIFIED, '没有认证'),
        (VERIFY_STATUS_UNDER_AUTO, '自动认证阶段'),
        (VERIFY_STATUS_UNDER_MANUAL, '人工认证阶段'),
        (VERIFY_STATUS_DONE, '成功认证'),
    )

    VERIFY_CHINA = 0
    VERIFY_ABROAD = 1
    VERIFY_TUPLE = (
        (VERIFY_CHINA, '中国大陆身份证认证'),
        (VERIFY_ABROAD, '其他地区身份认证'),
    )

    user_str_id = models.CharField(
        verbose_name='唯一随机用户ID',
        default=None,
        null=True,
        blank=True,
        max_length=32,
        unique=True,
    )
    qitian = models.CharField(
        default=None,
        unique=True,
        max_length=20,
        min_length=4,
    )
    phone = models.CharField(
        default=None,
        unique=True,
        max_length=20,
    )
    password = models.CharField(
        max_length=32,
        min_length=6,
    )
    salt = models.CharField(
        max_length=10,
        default=None,
    )
    pwd_change_time = models.FloatField(
        null=True,
        blank=True,
        default=0,
    )
    avatar = models.CharField(
        default=None,
        null=True,
        blank=True,
        max_length=1024,
    )
    nickname = models.CharField(
        max_length=10,
        default=None,
    )
    description = models.CharField(
        max_length=20,
        default=None,
        blank=True,
        null=True,
    )
    qitian_modify_time = models.IntegerField(
        verbose_name='齐天号被修改的次数',
        help_text='一般只能修改一次',
        default=0,
    )
    birthday = models.DateField(
        verbose_name='生日',
        default=None,
        null=True,
    )
    email = models.EmailField(
        verbose_name='邮箱',
        default=None,
        null=True,
    )

    verify_status = models.SmallIntegerField(
        verbose_name='是否通过实名认证',
        default=0,
        choices=VERIFY_STATUS_TUPLE,
    )
    real_verify_type = models.SmallIntegerField(
        verbose_name='实名认证类型',
        default=None,
        null=True,
    )
    real_name = models.CharField(
        verbose_name='真实姓名',
        default=None,
        max_length=32,
        null=True,
    )
    male = models.NullBooleanField(
        verbose_name='是否为男性',
        default=None,
        null=True,
    )
    idcard = models.CharField(
        verbose_name='身份证号',
        default=None,
        max_length=18,
        choices=VERIFY_TUPLE,
        null=True,
    )
    card_image_front = models.CharField(
        verbose_name='身份证正面照',
        max_length=1024,
        default=None,
        null=True,
    )
    card_image_back = models.CharField(
        verbose_name='身份证背面照',
        max_length=1024,
        default=None,
        null=True,
    )
    is_dev = models.BooleanField(
        verbose_name='是否开发者',
        default=False,
    )

    @classmethod
    def get_unique_id(cls):
        while True:
            user_str_id = get_random_string(length=6)
            try:
                cls.get_by_str_id(user_str_id)
            except E as e:
                if e.eis(UserError.USER_NOT_FOUND):
                    return user_str_id

    @classmethod
    def get_unique_qitian(cls):
        while True:
            qitian_id = get_random_string(length=8)
            try:
                cls.get_by_qitian(qitian_id)
            except E as e:
                if e.eis(UserError.USER_NOT_FOUND):
                    return qitian_id

    @staticmethod
    def _valid_qitian(qitian):
        """验证齐天号合法"""
        valid_chars = '^[A-Za-z0-9_]{4,20}$'
        if re.match(valid_chars, qitian) is None:
            raise UserError.INVALID_QITIAN

    @staticmethod
    def _valid_password(password):
        """验证密码合法"""
        valid_chars = '^[A-Za-z0-9!@#$%^&*()_+-=,.?;:]{6,16}$'
        if re.match(valid_chars, password) is None:
            raise UserError.INVALID_PASSWORD

    @staticmethod
    def _valid_birthday(birthday):
        """验证生日是否合法"""
        import datetime
        if birthday > datetime.datetime.now().date():
            raise UserError.BIRTHDAY_FORMAT

    @staticmethod
    def hash_password(raw_password, salt=None):
        if not salt:
            salt = get_random_string(length=6)
        hash_password = User._hash(raw_password + salt)
        return salt, hash_password

    @classmethod
    def create(cls, phone, password):
        salt, hashed_password = User.hash_password(password)

        User.exist_with_phone(phone)

        try:
            user = cls(
                qitian=cls.get_unique_qitian(),
                phone=phone,
                password=hashed_password,
                salt=salt,
                avatar=None,
                nickname='',
                description=None,
                qitian_modify_time=0,
                user_str_id=cls.get_unique_id(),
                birthday=None,
                verify_status=cls.VERIFY_STATUS_UNVERIFIED,
                is_dev=False,
            )
            user.save()
        except Exception as err:
            raise UserError.CREATE_USER(debug_message=err)
        return user

    def modify_password(self, password):
        self.salt, self.password = User.hash_password(password)
        import datetime
        self.pwd_change_time = datetime.datetime.now().timestamp()
        self.save()

    def change_password(self, password, old_password):
        """修改密码"""
        if self.password != User._hash(old_password + self.salt):
            raise UserError.PASSWORD
        self.salt, self.password = User.hash_password(password)
        import datetime
        self.pwd_change_time = datetime.datetime.now().timestamp()
        self.save()

    @staticmethod
    def _hash(s):
        from Base.common import md5
        return md5(s)

    @classmethod
    def get_by_str_id(cls, user_str_id):
        try:
            return cls.objects.get(user_str_id=user_str_id)
        except cls.DoesNotExist:
            raise UserError.USER_NOT_FOUND

    @classmethod
    def get_by_phone(cls, phone):
        """根据手机号获取用户对象"""
        try:
            return cls.objects.get(phone=phone)
        except cls.DoesNotExist:
            raise UserError.USER_NOT_FOUND('手机号未注册')

    @classmethod
    def exist_with_phone(cls, phone):
        try:
            cls.objects.get(phone=phone)
        except cls.DoesNotExist:
            return
        raise UserError.PHONE_EXIST

    @classmethod
    def get_by_qitian(cls, qitian_id):
        try:
            return cls.objects.get(qitian=qitian_id)
        except cls.DoesNotExist:
            raise UserError.USER_NOT_FOUND('不存在的齐天号')

    @classmethod
    def exist_with_qitian(cls, qitian_id):
        try:
            cls.objects.get(qitian=qitian_id)
        except cls.DoesNotExist:
            return
        raise UserError.QITIAN_EXIST

    @classmethod
    def get_by_id(cls, user_id):
        """根据用户ID获取用户对象"""
        try:
            return cls.objects.get(pk=user_id)
        except cls.DoesNotExist:
            raise UserError.USER_NOT_FOUND

    def allow_qitian_modify(self):
        return self.qitian_modify_time == 0

    def _readable_avatar(self):
        return self.get_avatar_url()

    def _readable_birthday(self):
        return self.birthday.strftime('%Y-%m-%d') if self.birthday else None

    def _readable_allow_qitian_modify(self):
        return int(self.allow_qitian_modify())

    def d_oauth(self):
        return self.dictify('avatar', 'nickname', 'description')

    def d_base(self):
        return self.dictify('user_str_id', 'avatar', 'nickname', 'description')

    def d(self):
        return self.dictify('birthday', 'user_str_id', 'qitian', 'avatar',
                            'nickname', 'description', 'allow_qitian_modify',
                            'verify_status', 'verify_type', 'is_dev')

    @classmethod
    def authenticate(cls, qitian, phone, password):
        """验证手机号和密码是否匹配"""
        if qitian:
            user = cls.get_by_qitian(qitian)
        else:
            user = cls.get_by_phone(phone)

        salt, hashed_password = User.hash_password(password, user.salt)
        if hashed_password == user.password:
            return user
        raise UserError.PASSWORD

    def get_avatar_url(self, small=True):
        """获取用户头像地址"""
        if self.avatar is None:
            return None
        from Base.qn import qn_public_manager
        key = "%s-small" % self.avatar if small else self.avatar
        return qn_public_manager.get_resource_url(key)

    def get_card_urls(self):
        from Base.qn import qn_res_manager
        front_url = qn_res_manager.get_resource_url(self.card_image_front) \
            if self.card_image_front else None
        back_url = qn_res_manager.get_resource_url(self.card_image_back) \
            if self.card_image_back else None
        return dict(
            front=front_url,
            back=back_url,
        )

    def modify_avatar(self, avatar):
        """修改用户头像"""
        if self.avatar:
            from Base.qn import qn_public_manager
            qn_public_manager.delete_res(self.avatar)
        self.avatar = avatar
        self.save()

    def upload_verify_front(self, card_image_front):
        from Base.qn import qn_res_manager
        if self.card_image_front:
            qn_res_manager.delete_res(self.card_image_front)

        self.card_image_front = card_image_front
        self.save()
        qn_res_manager.get_resource_url(self.card_image_front + '-small')

    def upload_verify_back(self, card_image_back):
        from Base.qn import qn_res_manager
        if self.card_image_back:
            qn_res_manager.delete_res(self.card_image_back)

        self.card_image_back = card_image_back
        self.save()
        qn_res_manager.get_resource_url(self.card_image_back + '-small')

    def modify_info(self, nickname, description, qitian, birthday):
        """修改用户信息"""
        if nickname is None:
            nickname = self.nickname
        if description is None:
            description = self.description
        if qitian is None:
            qitian = self.qitian
        if birthday is None or (self.verify_status and self.real_verify_type
                                == User.VERIFY_CHINA):
            birthday = self.birthday

        if self.allow_qitian_modify():
            if self.qitian != qitian:
                self.exist_with_qitian(qitian)
                self.qitian = qitian
                self.qitian_modify_time += 1
        self.nickname = nickname
        self.description = description
        self.birthday = birthday
        self.save()

    def update_card_info(self, real_name, male, idcard, birthday):
        self.real_name = real_name
        self.male = male
        self.idcard = idcard
        self.birthday = birthday
        try:
            self.save()
        except Exception as err:
            return IDCardError.AUTO_VERIFY_FAILED(debug_message=err)

    def update_verify_status(self, status):
        self.verify_status = status
        self.save()

    def update_verify_type(self, verify_type):
        self.real_verify_type = verify_type
        self.save()

    def developer(self):
        self.is_dev = True
        self.save()