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)
class User(models.Model): openid = models.CharField(max_length=64, unique=True) create_time = models.DateTimeField() interaction_times = models.IntegerField(default=1) inside_service = models.CharField(max_length=10, null=True, default=None) phone = models.CharField(max_length=20, null=True, default=None) @classmethod def get_or_create(cls, openid): try: user = cls.objects.get(openid=openid) user.interact() return user except cls.DoesNotExist: return cls.objects.create(openid=openid, create_time=datetime.now()) def interact(self): self.interaction_times = F('interaction_times') + 1 self.save() self.refresh_from_db() def inside(self, service): self.inside_service = service self.save() def set_phone(self, phone): self.phone = phone self.save() @property def phone_bind(self): return self.phone is not None def require_phone(self): if not self.phone: raise UserError.REQUIRE_PHONE
class Segment(models.Model): project = models.ForeignKey( 'Project.Project', on_delete=models.CASCADE, ) time = models.DateTimeField( verbose_name='数据产生时间', default=0, db_index=True, ) @classmethod def get(cls, sid): try: return cls.objects.get(pk=sid) except cls.DoesNotExist: return SegmentError.SEGMENT_NOT_FOUND except Exception as err: raise SegmentError.GET_SEGMENT(debug_message=err) @classmethod def new(cls, project, time): try: segment = cls(project=project, time=time) segment.save() except Exception as err: raise SegmentError.NEW_SEGMENT(debug_message=err) return segment def _readable_sid(self): return self.pk def _readable_time(self): return self.time.timestamp() def _readable_waves(self): return Wave.objects.filter(segment=self).dict(Wave.d) def d(self): return self.dictor('sid', 'time', 'waves')
class Article(models.Model): user = models.ForeignKey( 'User.MiniUser', on_delete=models.CASCADE, ) aid = models.CharField( verbose_name='文章ID', max_length=6, min_length=6, unique=True, ) origin = models.CharField( max_length=20, null=True, default=None, ) author = models.CharField( max_length=20, null=True, default=None, ) create_time = models.DateTimeField(auto_now_add=True, ) title = models.CharField(max_length=50, ) self_product = models.BooleanField( verbose_name='原创声明', default=False, null=True, ) require_review = models.BooleanField( verbose_name='需要审核', default=False, null=True, ) allow_open_reply = models.BooleanField( verbose_name='允许公开回复', default=False, null=True, ) @classmethod def get(cls, aid): try: return cls.objects.get(aid=aid) except cls.DoesNotExist: raise ArticleError.NOT_FOUND @classmethod def get_unique_id(cls): while True: aid = get_random_string(length=6) try: cls.get(aid) except E: return aid @classmethod def create(cls, user, author, origin, title, self_product, require_review, allow_open_reply): try: return cls.objects.create( user=user, title=title, author=author, origin=origin, self_product=self_product, require_review=require_review, allow_open_reply=allow_open_reply, aid=cls.get_unique_id(), ) except Exception as err: raise ArticleError.CREATE(debug_message=err) def update(self, title, origin, author): self.origin = origin self.title = title self.author = author self.save() def assert_belongs_to(self, user): if self.user != user: raise ArticleError.NOT_OWNER def remove(self): self.delete() def get_comments(self, show_all=False, selected=True): comments = self.comment_set.filter(reply_to=None) if not show_all: comments = comments.filter(selected=selected) return comments.order_by('pk') def _readable_create_time(self): return self.create_time.timestamp() def _readable_comments(self, show_all=False): if not self.require_review and show_all: return comments = self.comment_set.filter(reply_to=None) if self.require_review: comments = comments.filter(selected=True) return comments.order_by('pk').dict(Comment.d_replies, show_all) def _readable_my_comments(self, user): if self.require_review: return self.comment_set.filter(~Q(selected=True), user=user, reply_to=None).order_by('pk').dict( Comment.d_replies) else: return [] def _readable_user(self): return self.user.d() def d_base(self): return self.dictify('aid', 'title', 'origin', 'author', 'create_time', 'self_product', 'require_review', 'allow_open_reply') def d(self, user): d = self.d_base() if self.user == user: d.update( self.dictify('comments', 'user', ('comments->all_comments', True))) else: d.update(self.dictify('comments', 'user', ('my_comments', user))) return d def d_create(self): return self.dictify('aid') def comment(self, user, content): return Comment.create(self, user, content)
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
class Project(models.Model): name = models.CharField( verbose_name='项目名称', max_length=20, ) pid = models.CharField( verbose_name='项目ID', max_length=4, unique=True, ) create_time = models.DateTimeField( verbose_name='创建时间', default=0, ) owner = models.ForeignKey( 'User.User', on_delete=models.CASCADE, default=None, ) ticket = models.CharField( verbose_name='项目录入凭证', max_length=64, default=None, ) @classmethod def get(cls, pid): try: return cls.objects.get(pid=pid) except cls.DoesNotExist: raise ProjectError.PROJECT_NOT_FOUND except Exception as err: raise ProjectError.GET_PROJECT(debug_message=err) @classmethod def get_unique_pid(cls): while True: pid = get_random_string(length=4) try: cls.get(pid) except E as e: if e.eis(ProjectError.PROJECT_NOT_FOUND): return pid @classmethod def new(cls, name, owner): crt_time = get_time() try: project = cls(name=name, pid=cls.get_unique_pid(), create_time=crt_time, owner=owner, ticket=get_random_string(length=64)) project.save() except Exception as err: raise ProjectError.NEW_PROJECT(debug_message=err) return project def _readable_create_time(self): return self.create_time.timestamp() def _readable_owner(self): return self.owner.d() def d(self): return self.dictor('name', 'pid', 'create_time', 'owner') def d_owner(self): return self.dictor('name', 'pid', 'create_time', 'owner', 'ticket') def refresh_ticket(self): self.ticket = get_random_string(length=64) self.save() def auth_ticket(self, ticket): return self.ticket == ticket
class Room(models.Model): """ 房间类 """ number = models.IntegerField( unique=True, null=False, ) password = models.CharField(max_length=5, min_length=4, null=True, default=None) is_public = models.BooleanField(default=True) owner = models.ForeignKey( 'Room.Member', related_name='owner', on_delete=models.SET_NULL, null=True, ) member_a = models.ForeignKey( 'Room.Member', related_name='member_a', on_delete=models.SET_NULL, null=True, default=None, ) member_b = models.ForeignKey( 'Room.Member', related_name='member_b', on_delete=models.SET_NULL, null=True, default=None, ) # 房间人数0/3 member_num = models.IntegerField(default=1, ) status = models.BooleanField(default=False) # 轮到说话的人(1、2、3)(1默认房主) speaker = models.IntegerField(default=1, ) create_time = models.DateTimeField(auto_now_add=True) def d(self): return self.dictor('pk->rid', 'is_public', 'number', 'password', 'owner', 'member_a', 'member_b', 'member_num', 'speaker', 'status', 'create_time') def d_room_list(self): return self.dictor('pk->rid', 'number', 'is_public', 'owner', 'member_a', 'member_b', 'member_num', 'create_time') def d_number(self): return self.dictor('number') def _readable_owner(self): if self.owner: return self.owner.d() def _readable_member_a(self): if self.member_a: return self.member_a.d() def _readable_member_b(self): if self.member_b: return self.member_b.d() def _readable_create_time(self): return self.create_time.timestamp() @classmethod def check_password(cls, room, password): """验证房间密码是否正确""" if not room.is_public: if room.password != password: raise RoomError.JOIN_ROOM_PASSWORD(room.number) @staticmethod def get_room_by_pk(pk): try: return Room.objects.get(pk=pk) except Exception: raise RoomError.GET_ROOM_BY_PK(pk) @staticmethod def get_room_by_number(number): try: room = Room.objects.get(number=number) except Room.DoesNotExist: raise RoomError.GET_ROOM_BY_NUMBER(number) return room @classmethod def get_room_list(cls): Rooms = [] for room in Room.objects.filter( create_time__lte=datetime.datetime.now()): Rooms.append(room.d_room_list()) return Rooms @classmethod def creat_room(cls, user, password): try: print(password) room = cls(number=random.randint(1000, 9999), owner=Member.join_room(user), password=password) if room.password is not None: room.is_public = False room.save() except Exception as err: user.leave_room() raise RoomError.Create_ROOM(debug_message=err) return room @classmethod def close_room(cls, room): try: if room.member_a is not None: Member.leave_room(room.member_a) if room.member_b is not None: Member.leave_room(room.member_b) if room.owner is not None: Member.leave_room(room.owner) room.delete() print("delete======ok") except Exception as err: raise RoomError.CLOSE_ROOM(room.number, debug_message=err) @classmethod def join_room(cls, user, room, password): Room.check_password(room, password) if room.member_num == 3: raise RoomError.ROOM_FULL(room.number) try: member_num = room.member_num if member_num == 1: room.member_a = Member.join_room(user) else: room.member_b = Member.join_room(user) room.member_num = member_num + 1 room.save() except Exception: raise RoomError.MEMBER_JOIN_ROOM(user.username, room.number) return room @classmethod def change_position(cls, room): if room.owner is None: if room.member_b is not None: print("b->owner") room.owner = room.member_b room.member_b = None elif room.member_a is not None: print("a->owner") room.owner = room.member_a room.member_a = None if room.member_a is None and room.member_b is not None: print("b->a") room.member_a = room.member_b room.member_b = None room.member_num = room.member_num - 1 print(room.member_num) room.save() if room.member_num == 0: cls.close_room(room) def get_room_member(self): return [self.owner, self.member_a, self.member_b] @staticmethod def room_ready_status(user, room, ready): if room.status: raise RoomError.ROOM_NOT_UNREADY(room.number) try: print(ready) for member in room.get_room_member(): if member.user == user: member.is_ready = ready member.save() return room except Exception as err: raise RoomError.ROOM_CHANGE_STATUS(room.number, user.username, debug_message=err) @staticmethod def room_begin(room): room.status = True room.save() return room def room_change_speaker(self): try: self.speaker = (self.speaker + 1) if self.speaker == 4: self.speaker = 1 self.save() except Exception: raise RoomError.ROOM_CHANGE_SPEAKER(self.number)
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()
class Space(models.Model): space_id = models.CharField( max_length=20, min_length=4, unique=True, verbose_name='星球ID', null=False, ) name = models.CharField( max_length=15, min_length=2, verbose_name='星球名', default=None, null=True, ) rename_card = models.PositiveSmallIntegerField( default=1, verbose_name='星球改ID卡', ) access = models.CharField( choices=AccessChoices.list(), default=AccessChoices.ANY, max_length=10, ) create_time = models.DateTimeField(auto_now_add=True, ) default_milestone = models.ForeignKey('Milestone.Milestone', default=None, null=True, on_delete=models.SET_NULL, related_name='default_milestone') @staticmethod def _valid_space_id(space_id): if space_id[ 0] not in string.ascii_lowercase + string.ascii_uppercase + string.digits: raise SpaceError.INVALID_ID_SIDE if space_id[ -1] not in string.ascii_lowercase + string.ascii_uppercase + string.digits: raise SpaceError.INVALID_ID_SIDE valid_chars = '^[A-Za-z0-9_-]+$' if re.match(valid_chars, space_id) is None: raise SpaceError.INVALID_ID @classmethod def get_unique_id(cls): while True: space_id = get_random_string(length=8) try: cls.id_unique_checker(space_id) return space_id except E: pass # checkers @classmethod def id_unique_checker(cls, space_id: str): try: cls.objects.get(space_id__iexact=space_id.lower()) except cls.DoesNotExist: return raise SpaceError.ID_EXIST def owner_checker(self, user): if self.spaceman_set.get(is_owner=True).user != user: raise SpaceError.NOT_OWNER def member_checker(self, user): try: self.spaceman_set.get(user=user) except Exception: raise SpaceError.NOT_MEMBER def not_member_checker(self, user): try: self.spaceman_set.get(user=user) except Exception: return raise SpaceError.ALREADY_MEMBER @classmethod def get(cls, space_id: str): try: return cls.objects.get(space_id__iexact=space_id.lower()) except cls.DoesNotExist: raise SpaceError.NOT_FOUND @classmethod def create(cls, name, access, start_date, user): from Milestone.models import Milestone try: with transaction.atomic(): space = cls.objects.create( space_id=cls.get_unique_id(), rename_card=0, access=access, name=name, ) space.spaceman_set.create( user=user, avatar=None, name=user.nickname, is_owner=True, ) space.album_set.create( parent=None, name='星球主相册', grid_rows=4, grid_position=None, auto_arrange=True, cover=None, res_id=Album.generate_res_id(), ) milestone = Milestone.create(space=space, name='星球成立日', start_date=start_date) space.set_default_milestone(milestone) except Exception as err: raise SpaceError.CREATE(name, debug_message=err) return space def add_member(self, user): try: self.spaceman_set.create( user=user, avatar=None, name=user.nickname, is_owner=False, ) except Exception as err: raise SpaceError.JOIN(self.name, debug_message=err) def delete(self, *args, **kwargs): super(Space, self).delete(*args, **kwargs) def rename(self, space_id: str): if self.rename_card < 1: raise SpaceError.REQUIRE_RENAME_CARD self.id_unique_checker(space_id) self.space_id = space_id self.rename_card -= 1 self.save() # member def get_member(self, user): try: return self.spaceman_set.get(user=user) except Exception: raise SpaceError.MEMBER_NOT_FOUND # cover def get_cover_token(self): return self.default_milestone.get_image_token() def get_album(self): return self.album_set.get(parent=None) def set_default_milestone(self, milestone): self.default_milestone = milestone self.save() def _readable_create_time(self): return self.create_time.timestamp() def _readable_owner(self): return self.spaceman_set.get(is_owner=True).user.d() def _readable_cover(self, for_invite=False): if self.default_milestone.cover: if not for_invite: return self.default_milestone.cover.d_space() else: return self.default_milestone.cover.d_invite() def _readable_members(self, only_avatar=True): if only_avatar: return self.spaceman_set.dict(SpaceMan.get_avatar) return self.spaceman_set.dict(SpaceMan.d_space) def _readable_age(self): return self.default_milestone.get_duration() def _readable_milestones(self): from Milestone.models import Milestone return self.milestone_set.dict(Milestone.d) def _readable_default_milestone(self): return self.default_milestone.pk def _readable_album(self): return self.get_album().res_id def d(self): return self.dictify('name', ('members', False), 'album', 'milestones', ('cover', True), 'default_milestone') def d_create(self): return dict( space_dict=self.space_id, cover_token=self.get_cover_token(), ) def d_base(self): return self.dictify('name', 'space_id', 'cover', 'members', 'age') def d_member(self, only_avatar=True): return self._readable_members(only_avatar=only_avatar)
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()
class Foto(models.Model): foto_id = models.CharField( max_length=6, min_length=6, unique=True, ) create_time = models.DateTimeField(auto_now_add=True, ) key = models.CharField( max_length=100, unique=True, ) width = models.IntegerField() height = models.IntegerField() color_average = models.CharField( max_length=20, null=True, default=None, ) mime_type = models.CharField(max_length=50, ) orientation = models.IntegerField(default=1, ) album = models.ForeignKey( Album, on_delete=models.SET_NULL, default=None, null=True, ) pinned = models.BooleanField(default=False, ) @classmethod def is_id_unique(cls, foto_id): try: cls.objects.get(foto_id=foto_id) return False except cls.DoesNotExist: return True @classmethod def generate_foto_id(cls): while True: foto_id = get_random_string(6) if cls.is_id_unique(foto_id): return foto_id @classmethod def orientation_str2int(cls, orientation: list): if orientation[0] == 'TOP': return 1 if orientation[1] == 'LEFT' else 2 elif orientation[0] == 'BOTTOM': return 4 if orientation[1] == 'LEFT' else 3 elif orientation[1] == 'TOP': return 5 if orientation[1] == 'LEFT' else 6 else: return 8 if orientation[1] == 'LEFT' else 7 @classmethod def orientation_int2str(cls, orientation: int): o = orientation - 1 s = [''] * 2 s[o // 4] = 'TOP' if orientation in [1, 2, 5, 6] else 'BOTTOM' s[1 - o // 4] = 'LEFT' if orientation in [1, 4, 5, 8] else 'RIGHT' return '-'.join(s) def set_album(self, album): self.album = album self.save() def toggle_pin(self): self.pinned = not self.pinned self.save() @classmethod def get(cls, foto_id): try: return cls.objects.get(foto_id=foto_id) except cls.DoesNotExist: return FotoError.NOT_FOUND @classmethod def create(cls, width, height, orientation, **kwargs): if orientation >= 5: width, height = height, width try: return cls.objects.create( **kwargs, width=width, height=height, orientation=orientation, foto_id=cls.generate_foto_id(), ) except Exception as err: raise FotoError.CREATE(debug_message=err) @classmethod def get_tokens(cls, num, **kwargs): key_prefix = hex(int(datetime.datetime.now().timestamp() * 1000)) tokens = [] for _ in range(num): key = key_prefix + '/' + get_random_string(length=16) tokens.append( qn_manager.get_upload_token(key=key, policy=policy.customize(**kwargs))) return tokens def get_source(self, expires=3600, auto_rotate=True, resize=None, quality=100): url = qn_manager.get_image(self.key, expires=expires, auto_rotate=auto_rotate, resize=resize, quality=quality) return url def get_exif(self, expires=3600): return qn_manager.get_image_exif(self.key, expires=expires) def resize(self): target = 1200 if self.width <= target and self.height <= target: return self.width, self.height if self.width > self.height: return target, target * self.height // self.width return target * self.width // self.height, target def get_sources(self): return dict(origin=self.get_source(auto_rotate=False, resize=None), square=self.get_source(auto_rotate=True, resize=(600, 600), quality=75), rotate=self.get_source(auto_rotate=True, resize=self.resize(), quality=75)) def remove(self): qn_manager.delete_res(self.key) self.delete() @classmethod def get_pinned_fotos(cls, space): return cls.objects.filter(pinned=True, album__space=space) def _readable_sources(self): return dict( color=self.color_average, origin=self.get_source(auto_rotate=False, resize=None), square=self.get_source(auto_rotate=True, resize=(600, 600), quality=75), rotate=self.get_source(auto_rotate=True, resize=self.resize(), quality=75), exif=self.get_exif(), ) def _readable_orientation(self): return [self.orientation, self.orientation_int2str(self.orientation)] def _readable_album(self): return self.album.name def d(self): return self.dictify('sources', 'width', 'height', 'foto_id', 'orientation', 'album', 'pinned') def d_base(self): return self.dictify( 'album', 'foto_id', )
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()
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)