Example #1
0
class ServiceData(models.Model):
    """服务数据"""
    service = models.CharField(
        max_length=10,
    )

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

    data = models.TextField(
        null=True,
        default=None,
    )

    parameters = models.TextField(
        null=True,
        default=None,
    )

    interact_times = models.IntegerField(default=1)

    @classmethod
    def get_or_create(cls, service, user):
        if not isinstance(service, str):
            service = service.name

        try:
            service_data = cls.objects.get(service=service, user=user)
            service_data.interact()
            return service_data
        except cls.DoesNotExist:
            return cls.objects.create(service=service, user=user)

    def interact(self):
        self.interact_times = F('interact_times') + 1
        self.save()
        self.refresh_from_db()

    def jsonify(self):
        data = self.data or '{}'
        return json.loads(data)

    def classify(self):
        return Classify(self.jsonify())

    def update(self, data):
        if isinstance(data, Classify):
            data = data.dict()
        self.data = json.dumps(data, ensure_ascii=False)
        self.save()

    def fetch_parameters(self):
        return json.loads(self.parameters or '{}')

    def store_parameters(self, parameters):
        self.parameters = json.dumps(parameters, ensure_ascii=False)
        self.save()
Example #2
0
class Paragraph(models.Model):
    content = models.TextField()

    section = models.BooleanField()

    economist = models.ForeignKey(
        Economist,
        on_delete=models.CASCADE,
    )

    words = models.IntegerField(
        default=0,
    )

    @classmethod
    def create(cls, content: str, **kwargs):
        try:
            return cls.objects.create(
                content=content,
                words=len(content.split(' ')),
                **kwargs
            )
        except Exception:
            raise EconomistError.PARAGRAPH_CREATE

    @classmethod
    def get(cls, economist: Economist):
        return cls.objects.filter(economist=economist).order_by('pk')

    def d(self):
        return self.dictify('content', 'section')
Example #3
0
class Economist(models.Model):
    news_id = models.CharField(
        max_length=4,
        min_length=4,
    )

    date = models.CharField(
        max_length=10,
        min_length=10,
    )

    category = models.TextField()

    sub_headline = models.TextField()

    headline = models.TextField()

    description = models.TextField()

    image = models.TextField()

    url = models.TextField(default=None)

    @classmethod
    def get(cls, news_id):
        try:
            return cls.objects.get(news_id=news_id)
        except cls.DoesNotExist:
            raise EconomistError.GET

    @classmethod
    def generate_id(cls):
        while True:
            news_id = get_random_string(length=4)
            try:
                cls.get(news_id)
            except E as e:
                assert e.eis(EconomistError.GET)
                return news_id

    @classmethod
    def create(cls, **kwargs):
        try:
            return cls.objects.create(
                news_id=cls.generate_id(),
                **kwargs,
            )
        except Exception:
            raise EconomistError.CREATE

    def d_list(self):
        return self.dictify('news_id', 'date', 'category', 'headline', 'sub_headline', 'description', 'image')

    def d(self):
        d_ = self.d_list()
        d_.update(dict(paragraph=Paragraph.get(self)))
        return d_
Example #4
0
class Actions(models.Model):
    member = models.ForeignKey('Room.Member', on_delete=models.CASCADE)
    room = models.ForeignKey(
        'Room.Room',
        on_delete=models.CASCADE,
    )
    content = models.TextField(default=None, null=True)
    create_time = models.DateTimeField(auto_now_add=True)

    def d(self):
        return self.dictor('pk->aid', 'member', 'room', 'content',
                           'create_time')

    def _readable_member(self):
        return self.member.d_username()

    def _readable_room(self):
        return self.room.d_number()

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

    @staticmethod
    def get_actions(room):
        actions = []
        for action in Actions.objects.filter(
                room=room).order_by("-create_time"):
            actions.append(action.d())
        return actions

    @classmethod
    def create_action(cls, member, content, room):
        if content:
            try:
                action = cls(member=member, room=room, content=content)
                action.save()
            except Exception as err:
                raise RoomError.CREATE_ACTION(room.number,
                                              member.user.username,
                                              debug_message=err)
        room.room_change_speaker()
        return dict(next_speaker=room.speaker)
Example #5
0
class Collocation(models.Model):
    word = models.CharField(max_length=20, )

    collocation = models.TextField()
Example #6
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
Example #7
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()
Example #8
0
class Poem(models.Model):
    title = models.CharField(
        verbose_name='诗名',
        max_length=100,
    )

    content = models.TextField(
        verbose_name='正文',
    )

    create_time = models.DateTimeField(
        verbose_name='发布时间',
    )

    user = models.ForeignKey(
        'User.User',
        verbose_name='作者',
        default=None,
        null=True,
        on_delete=models.SET_NULL,
    )

    @classmethod
    def create(cls, title, content, user):
        crt_time = datetime.datetime.now()

        try:
            poem = cls(
                user=user,
                title=title,
                content=content,
                create_time=crt_time,
            )
            poem.save()
            return poem
        except Exception as err:
            raise PoemError.CREATE_POEM(debug_message=err)

    """
    查询函数
    """

    @classmethod
    def get_by_id(cls, poem_id):
        try:
            return cls.objects.get(pk=poem_id)
        except cls.DoesNotExist:
            raise PoemError.POEM_NOT_FOUND

    def belong(self, user):
        return self.user == user

    """
    筛选函数
    """

    @staticmethod
    def _search_keyword(v):
        return Q(title__contains=v) | Q(content__contains=v)

    """
    字典函数
    """

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

    def d_create(self):
        return self.dictor('pk->id')

    def d_list(self):
        return self.dictor('pk->id', 'title', 'create_time')

    def d(self):
        return self.dictor('title', 'content', 'create_time')

    """
    修改函数
    """

    def update(self, title, content):
        self.title = title
        self.content = content
        self.create_time = datetime.datetime.now()
        self.save()
Example #9
0
class Meat(models.Model):
    """
    肉类(任务)
    """
    # 天鹅肉
    content = models.TextField(
        default=None,
        null=True,
    )
    # 天鹅肉所有者
    toad = models.ForeignKey(
        'User.User',
        related_name='toad_user',
        on_delete=models.CASCADE,
    )
    # 目标时间
    target_time = models.DateTimeField(
        null=True
    )
    # 创建时间
    create_time = models.DateTimeField(
        auto_now_add=True

    )
    # 肉质及状态
    # 0还没熟
    # 1熟了(已到时间)
    # 2吃上了
    # 3下次一定
    status = models.IntegerField(
        default=0
    )
    # 短信提醒开关
    notification = models.BooleanField(
        # 是否开启短信提醒功能
        default=False
    )
    # 标记
    achieve = models.BooleanField(
        default=False
    )

    @classmethod
    def create(cls, user, content, target_time, notification):
        print("create++++++++++++++++")
        try:
            meat = cls(
                content=content,
                toad=user,
                target_time=target_time,
                create_time=datetime.datetime.now(),
                status=0,
                notification=notification,
                achieve=False
            )
            meat.save()
            user.add_meat_quantity()
        except Exception as err:
            raise MeatError.CREATE_MEAT(debug_message=err)
        return meat

    @classmethod
    def change_meat_status(cls, meat, status):
        try:
            meat.status = status
            meat.save()
        except Exception:
            raise MeatError.CHANGE_MEAT_STATUS
        if not meat.achieve and status > 1:
            cls.change_meat_achieve(meat, True)
        return meat

    @classmethod
    def check_target_time(cls):
        try:
            meats = cls.objects.filter(achieve=False)
            now_time = datetime.datetime.now()
            change_list = []
            for meat in meats:
                if now_time > meat.target_time:
                    m = cls.change_meat_status(meat, 1)
                    change_list.append(m.d_meat_list())
        except Exception as err:
            raise MeatError.CHECK_TARGET_TIME(debug_message=err)
        return change_list

    @staticmethod
    def change_meat_achieve(meat, achieve):
        try:
            meat.achieve = achieve
            meat.save()
        except Exception:
            raise MeatError.CHANGE_MEAT_ACHIEVE
        meat.toad.reduce_meat_quantity()

    @classmethod
    def get_meat_by_pk(cls, tid):
        try:
            return cls.objects.get(pk=tid)
        except Exception:
            raise MeatError.GET_MEAT_BY_PK

    @classmethod
    def get_meat_list(cls, user):
        pass

    def d(self):
        return self.dictor('pk->mid', 'content', 'toad', 'target_time->time', 'create_time', 'status', 'notification',
                           'achieve')

    def     d_meat_list(self):
        return self.dictor('pk->mid', 'content', 'status', 'achieve', 'target_time->time')

    def _readable_toad(self):
        if self.toad:
            return self.toad.d()

    def _readable_target_time(self):
        return self.target_time.timestamp()

    def _readable_create_time(self):
        return self.create_time.timestamp()
Example #10
0
class App(models.Model):
    R_USER = '******'
    R_OWNER = 'owner'
    R_NONE = 'none'
    R_LIST = [R_USER, R_OWNER, R_NONE]

    name = models.CharField(
        verbose_name='应用名称',
        max_length=32,
        min_length=2,
        unique=True,
    )
    id = models.CharField(
        verbose_name='应用唯一ID',
        max_length=32,
        primary_key=True,
    )
    secret = models.CharField(
        verbose_name='应用密钥',
        max_length=32,
    )
    redirect_uri = models.URLField(
        verbose_name='应用跳转URI',
        max_length=512,
    )
    test_redirect_uri = models.URLField(
        verbose_name='测试环境下的应用跳转URI',
        max_length=512,
        default=None,
    )
    scopes = models.ManyToManyField(
        'Scope',
        default=None,
    )
    premises = models.ManyToManyField(
        'Premise',
        default=None,
    )
    owner = models.ForeignKey(
        'User.User',
        on_delete=models.CASCADE,
        db_index=True,
    )
    field_change_time = models.FloatField(
        null=True,
        blank=True,
        default=0,
    )
    desc = models.CharField(
        max_length=32,
        default=None,
    )
    logo = models.CharField(
        default=None,
        null=True,
        blank=True,
        max_length=1024,
    )
    mark = models.SlugField(
        default='0-0-0-0-0',
        verbose_name='1-5分评分人数',
    )
    info = models.TextField(
        default=None,
        verbose_name='应用介绍信息',
        null=True,
    )
    user_num = models.IntegerField(
        default=0,
        verbose_name='用户人数',
    )
    create_time = models.DateTimeField(
        default=None,
    )
    max_user_num = models.IntegerField(
        default=0,
        verbose_name='最多注册用户'
    )

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

    @classmethod
    def exist_with_name(cls, name):
        try:
            cls.objects.get(name=name)
        except cls.DoesNotExist:
            return
        raise AppError.EXIST_APP_NAME

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

    @classmethod
    def get_unique_app_id(cls):
        while True:
            app_id = get_random_string(length=8)
            try:
                cls.get_by_id(app_id)
            except E as e:
                if e.eis(AppError.APP_NOT_FOUND):
                    return app_id

    @classmethod
    def create(cls, name, desc, redirect_uri, test_redirect_uri, scopes, premises, owner):
        cls.exist_with_name(name)

        try:
            crt_time = datetime.datetime.now()
            app = cls(
                name=name,
                desc=desc,
                id=cls.get_unique_app_id(),
                secret=get_random_string(length=32),
                redirect_uri=redirect_uri,
                test_redirect_uri=test_redirect_uri,
                owner=owner,
                field_change_time=datetime.datetime.now().timestamp(),
                info=None,
                create_time=crt_time,
            )
            app.save()
            app.scopes.add(*scopes)
            app.premises.add(*premises)
            app.save()
        except Exception as err:
            raise AppError.CREATE_APP(debug_message=err)
        return app

    def modify_test_redirect_uri(self, test_redirect_uri):
        self.test_redirect_uri = test_redirect_uri
        self.save()

    def modify(self, name, desc, info, redirect_uri, scopes, premises, max_user_num):
        """修改应用信息"""
        self.name = name
        self.desc = desc
        self.info = info
        self.redirect_uri = redirect_uri
        self.max_user_num = max_user_num
        for scope in self.scopes.all():
            self.scopes.remove(scope)
        self.scopes.add(*scopes)
        for premise in self.premises.all():
            self.premises.remove(premise)
        self.premises.add(*premises)
        self.field_change_time = datetime.datetime.now().timestamp()
        try:
            self.save()
        except Exception as err:
            raise AppError.MODIFY_APP(debug_message=err)

    def _readable_app_name(self):
        return self.name

    def _readable_app_id(self):
        return self.id

    def _readable_app_desc(self):
        return self.desc

    def _readable_logo(self, small=True):
        if self.logo is None:
            return None
        from Base.qn import qn_public_manager
        key = "%s-small" % self.logo if small else self.logo
        return qn_public_manager.get_resource_url(key)

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

    def _readable_app_info(self):
        return self.info

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

    def _readable_mark(self):
        return list(map(int, self.mark.split('-')))

    def mark_as_list(self):
        return self._readable_mark()

    def _readable_scopes(self):
        scopes = self.scopes.all()
        return list(map(lambda s: s.d(), scopes))

    def _readable_premises(self):
        premises = self.premises.all()
        return list(map(lambda p: p.d(), premises))

    def d(self):
        return self.dictify(
            'app_name', 'app_id', 'app_desc', 'app_info', 'user_num', ('logo', False),
            'redirect_uri', 'create_time', 'owner', 'mark', 'scopes', 'premises',
            'test_redirect_uri', 'max_user_num')

    def d_user(self, user):
        dict_ = self.d()
        dict_.update(dict(premises=self.check_premise(user)))
        return dict_

    def d_base(self):
        return self.dictify('app_name', 'app_id', 'logo', 'app_desc', 'user_num', 'create_time')

    def modify_logo(self, logo):
        """修改应用logo"""
        from Base.qn import qn_public_manager
        if self.logo:
            qn_public_manager.delete_res(self.logo)
        self.logo = logo
        self.save()

    def is_user_full(self):
        if self.max_user_num == 0:
            return False
        return self.max_user_num >= self.user_num

    def belong(self, user):
        return self.owner == user

    def authentication(self, app_secret):
        return self.secret == app_secret

    def check_premise(self, user):
        premises = []
        for premise in self.premises.all():
            checker = Premise.get_checker(premise.name)
            if checker and callable(checker):
                try:
                    checker(user)
                    raise BaseError.OK
                except E as e:
                    error = e
            else:
                error = PremiseCheckerError.CHECKER_NOT_FOUND
            p_dict = premise.d()
            p_dict['check'] = dict(
                identifier=error.identifier,
                msg=error.message,
            )
            premises.append(p_dict)
        return premises

    @classmethod
    def list(cls):
        return cls.objects.all().dict(cls.d_base)