class ProjectUserBase(JsonifyPatchMixin, db.Document): """프로젝트-사용자를 표현하는 기본클래스. 정확히는 프로젝트와 프로젝트그룹사용자의 관계를 표현한다. 사용자객체와 email은 자주 꺼내쓰기때문에 cache해둔다. """ meta = { 'allow_inheritance': True, 'index_cls': False, 'indexes': [ { 'fields': ['project', 'user'], 'unique': True }, ], } #################################################################### # fields #################################################################### project = db.ReferenceField('Project', required=True, reverse_delete_rule=mongoengine.CASCADE) created_at = db.DateTimeField(default=datetime.now) #################################################################### # cached property user_email = db.EmailField(max_length=255) user = db.ReferenceField('User', required=True, reverse_delete_rule=mongoengine.CASCADE)
class ProjectUserReportSubscription(db.Document, ProjectUserReportSubscriptionMixin): '''project-user에 넣으면 좋지만, 고객사요건으로 project-user가 아닌 경우에도 구독이 가능해야 해서, 시간과 영향도를 고려하여 불가피하게 별도 collection으로 분리하게 되었음. 추후 project-user로 편입시킬 수 있으면 좋겠음.''' project = db.ReferenceField('Project', required=True, reverse_delete_rule=mongoengine.CASCADE) user = db.ReferenceField('User', required=True, reverse_delete_rule=mongoengine.CASCADE)
class ProjectGroupUser(JsonifyPatchMixin, db.Document): meta = { 'indexes': [ { 'fields': ['project_group', 'user'], 'unique': True }, ], } #################################################################### # fields #################################################################### project_group = db.ReferenceField('ProjectGroup', required=True, reverse_delete_rule=mongoengine.CASCADE) user = db.ReferenceField('User', required=True, reverse_delete_rule=mongoengine.CASCADE) is_owner = db.BooleanField(default=False) is_moderator = db.BooleanField(default=False) is_termer = db.BooleanField(default=False) last_visited_at = db.DateTimeField(default=datetime.now) created_at = db.DateTimeField(default=datetime.now) # ui project_layout = db.StringField(default='boxed') render_template_path = "project_group/_members_tbl_row.html" #################################################################### # cached properties #################################################################### user_email = db.EmailField(max_length=255) #################################################################### # methods #################################################################### def __unicode__(self): return '{0}:{1}'.format(self.project_group.slug, self.user.email) def clean(self): self.user_email = self.user.email @classmethod def post_save(cls, sender, document, **kwargs): logger.debug('post save : %s' % document) on_joined_to_project_group.send( (document.user, document.project_group))
class AuditableMixin(object): created_by = db.ReferenceField( 'User', default=current_user_or_none, reverse_delete_rule=mongoengine.NULLIFY) created_at = db.DateTimeField(default=datetime.now, required=True) modified_by = db.ReferenceField( 'User', default=current_user_or_none, reverse_delete_rule=mongoengine.NULLIFY) modified_at = db.DateTimeField(default=datetime.now, required=True) def clean_by_auditable_mixin(self): self.modified_at = datetime.now() self.modified_by = current_user_or_none()
class ProjectGroupNotice(db.EmbeddedDocument): # project_group = db.ReferenceField('ProjectGroup') seq = db.IntField(default=0) created_at = db.DateTimeField(default=datetime.now, required=True) created_by = db.ReferenceField('User', required=True) publish_begin_at = db.DateTimeField(default=datetime.now, required=True) publish_end_at = db.DateTimeField(default=datetime.now, required=True) content = db.StringField(required=True)
class ProjectWaitingUserInbound(ProjectUserBase): project_group_user = db.ReferenceField( 'ProjectGroupUser', required=True, reverse_delete_rule=mongoengine.CASCADE) """사용자가 가입요청을 했을 경우""" done = db.BooleanField(default=False) done_by = db.ReferenceField('User', reverse_delete_rule=mongoengine.NULLIFY) done_at = db.DateTimeField(default=datetime.now) done_message = db.StringField() rejected = db.BooleanField(default=False) asked_at = db.DateTimeField(default=datetime.now) asked_message = db.StringField() render_template_path = 'project/_members_waiting_tbl_row.html' def clean(self): pgu = ProjectGroupUser.objects( project_group=self.project.project_group, user=self.user).first() if pgu is None: raise ValidationError('Invalid group-project-usermapping') else: self.project_group_user = pgu # cached property self.user_email = self.user.email def approve_and_get_new_project_user(self): if not self.project.is_new_member_available(): return None project = self.project user = self.user self.delete() return ProjectUser(project=project, user=user).save()
class InviteToken(UserToken): """ PROJECT에서 초청되었을때 생성되는 가입토큰 """ project = db.ReferenceField('Project', reverse_delete_rule=mongoengine.CASCADE) def sendmail(self): """project 초청메일 발송(project_url을 발송한다.) 가입자, 미가입자 상관없이 메일이 발송된다. TODO: 미가입자에 대한 안내가 별도로 필요할 수 있음 """ signup_url = url_for('login.signup', _external=True) title = lazy_gettext(u'NEXCORE ER-C 프로젝트에 초대되었습니다.' '[%(title)s]', title=self.project.title) message = render_template('project/invite.email', signup_url=signup_url, project=self.project) return sendmail(self.email, title, message) def is_valid(self, email, project): '''project에 속한 email의 invitation의 유효성을 체크합니다. 7일의 유효기간으로 계산해서 유효여부를 True/False로 리턴. ''' try: time_threshold = datetime.now() - timedelta(days=7) token = InviteToken.objects.get(email=email, project=self, created_at__gte=time_threshold) logger.debug('token found(id: %s)' % token.id) ret = True except InviteToken.DoesNotExist: ret = False return ret
class ProjectWaitingUserOutbound(ProjectUserBase): """가입되지 않은 사용자를 초대받을때""" user = db.EmailField(required=True) outbound_email_sent_at = db.DateTimeField() outbound_email_sent_count = db.IntField(default=0) invited_by = db.ReferenceField('User', reverse_delete_rule=mongoengine.NULLIFY) invited_at = db.DateTimeField(default=datetime.now) # dropped = db.BooleanField(default=False) render_template_path = 'project/_members_invited_tbl_row.html' @property def is_expired(self): '''초대요청이 오래지나면 만료된다. 만료기간은 14일.''' return self.outbound_email_sent_at < datetime.now() - \ timedelta(days=14) def check_integrity(self): '''외부사용자객체의 무결성을 검사합니다. 외부사용자로 되어있는데 실제 user에도 존재하는 경우는 강제보정 만료된 객체의 경우 삭제처리합니다.''' if self.is_expired: logger.info( 'Deleting expired old-waiting-user-project-relation' '[%s].', self) self.delete() else: user = User.objects(email=self.user).first() if user: '''이미 가입된 사용자로 존재하는군요. 프로젝트와의 관계까지검사합니다.''' relation = ProjectUserBase.objects(project=self.project, user=user).first() if relation: logger.info( 'Deleting useless old-waiting-user-project-relation' '[%s].', self) self.delete() # useless. else: '''미처리된 사용자이므로 가입처리''' new_project_user = ProjectUser(project=self.project, user=user).save() logger.info('Creating new-user-project-relation' '[%s].', new_project_user) logger.info( 'Deleting old-waiting-user-project-relation' '[%s].', self) self.delete() else: '''정상적인 waiting이므로 done nothing.''' pass def sendmail(self): if self.outbound_email_sent_count > 4: logger.warning('outbound-email[%s]-surge-protection', self.user) return token = InviteToken(email=self.user, project=self.project).save() token.sendmail() self.outbound_email_sent_at = datetime.now() self.outbound_email_sent_count += 1 self.save() def clean(self): if self.project.project_group.is_not_default: raise ValidationError( 'outbound-user cannot be created at non-default-project-group') # 초대그룹의 email이 encrypt되어있지 않아서 다른쪽과 interface를 맞추기 위해 암호화 self.user_email = self.user def to_json(self, *args, **kwargs): """일부 계산된 properties를 json으로 내보내기 위한 patch""" ret = super(ProjectWaitingUserOutbound, self).to_json(*args, **kwargs) # patch for email-encryption (slow...) from json import dumps, loads d = loads(ret) d['is_expired'] = self.is_expired return dumps(d)
class ProjectUser(ProjectUserBase, ProjectUserReportSubscriptionMixin): """project에 속한 user관리.""" project_group_user = db.ReferenceField( 'ProjectGroupUser', required=True, reverse_delete_rule=mongoengine.CASCADE) is_owner = db.BooleanField(default=False) last_visited_at = db.DateTimeField(default=datetime.now) # # for modeling # is_modeler = db.BooleanField(default=False) # can_manage_all_models = db.BooleanField(default=True) # manageable_models = db.ListField(db.ReferenceField( # 'Model', reverse_delete_rule=mongoengine.PULL)) # # for terming # is_termer = db.BooleanField(default=False) # can_manage_all_glossaries = db.BooleanField(default=True) # manageable_glossaries = db.ListField(db.ReferenceField( # 'GlossaryBase', reverse_delete_rule=mongoengine.PULL)) # ui project_layout = db.StringField(default='boxed') render_template_path = 'project/_members_tbl_row.html' def clean(self): pgu = ProjectGroupUser.objects( project_group=self.project.project_group, user=self.user).first() if pgu is None: raise ValidationError('Invalid project-group-user-mapping') else: self.project_group_user = pgu # cached property self.user_email = self.user.email def visit(self): if self.project.demo: return # self.last_visited_at = datetime.now() # self.save() self.update(last_visited_at=datetime.now()) @property def grades(self): ret = [] if self.is_owner: ret.append('owner') if self.is_modeler: ret.append('modeler') if self.is_termer: ret.append('termer') if len(ret) == 0: ret.append('member') return ret def __unicode__(self): return u'%s:%s:%s' % (self.project, self.user, ','.join(self.grades))
class ProjectGroup( db.Document, ProjectGroupNotices, ProjectGroupAppereance, ProjectGroupLimitFactors, ProjectGroupMy, ProjectGroupMemberJoin, ProjectGroupGlossaryMasterMixin, # BillingMixin ): """프로젝트를 그룹하여 관리하는 객체. project는 한개의 group에 종속된다. default라는 이름으로 기본 project_group이 항상 존재해야 함. """ meta = { 'indexes': [ { 'fields': ['slug'], 'unique': True }, ], } #################################################################### # fields #################################################################### title = db.StringField(required=True, max_length=255, min_length=2) slug = db.StringField(required=True, max_length=255, min_length=2) description = db.StringField(required=True, max_length=4000) external_homepage_url = db.URLField(max_length=1000) private = db.BooleanField(default=False) visible = db.BooleanField(default=True) created_at = db.DateTimeField(default=datetime.now, required=True) created_by = db.ReferenceField('User') allow_subscribe_all_project_changes = db.BooleanField(default=False) #################################################################### # properties #################################################################### @property def queryset_project(self): from erks.erks_bps.project.models import Project return Project.objects(project_group=self) @property def queryset_project_group_user(self): return ProjectGroupUser.objects(project_group=self) @property def url(self): return url_for('project_group.list_projects', slug=self.slug) @property def is_not_default(self): return self.slug != 'default' @property def is_default(self): return self.slug == 'default' @classmethod def default(cls): slug = current_app.config['DEFAULT_PROJECT_GROUP_SLUG'] default_project_group = ProjectGroup.objects(slug=slug).first() # if not default_project_group.theme_key and current_app.config['DEFAULT_PROJECT_GROUP_THEME_KEY']: # default_project_group.theme_key = current_app.config['DEFAULT_PROJECT_GROUP_THEME_KEY'] return default_project_group #################################################################### # methods #################################################################### def __unicode__(self): return self.slug def clean(self): # project_group에 속한 여러개의 mixins의 # clean method를 차례로 호출 for base in ProjectGroup.__bases__: try: base.clean(self) except AttributeError: pass def save_as_random_slug(self): logger.debug("save_as_random_slug called") try: # import pdb; pdb.set_trace() self.slug = self.slug + str(random.randrange(1, 1000)) self.save() logger.debug("slug {0}, " "save_as_random_slug saved".format(self.slug)) except mongoengine.errors.NotUniqueError: self.save_as_random_slug() def save(self, *args, **kwargs): is_new = not self.id self.is_free = False # project_group always shouldn't be free. ret = super(ProjectGroup, self).save(*args, **kwargs) # if kwargs.get('emit_signals', True) and self.is_not_default: if is_new: on_created_project_group.send(self) else: on_changed_project_group.send(self) return ret
class Project( JsonifyPatchMixin, AuditableMixin, db.Document, # ProjectBillingMixin, # ProjectGlossaryDerivedMixin, ProjectInvatationMixin, # ProjectRecommendationMixin, # ProjectReportMixin, # ProjectSchemaCollectorMixin, ProjectUserMixin, ): title = db.StringField(required=True, max_length=40, min_length=2) # created_at = db.DateTimeField(default=datetime.now, required=True) private = db.BooleanField(default=False) visible = db.BooleanField(default=True) demo = db.BooleanField(default=False) description = db.StringField() contact = db.StringField() profile_imgf = db.ImageField( collection_name='project_images', size=(600, 600, True), thumbnail_size=(140, 140, True), ) project_group = db.ReferenceField('ProjectGroup', required=True) project_group_managed = db.BooleanField(default=False) # modified_at = db.DateTimeField( # default=datetime.now, required=True) meta = {'ordering': ['-modified_at', '-created_at']} #################################################################### # PROJECT내에서 사용되는 GRADE #################################################################### ORGANIZER = u'owner' MEMBER = u'member' MODELER = u'modeler' TERM_MANAGER = u'termer' WAITING_MEMBER = u'waiting_member' GUEST = u'guest' @property def base_html(self): if self.project_group: return self.project_group.project_base_html else: return "project/base.html" @property def base4erc_html(self): if current_user.is_authenticated: if self.project_group: return self.project_group.base4erc_html else: return "base4erc.html" else: return ProjectGroup.default().base4erc_html #################################################################### # properties #################################################################### @property def queryset_project_user(self): from erks.models import ProjectUserBase return ProjectUserBase.objects(project=self) @property def queryset_post(self): from erks.models import Post return Post.objects(project=self) # @property # def queryset_glossary(self): # from erks.models import GlossaryBase # return GlossaryBase.head_objects(project=self) @property def queryset_user(self): '''todo: mongodb와 document 설계 한계로 인해서 사용자객체의 queryset 형태로 구현하기에는 현재로서는 어려워보임.''' # code = """ # function(field) { # var docs = []; # db['project_user_base'].find( # {project: ObjectId(options.project_id)} # ).forEach(function(doc) { # //docs.push(db[collection].findOne({_id: doc.user})); # docs.push(doc.user); # }); # return docs; # } # """ # return User.objects.exec_js(code, 'id', project_id=str(self.id)) raise NotImplementedError() # @property # def context_term_managers(self): # '''현재 project, glossary에 속해있는 용어관리자를 return''' # return [ # entry.user # for entry in self.queryset_project_user.filter( # is_termer=True).only('user', 'can_manage_all_glossaries', # 'manageable_glossaries') # if entry.can_manage_all_glossaries or ( # entry.manageable_glossaries and # g.glossary in entry.manageable_glossaries) # ] @property def owner(self): project_owner = self.queryset_project_user.filter( is_owner=True).only('user').first() return project_owner.user @property def members(self): # TODO: 속도개선을 위해 iterable하고 container type의 객체를 return하도록 return [ entry.user for entry in self.queryset_project_user.only('user') ] @property def term_managers(self): # TODO: 속도개선을 위해 iterable하고 container type의 객체를 return하도록 return [ entry.user for entry in self.queryset_project_user.filter( is_termer=True).only('user') ] @property def modelers(self): # TODO: 속도개선을 위해 iterable하고 container type의 객체를 return하도록 return [ entry.user for entry in self.queryset_project_user.filter( is_modeler=True).only('user') ] @property def url(self): return url_for('project.index', project_id=self.id) @property def external_url(self): return url_for('project.index', project_id=self.id, _external=True) #################################################################### # queryset #################################################################### @db.queryset_manager def demo_objects(doc_cls, queryset): return queryset.filter(demo=True) @db.queryset_manager def visible_objects(doc_cls, queryset): '''프로젝트포털에 노출가능한 것만 보여준다.''' # TODO: 내 것은 무조건 보여야 한다. return queryset.filter((Q(visible=True) | Q(visible=None)) & Q(demo=False)) #################################################################### # methods #################################################################### def save(self, *args, **kwargs): # NOTIFY_MAP = { # 'title': dict(message=lazy_gettext(u'프로젝트명이 \'%s\'로 변경되었습니다.' % self.title, typ='project'), # 'private': dict(message=lazy_gettext(u'이 프로젝트는 %s입니다.' % (lazy_gettext(u'공개', lazy_gettext(u'비공개')[self.private], typ='project'), # 'visible': dict(message=lazy_gettext(u'이 프로젝트는 %s.' % (lazy_gettext(u'검색되지 않습니다.', lazy_gettext(u'검색에 노출됩니다.')[self.visible], typ='project'), # 'description': dict(message=lazy_gettext(u'상세 설명 부분이 변경되었습니다.', typ='project'), # 'profile_imgf': dict(message=lazy_gettext(u'프로젝트 이미지가 변경되었습니다.', typ='project'), # } if self.id: # [self.notify(**NOTIFY_MAP[fieldname]) # for fieldname in self._changed_fields # if fieldname in NOTIFY_MAP] # OWNER변경에 대한 NOTIFICATION처리, OWNER가 종종 알수없이 _changed_fields에 # 들어가있다. # if 'owner' in self._changed_fields: # self.notify(message=lazy_gettext(u'{{user.email}} 사용자는 관리자입니다.', # user=self.owner, typ='user') # on_changed_project_owner.send(self) on_changed_project.send(self) ret = super(Project, self).save(*args, **kwargs) else: # You can only reference documents once they have been saved to the # database ret = super(Project, self).save(*args, **kwargs) on_created_project.send(self) # on_changed_project_owner.send(self) # self.notify( # message=lazy_gettext(u'프로젝트가 생성되었습니다 by {{user.email}}', user=self.owner, typ='project') # self.notify(message=lazy_gettext(u'{{user.email}} 사용자는 관리자입니다.', # user=self.owner, typ='user') return ret def __unicode__(self): return self.title def __lt__(self, other): return str(self) < str(other) def __gt__(self, other): return str(self) > str(other) def clean(self): # free-project-cannot-be-private # self.id가 없을때 product를 참고하면 오류발 if current_app.config['BILLING']: if self.id and \ (self.product is None or not self.product.support_private): self.private = False self.visible = True # project-group-check if self.project_group is None: self.project_group = ProjectGroup.default() def get_grade(self, user): from erks.models import ( ProjectUser, ProjectUserBase, ProjectWaitingUserInbound, ) # 미로그인사용자도 사용할 수 있는 함수 # if user.is_active: # if user == self.owner: # return self.ORGANIZER # elif user in self.modelers: # return self.MODELER # elif user in self.term_managers: # return self.TERM_MANAGER # elif user in self.members: # return self.MEMBER # elif user in self.waiting_members: # return self.WAITING_MEMBER # # elif user in self.invited_members: # # return self.WAITING_MEMBER # else: # logger.debug('user is not active.') # return self.GUEST if user.is_active: entry = ProjectUserBase.objects(project=self, user=user).first() if entry: if isinstance(entry, ProjectUser): if entry.is_owner: return self.ORGANIZER elif entry.is_modeler: return self.MODELER elif entry.is_termer: return self.TERM_MANAGER else: return self.MEMBER elif isinstance(entry, ProjectWaitingUserInbound): return self.WAITING_MEMBER else: logger.debug('user is not active.') return self.GUEST def _get_grades(self, user): from erks.models import ( ProjectUser, ProjectUserBase, ProjectWaitingUserInbound, ) grades = [] if user.is_active: entry = ProjectUserBase.objects(project=self, user=user).first() if isinstance(entry, ProjectUser): if entry.is_owner: grades.append(self.ORGANIZER) if entry.is_modeler: grades.append(self.MODELER) if entry.is_termer: grades.append(self.TERM_MANAGER) if not grades: if isinstance(entry, ProjectUser): grades.append(self.MEMBER) elif isinstance(entry, ProjectWaitingUserInbound): grades.append(self.WAITING_MEMBER) if grades: return grades return [self.GUEST] def get_grades(self, user): def _(grade): return { 'owner': { 'label': 'label-primary', 'grade': gettext(u'프로젝트 관리자') }, 'member': { 'label': 'label-warning', 'grade': gettext(u'일반회원') }, 'modeler': { 'label': 'label-success', 'grade': gettext(u'모델러') }, 'termer': { 'label': 'label-info', 'grade': gettext(u'용어 관리자') }, 'waiting_member': { 'label': 'label-default', 'grade': gettext(u'손님(등록 대기중)') }, 'guest': { 'label': 'label-default', 'grade': gettext(u'손님') } }[grade] return [_(grade) for grade in self._get_grades(user)] def check_to_enter(self, user=None): from erks.models import ( ProjectUser, ) '''project에 입장할 수 있는지를 검사''' if self.demo: return True # TODO: 이게 맞나요? if not current_user.is_active: return False if user is None: user = current_user._get_current_object() is_member = ProjectUser.objects( project=self, user=user).only('id').no_dereference().first() is not None return not self.private or is_member # def count_entities(self): # from erks.erks_bps.erc.models import Entity # return len(Entity.objects(prjId=str(self.id))) # def count_terms(self): # from erks.erks_bps.term.models import Term # return len(Term.objects(project=self)) # def is_custom_img(self): # return self.profile_imgf # def is_new(self): # """ # project가 새 것인지를 판단하기 # 주제영역이 하나라도 구성되어 있으면 알림을 주지 않기 위해. # """ # from erks.erks_bps.erc.models import SubjectArea # return SubjectArea.objects(prjId=str(self.id)).first() is None def get_profile_img_url(self, thumbnail=False): """binary값 기준으로 무작위로 profile image를 골라준다.""" # 샘플이미지파일 개수 SAMPLE_IMG_CNT = 5 # TODO: 매번계산하므로 성능상 불리. 개선필요하다. random_number = sum( map(ord, list(hashlib.md5( self.id.binary).hexdigest()))) % SAMPLE_IMG_CNT + 1 if self.profile_imgf: return url_for('project.profile_img', project_id=self.id) else: if self.project_group and self.project_group.theme_key in THEME_KEYS: filename = '%01s/img/Project_thumb_768x573_%02d.jpg' % ( self.project_group.theme_key, random_number) else: filename = 'img/r3/Project_thumb_768x573_%02d.jpg' % ( random_number) return url_for('static', filename=filename) def destroy(self): '''project 삭제처리. project에 속한 모든 resource를 삭제하므로 경우에 따라 heavy할 수 있기 때문에 가급적이면 web-request에서 처리하지 않는 것을 권장''' from erks.erks_bps.erc.models import (Model, Domain, SubjectArea, Entity, Relation, Lock) # delete models Model.objects(prjId=str(self.id)).delete() # domain Domain.objects(prjId=str(self.id)).delete() # delete subjectarea SubjectArea.objects(prjId=str(self.id)).delete() # delete entities Entity.objects(prjId=str(self.id)).delete() # delete relation Relation.objects(prjId=str(self.id)).delete() # delete lock Lock.objects(prjId=str(self.id)).delete() # delete project self.delete()