Exemplo n.º 1
0
def active(patterns, tag = 'active', exact = False, *args):
    """
    Checks if a given regex pattern is the current request path.
    Useful for seeing if a current menu item is active.

    Arguments:
        patterns: a pattern for URL reverse or a regex. Can be a string separated by commas for multiple
        tag: an optional string to return if the pattern is matched. Defaults to active.
        exact: whether an exact match is required

    Usage:
         <a class="{% active "^/services/" %}" href="/services/">Services</a>
    """
    request = get_request()

    patterns = patterns.split(',')

    for pattern in patterns:
        try:
            pattern = reverse(pattern, args=args)
        except NoReverseMatch:
            pass

        if exact:
            if request.path == pattern:
                return tag
        else:
            if re.search(pattern, request.path):
                return tag
    return ''
def add_to_session(target, read_only):
    """
    This adds a hash that identifies the contents of a wall of comments_list in the session
    This hash will get checked against when loading more comments, to make sure
    They are allowed to load the content they are asking for

    The hashing algorithm is sha224

    Arguments
        target: the target(s) that are getting hashed
    """

    # for security, store a hash of this comments conetents in the users session
    request = get_request()

    # create our list if nonexistant
    if not 'primer_comment_hashes' in request.session:
        request.session['primer_comment_hashes'] = {}

    # convert the stream to a serialized list of content_types and pks
    target_list = get_content_types_list(target)
    comment_hash = get_content_types_hash(target_list)

    # add it to the session
    request.session['primer_comment_hashes'][comment_hash] = {
        'content_types' : target_list,
        'read_only' : bool(read_only),
        'blah' : 'foo'
    }

    request.session.save()
    print read_only

    return comment_hash
Exemplo n.º 3
0
def active(patterns, tag='active', exact=False, *args):
    """
    Checks if a given regex pattern is the current request path.
    Useful for seeing if a current menu item is active.

    Arguments:
        patterns: a pattern for URL reverse or a regex. Can be a string separated by commas for multiple
        tag: an optional string to return if the pattern is matched. Defaults to active.
        exact: whether an exact match is required

    Usage:
         <a class="{% active "^/services/" %}" href="/services/">Services</a>
    """
    request = get_request()

    patterns = patterns.split(',')

    for pattern in patterns:
        try:
            pattern = reverse(pattern, args=args)
        except NoReverseMatch:
            pass

        if exact:
            if request.path == pattern:
                return tag
        else:
            if re.search(pattern, request.path):
                return tag
    return ''
Exemplo n.º 4
0
def render(args=None, use_request_context = True, request=None):
    '''
    Magic render... steal the request from the calling function.
    The template is determinted by whatever is set in args.template
    and lastly, pass in any of their arguments

    requires the primer.middleware.AutoMiddleware for the extra request parameters
    '''
    #get the request out of the stack
    if request is None:
        request = get_request()

    #make args an empty dictionary if it is none so we can merge it with kwargs
    if not args:
        args = {}
    
    #check to see what template we should render
    #if the dev passed one, honor that, otherwise use the one determined in primer middleware
    if not 'view_template' in args:
        args['view_template'] = request.primer.get('view_template')

    if use_request_context:
        return django_render(request, args['view_template'], args, context_instance=RequestContext(request))
    else:
        return django_render(request, args['view_template'], args)
Exemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)

        # so, we hid it in our default form, but we want to support
        # non authenticated comments lists, so re-show the fields
        request = get_request()
        if not request.user.is_authenticated():
            self.fields['name'].widget = forms.TextInput(attrs = {'placeholder' : 'Name'})
            self.fields['name'].required = True
            self.fields['email'].widget = forms.TextInput(attrs = {'placeholder' : 'Email'})
            self.fields['email'].required = True
Exemplo n.º 6
0
 def get_channels_for_user(self, user):
     """
     Accepts a single user object and returns their
     randomized channel names that are stored int their sessions
     """
     request = get_request()
     
     # get the sessions for authenticated users. We have patched a user onto the sessions table
     if user is not request.user or request.user.is_authenticated():
         sessions = user.sessions.filter(expire_date__gt = datetime.now())
         return [ session.get_decoded().get('push_channel_id') for session in sessions if session.get_decoded().get('push_channel_id') ]
     
     # our user is not authenticated which means it must be the current logged in user
     elif user == request.user:
         return [ request.session.get('push_channel_id') ]
Exemplo n.º 7
0
    def get_channels_for_user(self, user):
        """
        Accepts a single user object and returns their
        randomized channel names that are stored int their sessions
        """
        request = get_request()

        # get the sessions for authenticated users. We have patched a user onto the sessions table
        if user is not request.user or request.user.is_authenticated():
            sessions = user.sessions.filter(expire_date__gt=datetime.now())
            return [
                session.get_decoded().get('push_channel_id')
                for session in sessions
                if session.get_decoded().get('push_channel_id')
            ]

        # our user is not authenticated which means it must be the current logged in user
        elif user == request.user:
            return [request.session.get('push_channel_id')]
Exemplo n.º 8
0
    def send(self):
        """
        Send and or save the actual notification
        """
        request = get_request()
        self.tags = '%s %s' % (self.tags, self.type)

        # if we still dont have any users, set it to the user in the request.
        # We do it here and not in model init to avoid redundant calls to get_request
        # when we might be saving the model directly
        if not len(self.users):
            self.users = [request.user]

        # if the store option is 1 or 2, we will store the notification
        if self.store == 1 or self.store == 2:

            # start by saving the actual notification
            notification = NotificationStore(message=self.message,
                                             target=self.get_target(),
                                             type=self.type,
                                             sender=self.sender,
                                             data=self.data).save()

            # loop through and create following links for users
            followers_to_save = []
            for user in self.users:

                # catch if is is an unauthenticated user, we wont save
                if user == request.user and not request.user.is_authenticated(
                ):
                    continue
                else:
                    followers_to_save.append(
                        UserNotification(user=user, notification=notification))

            # bulk save the user links
            UserNotification.objects.bulk_create(followers_to_save)

            # update the users notification counts
            for user in self.users:
                push_count_update(user)

        # here we check to see that the notification should actually be sent, which is any storage level except 2
        if self.store != 2:

            for user in self.users:

                # push our notification is push is set to true and we have a push service
                if self.push and PushService:

                    # here we have a user making a request that is not ajax and the push notification is supposed to go to them
                    # it will never make it there because of the page request, so just catch it and send it through normally
                    if not request.is_ajax() and user == request.user:
                        messages.add_message(request,
                                             messages.INFO,
                                             self,
                                             extra_tags=self.tags)
                    else:

                        # we will send through our arbitrary data with the message
                        push_data = {
                            'message': self.message,
                            'tags': self.tags
                        }
                        if self.data: push_data.update(self.data)

                        PushService.send(event='notification.new-notification',
                                         data=push_data,
                                         users=user)

                else:
                    if user == request.user:
                        messages.add_message(request,
                                             messages.INFO,
                                             self,
                                             extra_tags=self.tags)
Exemplo n.º 9
0
    def send(self):
        """
        Send and or save the actual notification
        """ 
        request = get_request()
        self.tags = '%s %s' % (self.tags, self.type)

        # if we still dont have any users, set it to the user in the request.
        # We do it here and not in model init to avoid redundant calls to get_request
        # when we might be saving the model directly
        if not len(self.users):
            self.users = [request.user]

        # if the store option is 1 or 2, we will store the notification
        if self.store == 1 or self.store == 2:
            
            # start by saving the actual notification
            notification = NotificationStore(
                message = self.message,
                target = self.get_target(),
                type = self.type,
                sender = self.sender,
                data = self.data
                ).save()

            # loop through and create following links for users
            followers_to_save = []
            for user in self.users:

                # catch if is is an unauthenticated user, we wont save
                if user == request.user and not request.user.is_authenticated():
                    continue
                else:
                    followers_to_save.append(UserNotification(user = user, notification = notification))

            # bulk save the user links
            UserNotification.objects.bulk_create(followers_to_save)

            # update the users notification counts
            for user in self.users:
                push_count_update(user)


        # here we check to see that the notification should actually be sent, which is any storage level except 2
        if self.store != 2:

            for user in self.users:

                # push our notification is push is set to true and we have a push service
                if self.push and PushService:

                    # here we have a user making a request that is not ajax and the push notification is supposed to go to them
                    # it will never make it there because of the page request, so just catch it and send it through normally
                    if not request.is_ajax() and user == request.user:
                        messages.add_message(request, messages.INFO, self, extra_tags = self.tags)
                    else:
                        
                        # we will send through our arbitrary data with the message
                        push_data = {'message' : self.message, 'tags' : self.tags}
                        if self.data: push_data.update(self.data)

                        PushService.send(
                            event = 'notification.new-notification', 
                            data = push_data,
                            users = user
                            )

                else:
                    if user == request.user:
                        messages.add_message(request, messages.INFO, self, extra_tags = self.tags)