Ejemplo n.º 1
0
def _user_snippet(user_email, weeks_back=0):
    """Return the user's most recent Snippet.

    If one doesn't exist, one will be automatically filled from the template
    (but not saved).

    By using the optional `weeks_back` parameter, you can step backwards in
    time. Note that if you go back before the user's *first* snippet, they will
    not be filled (the default filling seems to only go forwardwise in time),
    and an IndexError will be raised.

    Raises an IndexError if requested snippet week comes before user birth.
    Raises ValueError if user couldn't be found.
    """
    account = util.get_user_or_die(user_email)  # can raise ValueError
    user_snips = util.snippets_for_user(user_email)
    logging.debug('User %s got snippets from db: %s', user_email,
                  len(user_snips))

    filled_snips = util.fill_in_missing_snippets(user_snips, account,
                                                 user_email, _TODAY_FN())
    logging.debug('User %s snippets *filled* to: %s', user_email,
                  len(filled_snips))

    index = (-1) - weeks_back
    return filled_snips[index]
Ejemplo n.º 2
0
def _user_snippet(user_email, weeks_back=0):
    """Return the user's most recent Snippet.

    If one doesn't exist, one will be automatically filled from the template
    (but not saved).

    By using the optional `weeks_back` parameter, you can step backwards in
    time. Note that if you go back before the user's *first* snippet, they will
    not be filled (the default filling seems to only go forwardwise in time),
    and an IndexError will be raised.

    Raises an IndexError if requested snippet week comes before user birth.
    Raises ValueError if user couldn't be found.
    """
    account = util.get_user_or_die(user_email)  # can raise ValueError
    user_snips = util.snippets_for_user(user_email)
    logging.debug(
        'User %s got snippets from db: %s', user_email, len(user_snips)
    )

    filled_snips = util.fill_in_missing_snippets(user_snips, account,
                                                 user_email, _TODAY_FN())
    logging.debug(
        'User %s snippets *filled* to: %s', user_email, len(filled_snips)
    )

    index = (-1) - weeks_back
    return filled_snips[index]
Ejemplo n.º 3
0
    def get(self):
        # options are 'email', 'creation_time', 'last_snippet_time'
        sort_by = self.request.get('sort_by', 'creation_time')

        # First, check if the user had clicked on a button.
        for (name, value) in self.request.params.iteritems():
            if name.startswith('hide '):
                email_of_user_to_hide = name[len('hide '):]
                # TODO(csilvers): move this get/update/put atomic into a txn
                user = util.get_user_or_die(email_of_user_to_hide)
                user.is_hidden = True
                user.put()
                time.sleep(0.1)  # encourage eventual consistency
                self.redirect('/admin/manage_users?sort_by=%s&msg=%s+hidden' %
                              (sort_by, email_of_user_to_hide))
                return
            if name.startswith('unhide '):
                email_of_user_to_unhide = name[len('unhide '):]
                # TODO(csilvers): move this get/update/put atomic into a txn
                user = util.get_user_or_die(email_of_user_to_unhide)
                user.is_hidden = False
                user.put()
                time.sleep(0.1)  # encourage eventual consistency
                self.redirect(
                    '/admin/manage_users?sort_by=%s&msg=%s+unhidden' %
                    (sort_by, email_of_user_to_unhide))
                return
            if name.startswith('delete '):
                email_of_user_to_delete = name[len('delete '):]
                user = util.get_user_or_die(email_of_user_to_delete)
                db.delete(user)
                time.sleep(0.1)  # encourage eventual consistency
                self.redirect('/admin/manage_users?sort_by=%s&msg=%s+deleted' %
                              (sort_by, email_of_user_to_delete))
                return

        user_q = models.User.all()
        results = user_q.fetch(1000)

        # Tuple: (email, is-hidden, creation-time, days since last snippet)
        user_data = []
        for user in results:
            # Get the last snippet for that user.
            last_snippet = util.most_recent_snippet_for_user(user.email)
            if last_snippet:
                seconds_since_snippet = ((_TODAY_FN().date() -
                                          last_snippet.week).total_seconds())
                weeks_since_snippet = int(
                    seconds_since_snippet /
                    datetime.timedelta(days=7).total_seconds())
            else:
                weeks_since_snippet = None
            user_data.append((user.email, user.is_hidden, user.created,
                              weeks_since_snippet))

        # We have to use 'cmp' here since we want ascending in the
        # primary key and descending in the secondary key, sometimes.
        if sort_by == 'email':
            user_data.sort(lambda x, y: cmp(x[0], y[0]))
        elif sort_by == 'creation_time':
            user_data.sort(lambda x, y: (-cmp(x[2] or datetime.datetime.min, y[
                2] or datetime.datetime.min) or cmp(x[0], y[0])))
        elif sort_by == 'last_snippet_time':
            user_data.sort(lambda x, y: (-cmp(1000 if x[3] is None else x[
                3], 1000 if y[3] is None else y[3]) or cmp(x[0], y[0])))
        else:
            raise ValueError('Invalid sort_by value "%s"' % sort_by)

        template_values = {
            'logout_url': users.create_logout_url('/'),
            'message': self.request.get('msg'),
            'username': _current_user_email(),
            'is_admin': users.is_current_user_admin(),
            'view_week': util.existingsnippet_monday(_TODAY_FN()),
            'user_data': user_data,
            'sort_by': sort_by,
        }
        self.render_response('manage_users.html', template_values)
Ejemplo n.º 4
0
    def get(self):
        # options are 'email', 'creation_time', 'last_snippet_time'
        sort_by = self.request.get('sort_by', 'creation_time')

        # First, check if the user had clicked on a button.
        for (name, value) in self.request.params.iteritems():
            if name.startswith('hide '):
                email_of_user_to_hide = name[len('hide '):]
                # TODO(csilvers): move this get/update/put atomic into a txn
                user = util.get_user_or_die(email_of_user_to_hide)
                user.is_hidden = True
                user.put()
                time.sleep(0.1)   # encourage eventual consistency
                self.redirect('/admin/manage_users?sort_by=%s&msg=%s+hidden'
                              % (sort_by, email_of_user_to_hide))
                return
            if name.startswith('unhide '):
                email_of_user_to_unhide = name[len('unhide '):]
                # TODO(csilvers): move this get/update/put atomic into a txn
                user = util.get_user_or_die(email_of_user_to_unhide)
                user.is_hidden = False
                user.put()
                time.sleep(0.1)   # encourage eventual consistency
                self.redirect('/admin/manage_users?sort_by=%s&msg=%s+unhidden'
                              % (sort_by, email_of_user_to_unhide))
                return
            if name.startswith('delete '):
                email_of_user_to_delete = name[len('delete '):]
                user = util.get_user_or_die(email_of_user_to_delete)
                db.delete(user)
                time.sleep(0.1)   # encourage eventual consistency
                self.redirect('/admin/manage_users?sort_by=%s&msg=%s+deleted'
                              % (sort_by, email_of_user_to_delete))
                return

        user_q = models.User.all()
        results = user_q.fetch(1000)

        # Tuple: (email, is-hidden, creation-time, days since last snippet)
        user_data = []
        for user in results:
            # Get the last snippet for that user.
            last_snippet = util.most_recent_snippet_for_user(user.email)
            if last_snippet:
                seconds_since_snippet = (
                    (_TODAY_FN().date() - last_snippet.week).total_seconds())
                weeks_since_snippet = int(
                    seconds_since_snippet /
                    datetime.timedelta(days=7).total_seconds())
            else:
                weeks_since_snippet = None
            user_data.append((user.email, user.is_hidden,
                              user.created, weeks_since_snippet))

        # We have to use 'cmp' here since we want ascending in the
        # primary key and descending in the secondary key, sometimes.
        if sort_by == 'email':
            user_data.sort(lambda x, y: cmp(x[0], y[0]))
        elif sort_by == 'creation_time':
            user_data.sort(lambda x, y: (-cmp(x[2] or datetime.datetime.min,
                                              y[2] or datetime.datetime.min)
                                         or cmp(x[0], y[0])))
        elif sort_by == 'last_snippet_time':
            user_data.sort(lambda x, y: (-cmp(1000 if x[3] is None else x[3],
                                              1000 if y[3] is None else y[3])
                                         or cmp(x[0], y[0])))
        else:
            raise ValueError('Invalid sort_by value "%s"' % sort_by)

        template_values = {
            'logout_url': users.create_logout_url('/'),
            'message': self.request.get('msg'),
            'username': _current_user_email(),
            'is_admin': users.is_current_user_admin(),
            'view_week': util.existingsnippet_monday(_TODAY_FN()),
            'user_data': user_data,
            'sort_by': sort_by,
        }
        self.render_response('manage_users.html', template_values)