Beispiel #1
0
class Channeling(object):
    channel = db.ReferenceField(Channel, required=True,
                                reverse_delete_rule=db.DENY)
    related_channels = db.ListField(
        db.ReferenceField('Channel', reverse_delete_rule=db.PULL)
    )
    show_on_channel = db.BooleanField(default=True)
Beispiel #2
0
class SubContent(Publishable, Ordered, db.EmbeddedDocument):
    """Content can have inner contents
    Its useful for any kind of relation with Content childs
    Images, ImageGalleries, RelatedContent, Attachments, Media
    """

    content = db.ReferenceField('Content', required=True)
    caption = db.StringField()
    purpose = db.ReferenceField(SubContentPurpose, required=True)
    identifier = db.StringField()

    @property
    def thumb(self):
        try:
            return url_for('media', filename=self.content.thumb)
            # return self.content.thumb
        except Exception as e:
            logger.warning(str(e))
            return self.content.get_main_image_url(thumb=True)

    meta = {
        'ordering': ['order'],
        'indexes': ['order']
    }

    def clean(self):
        self.identifier = self.purpose.identifier

    def __unicode__(self):
        return self.content and self.content.title or self.caption
Beispiel #3
0
class CourseSubscription(BaseProductReference, Publishable,
                         db.DynamicDocument):
    subscriber = db.ReferenceField(Subscriber, reverse_delete_rule=db.NULLIFY)
    student = db.ReferenceField(Subscriber, reverse_delete_rule=db.NULLIFY)
    course = db.ReferenceField(Course,
                               required=True,
                               reverse_delete_rule=db.DENY)
    classroom = db.StringField()
    variant = db.EmbeddedDocumentField(CourseVariant)
    status = db.StringField(default="pending")
    unity_value = db.FloatField()
    total_value = db.FloatField()
    cart = db.ReferenceField(Cart, reverse_delete_rule=db.NULLIFY)
    confirmed_date = db.DateTimeField()

    def clean(self):
        self.unity_value = self.get_unity_value()

    def __unicode__(self):
        if self.variant:
            return u"{s.course.title} {s.classroom} {s.variant}".format(s=self)
        else:
            return self.course.title

    def get_title(self):
        return self.course.get_title()

    def get_description(self):
        return "<br>".join([
            self.course.get_summary(classroom=self.classroom),
            self.variant.get_description() if self.variant else '',
            self.student.name if self.student else ''
        ])

    def get_unity_value(self):
        if self.unity_value:
            return self.unity_value
        if self.variant and self.variant.unity_value:
            return self.variant.unity_value
        return self.course.get_unity_value()

    def get_weight(self):
        return getattr(self, 'weight', None)

    def get_dimensions(self):
        return getattr(self, 'dimensions', None)

    def get_extra_value(self):
        return getattr(self, 'extra_value', None)

    def get_uid(self):
        return str(self.id)

    def set_status(self, status, *args, **kwargs):
        self.status = status
        if status == "confirmed":
            now = datetime.datetime.now()
            self.confirmed_date = kwargs.get('date', now)
        self.save()
Beispiel #4
0
class Channeling(object):
    channel = db.ReferenceField(Channel, required=True,
                                reverse_delete_rule=db.DENY)
    # Objects can be in only one main channel it gives an url
    # but the objects can also be relates to other channels
    related_channels = db.ListField(
        db.ReferenceField('Channel', reverse_delete_rule=db.NULLIFY)
    )
    show_on_channel = db.BooleanField(default=True)
Beispiel #5
0
class Channeling(object):
    channel = db.ReferenceField(Channel, required=True,
                                reverse_delete_rule=db.DENY,
                                verbose_name=_l('Channel'))
    related_channels = db.ListField(
        db.ReferenceField('Channel', reverse_delete_rule=db.PULL),
        verbose_name=_l('Related Channels')
    )
    show_on_channel = db.BooleanField(default=True,
                                      verbose_name=_l('Show On Channel'))
Beispiel #6
0
class Owned(object):
    created_by = db.ReferenceField(User)
    last_updated_by = db.ReferenceField(User)
    authors = db.ListField(db.ReferenceField(User))

    def get_authors(self, sortedf=None):
        return set(self.authors + [self.created_by])

    @property
    def has_multiple_authors(self):
        return len(self.get_authors()) > 1
Beispiel #7
0
class Channeling(object):
    channel = db.ReferenceField(Channel,
                                required=True,
                                reverse_delete_rule=db.DENY)
    related_channels = db.ListField(
        db.ReferenceField('Channel', reverse_delete_rule=db.PULL))
    related_mpath = db.ListField(db.StringField())
    show_on_channel = db.BooleanField(default=True)
    channel_roles = db.ListField(db.StringField())

    def populate_related_mpath(self):
        self.related_mpath = [rel.mpath for rel in self.related_channels]

    def populate_channel_roles(self):
        self.channel_roles = [role.name for role in self.channel.roles]
Beispiel #8
0
class AggregatedTopic(db.Document):
    """
    Store topics from external blogs
    """

    original_url = db.StringField(required=True)
    date_added = db.DateTimeField(default=datetime.now())
    blog = db.ReferenceField('ExternalBlogs',
                             required=True,
                             reverse_delete_rule=db.CASCADE)
    post = db.ReferenceField('Post',
                             required=True,
                             reverse_delete_rule=db.CASCADE)

    def __str__(self):
        return self.post.title
Beispiel #9
0
class SubContent(Publishable, Ordered, db.EmbeddedDocument):
    """Content can have inner contents
    Its useful for any kind of relation with Content childs
    Images, ImageGalleries, RelatedContent, Attachments, Media
    """

    content = db.ReferenceField('Content', required=True)
    caption = db.StringField()
    purpose = db.ReferenceField(SubContentPurpose, required=True)

    meta = {
        'ordering': ['order'],
        'indexes': ['order']
    }

    def __unicode__(self):
        return self.content.title
Beispiel #10
0
class ContactInfo(db.DynamicDocument):
    user = db.ReferenceField(User, reverse_delete_rule=db.CASCADE)

    def to_json(self):
        rtn = json.loads(super(ContactInfo, self).to_json())
        rtn.pop('user')
        rtn.update(json.loads(self.user.to_json()))
        return json.dumps(rtn)
Beispiel #11
0
class Content(HasCustomValue, Publishable, LongSlugged, Commentable,
              Channeling, Tagged, db.DynamicDocument):
    title = db.StringField(max_length=255, required=True)
    summary = db.StringField(required=False)
    template_type = db.ReferenceField(ContentTemplateType,
                                      required=False,
                                      reverse_delete_rule=db.NULLIFY)
    contents = db.ListField(db.EmbeddedDocumentField(SubContent))
    model = db.StringField()

    meta = {
        'allow_inheritance': True,
        'indexes': ['-created_at', 'slug'],
        'ordering': ['-created_at']
    }

    def get_themes(self):
        themes = self.channel.get_themes()
        theme = self.template_type and self.template_type.theme_name
        if theme:
            themes.insert(0, theme)
        return list(set(themes))

    def get_absolute_url(self, endpoint='detail'):
        if self.channel.is_homepage:
            long_slug = self.slug
        else:
            long_slug = self.long_slug

        try:
            return url_for(self.URL_NAMESPACE, long_slug=long_slug)
        except:
            return url_for(endpoint, long_slug=long_slug)

    def __unicode__(self):
        return self.title

    @property
    def model_name(self):
        return self.__class__.__name__.lower()

    @property
    def module_name(self):
        module = self.__module__
        module_name = module.replace('quokka.modules.', '').split('.')[0]
        return module_name

    def heritage(self):
        self.model = "{0}.{1}".format(self.module_name, self.model_name)

    def save(self, *args, **kwargs):
        self.validate_slug()
        self.validate_long_slug()
        self.heritage()
        super(Content, self).save(*args, **kwargs)
Beispiel #12
0
class Publishable(object):
    published = db.BooleanField(default=False)
    available_at = db.DateTimeField(default=datetime.datetime.now)
    created_at = db.DateTimeField(default=datetime.datetime.now)
    updated_at = db.DateTimeField(default=datetime.datetime.now)
    created_by = db.ReferenceField(User, reverse_delete_rule=db.DENY)
    last_updated_by = db.ReferenceField(User, reverse_delete_rule=db.DENY)

    def save(self, *args, **kwargs):
        self.updated_at = datetime.datetime.now()

        try:
            user = User.objects.get(id=current_user.id)
            if not self.id:
                self.created_by = user
            self.last_updated_by = user
        except Exception as e:
            logger.warning("No user to save the model: %s" % e.message)

        super(Publishable, self).save(*args, **kwargs)
Beispiel #13
0
class Subscriber(db.DynamicDocument):
    name = db.StringField()
    email = db.EmailField()
    document = db.StringField()
    phone = db.StringField()
    address = db.StringField()
    user = db.ReferenceField('User',
                             default=get_current_user,
                             reverse_delete_rule=db.NULLIFY)

    def __unicode__(self):
        return self.name
Beispiel #14
0
class Processor(Publishable, db.DynamicDocument):
    identifier = db.StringField(max_length=100, unique=True)
    module = db.StringField(max_length=255)
    requires = db.ListField(db.StringField(max_length=255))
    description = db.StringField()
    title = db.StringField()
    image = db.ReferenceField(Image, reverse_delete_rule=db.NULLIFY)
    link = db.StringField(max_length=255)
    config = db.DictField(default=lambda: {})
    pipeline = db.ListField(db.StringField(max_length=255), default=[])

    def import_processor(self):
        return import_string(self.module)

    def get_instance(self, *args, **kwargs):
        if 'config' not in kwargs:
            kwargs['config'] = self.config
        kwargs['_record'] = self
        return self.import_processor()(*args, **kwargs)

    def clean(self, *args, **kwargs):
        for item in (self.requires or []):
            import_string(item)
        super(Processor, self).clean(*args, **kwargs)

    def __unicode__(self):
        return self.identifier

    @classmethod
    def get_instance_by_identifier(cls, identifier, cart=None):
        processor = cls.objects.get(identifier=identifier)
        return processor.get_instance(cart=cart)

    @classmethod
    def get_default_processor(cls):
        default = lazy_str_setting('CART_DEFAULT_PROCESSOR',
                                   default={
                                       'module':
                                       'quokka.modules.cart.processors.Dummy',
                                       'identifier': 'dummy',
                                       'published': True,
                                       'title': "Test"
                                   })

        try:
            return cls.objects.get(identifier=default['identifier'])
        except:
            return cls.objects.create(**default)

    def save(self, *args, **kwargs):
        self.import_processor()
        super(Processor, self).save(*args, **kwargs)
Beispiel #15
0
class ExternalBlogs(db.Document):
    """
    Blogs that should be aggregated
    """
    name = db.StringField(max_length=255, required=True)
    root_url = db.StringField(default='')
    feeds_url = db.StringField(required=True)
    channel = db.ReferenceField('Channel',
                                required=True,
                                reverse_delete_rule=db.CASCADE)

    def __str__(self):
        return self.name
Beispiel #16
0
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)
Beispiel #17
0
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)
Beispiel #18
0
class Comment(db.EmbeddedDocument):
    body = db.StringField(verbose_name="Comment", required=True)
    author = db.StringField(verbose_name="Name", max_length=255, required=True)
    published = db.BooleanField(default=True)
    created_at = db.DateTimeField(default=datetime.datetime.now)
    created_by = db.ReferenceField(User)

    def __unicode__(self):
        return "{}-{}...".format(self.author, self.body[:10])

    meta = {
        'indexes': ['-created_at', '-available_at'],
        'ordering': ['-created_at']
    }
Beispiel #19
0
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)
Beispiel #20
0
class Content(HasCustomValue, Publishable, LongSlugged,
              Channeling, Tagged, ContentFormat, db.DynamicDocument):
    title = db.StringField(max_length=255, required=True)
    summary = db.StringField(required=False)
    template_type = db.ReferenceField(ContentTemplateType,
                                      required=False,
                                      reverse_delete_rule=db.NULLIFY)
    contents = db.ListField(db.EmbeddedDocumentField(SubContent))
    model = db.StringField()
    comments_enabled = db.BooleanField(default=True)

    meta = {
        'allow_inheritance': True,
        'indexes': ['-created_at', 'slug'],
        'ordering': ['-created_at']
    }

    @classmethod
    def available_objects(cls, **filters):
        now = datetime.datetime.now()
        default_filters = {
            "published": True,
            'available_at__lte': now,
        }
        default_filters.update(filters)
        return cls.objects(**default_filters)

    def get_main_image_url(self, thumb=False,
                           default=None, identifier='mainimage'):
        """
        """
        if not isinstance(identifier, (list, tuple)):
            identifier = [identifier]

        for item in identifier:
            try:
                if not thumb:
                    path = self.contents.get(identifier=item).content.path
                else:
                    path = self.contents.get(identifier=item).content.thumb
                return url_for('media', filename=path)
            except Exception as e:
                logger.warning(str(e))

        return default

    def get_uid(self):
        return str(self.id)

    def get_themes(self):
        themes = self.channel.get_themes()
        theme = self.template_type and self.template_type.theme_name
        if theme:
            themes.insert(0, theme)
        return list(set(themes))

    def get_absolute_url(self, endpoint='detail'):
        if self.channel.is_homepage:
            long_slug = self.slug
        else:
            long_slug = self.long_slug

        try:
            return url_for(self.URL_NAMESPACE, long_slug=long_slug)
        except:
            return url_for(endpoint, long_slug=long_slug)

    def get_canonical_url(self, *args, **kwargs):
        return self.get_absolute_url()

    def get_recommendations(self, limit=3, ordering='-created_at', *a, **k):
        now = datetime.datetime.now()
        filters = {
            'published': True,
            'available_at__lte': now,
            "id__ne": self.id
        }
        contents = Content.objects(**filters).filter(tags__in=self.tags or [])

        return contents.order_by(ordering)[:limit]

    def get_summary(self):
        if self.summary:
            return self.summary
        return self.get_text()

    def get_text(self):
        if hasattr(self, 'body'):
            text = self.body
        elif hasattr(self, 'description'):
            text = self.description
        else:
            text = self.summary

        if self.content_format == "markdown":
            return markdown(text)
        else:
            return text

    def __unicode__(self):
        return self.title

    @property
    def model_name(self):
        return self.__class__.__name__.lower()

    @property
    def module_name(self):
        module = self.__module__
        module_name = module.replace('quokka.modules.', '').split('.')[0]
        return module_name

    def heritage(self):
        self.model = "{0}.{1}".format(self.module_name, self.model_name)

    def save(self, *args, **kwargs):
        self.validate_slug()
        self.validate_long_slug()
        self.heritage()
        super(Content, self).save(*args, **kwargs)
Beispiel #21
0
class Owned(object):
    created_by = db.ReferenceField(User)
    last_updated_by = db.ReferenceField(User)
Beispiel #22
0
class ChannelingNotRequired(Channeling):
    channel = db.ReferenceField(Channel, required=False,
                                reverse_delete_rule=db.NULLIFY)
Beispiel #23
0
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)
Beispiel #24
0
class Imaged(object):
    main_image = db.ReferenceField("Image")
    main_image_caption = db.StringField(max_length=255)
Beispiel #25
0
class HasImages(object):
    images = db.ListField(db.ReferenceField(DBImage))
Beispiel #26
0
class HasDBImage(object):
    image = db.ReferenceField(DBImage)
Beispiel #27
0
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))
Beispiel #28
0
class Item(Ordered, Dated, db.EmbeddedDocument):
    product = db.ReferenceField(Content)
    reference = db.GenericReferenceField()  # customized product
    """
    Must implement all the BaseProduct methods/ its optional
    if None, "product" will be considered
    """
    uid = db.StringField()
    title = db.StringField(required=True, max_length=255)
    description = db.StringField(required=True)
    link = db.StringField()
    quantity = db.FloatField(default=1)
    unity_value = db.FloatField(required=True)
    total_value = db.FloatField()
    weight = db.FloatField()
    dimensions = db.StringField()
    extra_value = db.FloatField()
    allowed_to_set = db.ListField(db.StringField(), default=['quantity'])
    pipeline = db.ListField(db.StringField(), default=[])

    def set_status(self, status, *args, **kwargs):
        kwargs['item'] = self
        if self.reference and hasattr(self.reference, 'set_status'):
            self.reference.set_status(status, *args, **kwargs)
        if self.product and hasattr(self.product, 'set_status'):
            self.product.set_status(status, *args, **kwargs)

    def get_main_image_url(self, thumb=False, default=None):
        try:
            return self.product.get_main_image_url(thumb, default)
        except:
            return None

    @classmethod
    def normalize(cls, kwargs):
        new = {}
        for k, v in kwargs.items():
            field = cls._fields.get(k)
            if not field:
                continue
            new[k] = field.to_python(v)
        return new

    def __unicode__(self):
        return u"{i.title} - {i.total_value}".format(i=self)

    def get_uid(self):
        try:
            return self.product.get_uid()
        except:
            return self.uid

    @property
    def unity_plus_extra(self):
        return float(self.unity_value or 0) + float(self.extra_value or 0)

    @property
    def total(self):
        self.clean()
        self.total_value = self.unity_plus_extra * float(self.quantity or 1)
        return self.total_value

    def clean(self):
        mapping = [
            ('title', 'get_title'),
            ('description', 'get_description'),
            ('link', 'get_absolute_url'),
            ('unity_value', 'get_unity_value'),
            ('weight', 'get_weight'),
            ('dimensions', 'get_dimensions'),
            ('extra_value', 'get_extra_value'),
            ('uid', 'get_uid'),
        ]

        references = [self.reference, self.product]

        for ref in references:
            if not ref:
                continue
            for attr, method in mapping:
                current = getattr(self, attr, None)
                if current is not None:
                    continue
                setattr(self, attr, getattr(ref, method, lambda: None)())
Beispiel #29
0
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)
Beispiel #30
0
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))