class UserLink(db.EmbeddedDocument): title = db.StringField(max_length=50, required=True) link = db.StringField(max_length=255, required=True) icon = db.StringField(max_length=255) css_class = db.StringField(max_length=50) order = db.IntField(default=0) def __unicode__(self): return '{0} -> {1}'.format(self.title, self.link)
class Link(Content): link = db.StringField(required=True) force_redirect = db.BooleanField(default=True) increment_visits = db.BooleanField(default=True) visits = db.IntField(default=0) def pre_render(self, render_function, *args, **kwargs): if self.increment_visits: self.visits = self.visits + 1 self.save() if self.force_redirect: return redirect(self.link) return super(Link, self).pre_render(render_function, *args, **kwargs)
class User(db.DynamicDocument, UserMixin): name = db.StringField(max_length=255) email = db.EmailField(max_length=255, unique=True) password = db.StringField(max_length=255) active = db.BooleanField(default=True) confirmed_at = db.DateTimeField() roles = db.ListField( db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[] ) last_login_at = db.DateTimeField() current_login_at = db.DateTimeField() last_login_ip = db.StringField(max_length=255) current_login_ip = db.StringField(max_length=255) login_count = db.IntField() username = db.StringField(max_length=50, required=False, unique=True) def clean(self, *args, **kwargs): if not self.username: self.username = User.generate_username(self.email) try: super(User, self).clean(*args, **kwargs) except: pass @classmethod def generate_username(cls, email): username = email.lower() for item in ['@', '.', '-', '+']: username = username.replace(item, '_') return username @classmethod def createuser(cls, name, email, password, active=True, roles=None, username=None): username = username or cls.generate_username(email) return cls.objects.create( name=name, email=email, password=encrypt_password(password), active=active, roles=roles, username=username ) def __unicode__(self): return "{0} <{1}>".format(self.name or '', self.email)
class Channel(HasCustomValue, Publishable, Slugged, db.DynamicDocument): title = db.StringField(max_length=255, required=True) description = db.StringField() show_in_menu = db.BooleanField(default=False) is_homepage = db.BooleanField(default=False) include_in_rss = db.BooleanField(default=False) indexable = db.BooleanField(default=True) canonical_url = db.StringField() order = db.IntField(default=0) # MPTT parent = db.ReferenceField('self', required=False, default=None, reverse_delete_rule=db.DENY) def get_ancestors(self, menu=True): return self.__class__.objects(parent=self, show_in_menu=True) @classmethod def get_homepage(cls, attr=None): try: homepage = cls.objects.get(is_homepage=True) except Exception as e: logger.info("There is no homepage: %s" % e.message) return None else: if not attr: return homepage else: return getattr(homepage, attr, homepage) def __unicode__(self): return self.long_slug def get_absolute_url(self): return "/{0}/".format(self.long_slug) def clean(self): homepage = Channel.objects(is_homepage=True) if self.is_homepage and homepage and not self in homepage: raise db.ValidationError(lazy_gettext("Home page already exists")) super(Channel, self).clean() def save(self, *args, **kwargs): self.validate_slug() self.validate_long_slug() super(Channel, self).save(*args, **kwargs)
class Connection(db.Document): user_id = db.ObjectIdField() provider_id = db.StringField(max_length=255) provider_user_id = db.StringField(max_length=255) access_token = db.StringField(max_length=255) secret = db.StringField(max_length=255) display_name = db.StringField(max_length=255) full_name = db.StringField(max_length=255) profile_url = db.StringField(max_length=512) image_url = db.StringField(max_length=512) rank = db.IntField(default=1) @property def user(self): return User.objects(id=self.user_id).first()
class User(db.Document, UserMixin): name = db.StringField(max_length=255) email = db.StringField(max_length=255) password = db.StringField(max_length=255) active = db.BooleanField(default=True) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[]) last_login_at = db.DateTimeField() current_login_at = db.DateTimeField() last_login_ip = db.StringField(max_length=255) current_login_ip = db.StringField(max_length=255) login_count = db.IntField() def __unicode__(self): return "{} <{}>".format(self.name or '', self.email)
class Connection(db.Document): user_id = db.ObjectIdField(verbose_name=_l('Connection')) provider_id = db.StringField(max_length=255, verbose_name=_l('Provider ID')) provider_user_id = db.StringField(max_length=255, verbose_name=_l('Provider User ID')) access_token = db.StringField(max_length=255, verbose_name=_l('Access Token')) secret = db.StringField(max_length=255, verbose_name=_l('Secret')) display_name = db.StringField(max_length=255, verbose_name=_l('Display Name')) full_name = db.StringField(max_length=255, verbose_name=_l('Full Name')) profile_url = db.StringField(max_length=512, verbose_name=_l('Profile URL')) image_url = db.StringField(max_length=512, verbose_name=_l('Image URL')) rank = db.IntField(default=1, verbose_name=_l('Rank')) @property def user(self): return User.objects(id=self.user_id).first()
class User(db.DynamicDocument, UserMixin): name = db.StringField(max_length=255) email = db.EmailField(max_length=255, unique=True) password = db.StringField(max_length=255) active = db.BooleanField(default=True) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[]) last_login_at = db.DateTimeField() current_login_at = db.DateTimeField() last_login_ip = db.StringField(max_length=255) current_login_ip = db.StringField(max_length=255) login_count = db.IntField() username = db.StringField(max_length=50, requied=False, unique=True) @classmethod def generate_username(cls, name, user=None): name = name or '' username = slugify(name) filters = dict(username=username) if user: filters['id__ne'] = user.id if cls.objects.filter(**filters).count(): username = '******'.format(username, random.randint(1, 1000)) return username def set_password(self, password, save=False): self.password = encrypt_password(password) if save: self.save() @classmethod def create_user(cls, name, email, password, active=True, roles=None, username=None, *args, **kwargs): username = username or cls.generate_username(name) if 'links' in kwargs: kwargs['links'] = [UserLink(**link) for link in kwargs['links']] return cls.objects.create(name=name, email=email, password=encrypt_password(password), active=active, roles=roles, username=username, *args, **kwargs) @property def connections(self): return Connection.objects(user_id=str(self.id)) def __unicode__(self): return '{0} <{1}>'.format(self.name or '', self.email)
class Channel(Tagged, HasCustomValue, Publishable, LongSlugged, ChannelConfigs, ContentFormat, db.DynamicDocument): title = db.StringField(max_length=255, required=True) description = db.StringField() show_in_menu = db.BooleanField(default=False) is_homepage = db.BooleanField(default=False) include_in_rss = db.BooleanField(default=True) indexable = db.BooleanField(default=True) canonical_url = db.StringField() order = db.IntField(default=0) parent = db.ReferenceField('self', required=False, default=None, reverse_delete_rule=db.DENY) per_page = db.IntField(default=0) aliases = db.ListField(db.StringField(), default=[]) channel_type = db.ReferenceField(ChannelType, required=False, reverse_delete_rule=db.NULLIFY) redirect_url = db.StringField(max_length=255) render_content = db.ReferenceField(ContentProxy, required=False, reverse_delete_rule=db.NULLIFY) sort_by = db.ListField(db.StringField(), default=[]) meta = { 'ordering': ['order', 'title'] } def get_text(self): if self.content_format == "markdown": return markdown(self.description) else: return self.description def get_content_filters(self): filters = {} if self.channel_type and self.channel_type.content_filters: filters.update(self.channel_type.content_filters) if self.content_filters: filters.update(self.content_filters) return filters def get_ancestors_slugs(self): """return ancestors slugs including self as 1st item >>> channel = Channel(long_slug='articles/technology/programming') >>> channel.get_ancestors_slugs() ['articles/technology/programming', 'articles/technology', 'articles'] """ channel_list = [] channel_slugs = self.long_slug.split('/') while channel_slugs: channel_list.append("/".join(channel_slugs)) channel_slugs.pop() return channel_list def get_ancestors(self, **kwargs): """return all ancestors includind self as 1st item""" channel_list = self.get_ancestors_slugs() ancestors = self.__class__.objects( long_slug__in=channel_list, **kwargs ).order_by('-long_slug') return ancestors def get_children(self, **kwargs): """return direct children 1 level depth""" return self.__class__.objects( parent=self, **kwargs ).order_by('long_slug') def get_descendants(self, **kwargs): """return all descendants including self as 1st item""" return self.__class__.objects( __raw__={'mpath': {'$regex': '^{0}'.format(self.mpath)}} ).order_by('long_slug') def get_themes(self): return list({ c.channel_type.theme_name for c in self.get_ancestors(channel_type__ne=None) if c.channel_type and c.channel_type.theme_name }) @classmethod def get_homepage(cls, attr=None): try: homepage = cls.objects.get(is_homepage=True) except Exception as e: logger.info("There is no homepage: %s" % e.message) return None else: if not attr: return homepage else: return getattr(homepage, attr, homepage) def __unicode__(self): return self.long_slug def get_absolute_url(self, *args, **kwargs): return "/{0}/".format(self.long_slug) def get_canonical_url(self, *args, **kwargs): if self.is_homepage: return "/" return self.get_absolute_url() def clean(self): homepage = Channel.objects(is_homepage=True) if self.is_homepage and homepage and not self in homepage: raise db.ValidationError(_l("Home page already exists")) super(Channel, self).clean() def validate_render_content(self): if self.render_content and \ not isinstance(self.render_content, ContentProxy): self.render_content, created = ContentProxy.objects.get_or_create( content=self.render_content) else: self.render_content = None def heritage(self): """populate inheritance from parent channels""" parent = self.parent if not parent or not self.inherit_parent: return self.content_filters = self.content_filters or parent.content_filters self.include_in_rss = self.include_in_rss or parent.include_in_rss self.show_in_menu = self.show_in_menu or parent.show_in_menu self.indexable = self.indexable or parent.indexable self.channel_type = self.channel_type or parent.channel_type def update_descendants_and_contents(self): """TODO: Detect if self.long_slug and self.mpath has changed. if so, update every descendant using get_descendatns method to query. Also update long_slug and mpath for every Content in this channel This needs to be done by default in araw immediate way, but if current_app.config.get('ASYNC_SAVE_MODE') is True it will delegate all those tasks to celery.""" def save(self, *args, **kwargs): self.validate_render_content() self.validate_slug() self.validate_long_slug() self.heritage() self.update_descendants_and_contents() super(Channel, self).save(*args, **kwargs)
class Ordered(object): order = db.IntField(required=True, default=1)
class User(db.DynamicDocument, ThemeChanger, HasCustomValue, UserMixin, HasImages): name = db.StringField(max_length=255) email = db.EmailField(max_length=255, unique=True) password = db.StringField(max_length=255) active = db.BooleanField(default=True) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[]) last_login_at = db.DateTimeField() current_login_at = db.DateTimeField() last_login_ip = db.StringField(max_length=255) current_login_ip = db.StringField(max_length=255) login_count = db.IntField() username = db.StringField(max_length=50, required=False, unique=True) remember_token = db.StringField(max_length=255) authentication_token = db.StringField(max_length=255) tagline = db.StringField(max_length=255) bio = db.StringField() links = db.ListField(db.EmbeddedDocumentField(UserLink)) use_avatar_from = db.StringField(choices=(("gravatar", "gravatar"), ("url", "url"), ("upload", "upload"), ("facebook", "facebook")), default='gravatar') gravatar_email = db.EmailField(max_length=255) avatar_file_path = db.StringField() avatar_url = db.StringField(max_length=255) @property def display_name(self): rtn = None if self.name: rtn = self.name elif self.username: rtn = self.username elif self.email: rtn = self.email else: rtn = str(self) return rtn def get_avatar_url(self, *args, **kwargs): if self.use_avatar_from == 'url': return self.avatar_url elif self.use_avatar_from == 'upload': return url_for('quokka.core.media', filename=self.avatar_file_path) elif self.use_avatar_from == 'facebook': try: return Connection.objects( provider_id='facebook', user_id=self.id, ).first().image_url except Exception as e: logger.warning( '%s use_avatar_from is set to facebook but: Error: %s' % (self.display_name, str(e))) return Gravatar()(self.get_gravatar_email(), *args, **kwargs) @property def summary(self): return (self.bio or self.tagline or '')[:255] def get_gravatar_email(self): return self.gravatar_email or self.email def clean(self, *args, **kwargs): if not self.username: self.username = User.generate_username(self.name) super(User, self).clean(*args, **kwargs) @classmethod def generate_username(cls, name, user=None): name = name or '' username = slugify(name) filters = {"username": username} if user: filters["id__ne"] = user.id if cls.objects.filter(**filters).count(): username = "******".format(username, randint(1, 1000)) return username def set_password(self, password, save=False): self.password = encrypt_password(password) if save: self.save() @classmethod def createuser(cls, name, email, password, active=True, roles=None, username=None, *args, **kwargs): username = username or cls.generate_username(name) if 'links' in kwargs: kwargs['links'] = [UserLink(**link) for link in kwargs['links']] return cls.objects.create(name=name, email=email, password=encrypt_password(password), active=active, roles=roles, username=username, *args, **kwargs) @property def display_name(self): return abbreviate(self.name) or self.email def __unicode__(self): return u"{0} <{1}>".format(self.name or '', self.email) @property def connections(self): return Connection.objects(user_id=str(self.id))
class User(db.DynamicDocument, UserMixin): name = db.StringField(max_length=255) email = db.EmailField(max_length=255, unique=True) password = db.StringField(max_length=255) active = db.BooleanField(default=True) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[]) last_login_at = db.DateTimeField() current_login_at = db.DateTimeField() last_login_ip = db.StringField(max_length=255) current_login_ip = db.StringField(max_length=255) login_count = db.IntField() username = db.StringField(max_length=50, required=False, unique=True) remember_token = db.StringField(max_length=255) authentication_token = db.StringField(max_length=255) tagline = db.StringField(max_length=255) bio = db.StringField() links = db.ListField(db.EmbeddedDocumentField(UserLink)) gravatar_email = db.EmailField(max_length=255) def get_gravatar_email(self): return self.gravatar_email or self.email def clean(self, *args, **kwargs): if not self.username: self.username = User.generate_username(self.name) try: super(User, self).clean(*args, **kwargs) except: pass @classmethod def generate_username(cls, name): # username = email.lower() # for item in ['@', '.', '-', '+']: # username = username.replace(item, '_') # return username username = slugify(name) if cls.objects.filter(username=username).count(): username = "******".format(username, randint(1, 1000)) return username def set_password(self, password, save=False): self.password = encrypt_password(password) if save: self.save() @classmethod def createuser(cls, name, email, password, active=True, roles=None, username=None, *args, **kwargs): username = username or cls.generate_username(name) if "links" in kwargs: kwargs["links"] = [UserLink(**link) for link in kwargs['links']] return cls.objects.create(name=name, email=email, password=encrypt_password(password), active=active, roles=roles, username=username, *args, **kwargs) @property def display_name(self): return abbreviate(self.name) or self.email def __unicode__(self): return u"{0} <{1}>".format(self.name or '', self.email) @property def connections(self): return Connection.objects(user_id=str(self.id))
class UserLink(db.EmbeddedDocument): title = db.StringField(max_length=50, required=True) link = db.StringField(max_length=255, required=True) icon = db.StringField(max_length=255) css_class = db.StringField(max_length=50) order = db.IntField(default=0)
class User(db.DynamicDocument, UserMixin): name = db.StringField(max_length=255, verbose_name=_l('Name')) email = db.EmailField(max_length=255, unique=True, verbose_name=_l('Email')) password = db.StringField(max_length=255, verbose_name=_l('Password')) active = db.BooleanField(default=True, verbose_name=_l('Active')) confirmed_at = db.DateTimeField(verbose_name=_l('Confirmed At')) roles = db.ListField(db.ReferenceField(Role, reverse_delete_rule=db.DENY), default=[], verbose_name=_l('Roles')) last_login_at = db.DateTimeField(verbose_name=_l('Last Login At')) current_login_at = db.DateTimeField(verbose_name=_l('Current Login At')) last_login_ip = db.StringField(max_length=255, verbose_name=_l('Last Login IP')) current_login_ip = db.StringField(max_length=255, verbose_name=_l('Current Login IP')) login_count = db.IntField(verbose_name=_l('Login Count')) username = db.StringField(max_length=50, required=False, unique=True, verbose_name=_l('Username')) remember_token = db.StringField(max_length=255, verbose_name=_l('Remember Token')) authentication_token = db.StringField( max_length=255, verbose_name=_l('Authentication Tokern')) def clean(self, *args, **kwargs): if not self.username: self.username = User.generate_username(self.email) try: super(User, self).clean(*args, **kwargs) except: pass @classmethod def generate_username(cls, email): username = email.lower() for item in ['@', '.', '-', '+']: username = username.replace(item, '_') return username def set_password(self, password, save=False): self.password = encrypt_password(password) if save: self.save() @classmethod def createuser(cls, name, email, password, active=True, roles=None, username=None): username = username or cls.generate_username(email) return cls.objects.create(name=name, email=email, password=encrypt_password(password), active=active, roles=roles, username=username) @property def display_name(self): return self.name or self.email def __unicode__(self): return u"{0} <{1}>".format(self.name or '', self.email) @property def connections(self): return Connection.objects(user_id=str(self.id))
class Ordered(object): order = db.IntField(required=True, default=1, verbose_name=_l('Order'))