예제 #1
0
 def get(self):  # pylint: disable-msg=C6409
     """Return a users snippets for the requested timeframe in JSON format."""
     snipper_user = models.GetSnippetUser(users.get_current_user())
     tz = pytz.timezone(snipper_user.timezone)
     try:
         offset = int(self.request.get('offset', default_value=0))
     except ValueError:
         offset = 0
     results = models.FetchSnippets(offset=offset)
     self.response.headers['Content-Type'] = 'application/json'
     start_date = util.GetLastWeekDay(snipper_user.reset_day, offset,
                                      snipper_user.reset_hour, tz)
     end_date = util.GetNextWeekDay(snipper_user.reset_day, offset,
                                    snipper_user.reset_hour, tz)
     ret = {
         'snippets': [{
             'key': str(s.key()),
             'text': s.Snippet
         } for s in results],
         'dates': {
             'from': start_date.strftime('%b %d'),
             'to': end_date.strftime('%b %d')
         }
     }
     self.response.out.write(simplejson.dumps(ret))
예제 #2
0
    def get(self):
        """Render the preferences page."""
        user = users.get_current_user()
        snipper_user = models.GetSnippetUser(user)
        errors = self.request.get('errors', '')
        logging.info(errors)
        errors = filter(None, errors.split(','))
        logging.info(errors)

        template_values = {
            'gaia':
            util.GetGaiaData(user),
            'user':
            user,
            'errors':
            errors,
            'snipper_user':
            snipper_user,
            'reset_days':
            calendar.day_name,
            'reset_hours':
            ([(0, '12 am')] + [(x, '%s am' % x) for x in xrange(1, 12)] +
             [(12, '12 pm')] + [(x, '%s pm' % (x - 12))
                                for x in xrange(13, 24)]),
        }
        path = os.path.join(os.path.dirname(__file__),
                            'templates/preferences.html')
        rendered_page = template.render(path, template_values)
        self.response.headers['Expires'] = util.GetExpiryHeader(minutes=0)
        self.response.headers['Cache-Control'] = 'private, max-age=0'
        self.response.out.write(rendered_page)
예제 #3
0
  def post(self):
    """Get a chat, add to datastore."""
    err_msg = ':( %s'
    msg_from = self.request.get('from', '')
    msg_body = self.request.get('body', '').strip()
    if msg_body:
      logging.debug('Got a chat message from %s: "%s"', msg_from, msg_body)

      # Grab the username by removing the resource (if present) from the JID
      user_address = msg_from.split('/', 1)[0]

      # Try to create a snippetUser object.
      user = users.User(user_address)
      snipper_user = models.GetSnippetUser(user)
      if not snipper_user:
        logging.debug('Could not create a User object.')
        self.Reply(msg_from, err_msg)
        return

      # Disable the confirmation message for users that don't want it.
      if snipper_user.send_confirm is False:
        success_msg = ''
      else:
        # Check for April 1st, display cheeky messages :).
        now = datetime.datetime.now(pytz.timezone(snipper_user.timezone))
        cheeky = False
        if snipper_user.cheeky_confirm or (now.month == 4 and now.day == 1):
          cheeky = True
        success_msg = GetNextSuccessMsg(user.nickname(), cheeky)

      # Handle commands sent by chat.
      cmd = msg_body.lower()
      if cmd in _CHAT_COMMANDS:
        replies = _CHAT_COMMANDS[cmd](user)
        # Send the replies back to the user then quit.
        self.Reply(msg_from, replies)
        return

      # Convert multi-line snippets into a list.
      snippets = msg_body.splitlines()
      # Try to save each snippet, and store the result in the list.
      results, errors = zip(*[models.SaveSnippet(user, 'xmpp', s)
                              for s in snippets])

      if False not in results:
        message = success_msg
      else:
        message = err_msg % filter(None, errors)[0]  # Return the first error.
        logging.debug('%s said "%s"', msg_from, msg_body)

      if message:
        self.Reply(msg_from, message)
예제 #4
0
    def get(self):  # pylint: disable-msg=C6409
        """Render the Snipper page."""
        user = users.get_current_user()
        snipper_user = models.GetSnippetUser(user)
        tz = pytz.timezone(snipper_user.timezone)
        try:
            offset = int(self.request.get('offset', default_value=0))
        except ValueError:
            offset = 0
        results = models.FetchSnippets(offset=offset)
        snippets = [s.Snippet for s in results]
        template_values = {
            'gaia':
            util.GetGaiaData(user),
            'user':
            user,
            'reset_day':
            calendar.day_name[snipper_user.reset_day],
            'start':
            util.GetLastWeekDay(snipper_user.reset_day,
                                hour=snipper_user.reset_hour,
                                tz=tz),
            'end':
            util.GetNextWeekDay(snipper_user.reset_day,
                                hour=snipper_user.reset_hour,
                                tz=tz),
            'snippets':
            snippets,
            'offset':
            offset,
            'older':
            offset + 1,
            'msg':
            self.request.get('msg'),
        }
        if offset:
            template_values['newer'] = offset - 1
        else:
            template_values['newer'] = 0

        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        rendered_page = template.render(path, template_values)
        self.response.headers['Expires'] = util.GetExpiryHeader(minutes=1)
        self.response.headers['Cache-Control'] = 'private, max-age=60'
        self.response.out.write(rendered_page)
예제 #5
0
    def post(self):  # pylint: disable-msg=C6409
        """Add a snippet to the datastore for a user. Print 1 on success."""
        self.response.headers['Content-Type'] = 'application/json'
        user = users.get_current_user()
        snip = self.request.get('s', '')
        version = self.request.get('v', '')
        if not user:
            logging.debug(
                'Could not get user information, bailing out. '
                'Version: %s Snippet: %s', version, snip)
            self.response.out.write('0')
            return
        # Make sure the user has been added.
        assert models.GetSnippetUser(user)
        if not snip:
            logging.debug('Empty snippet.')
            self.response.out.write('0')
            return

        result = models.SaveSnippet(user, version, snip)
        self.response.out.write(int(result[0]))
예제 #6
0
 def post(self):
     """Save the user's preferences."""
     user = users.get_current_user()
     snipper_user = models.GetSnippetUser(user)
     logging.debug('Saving settings for %s', user)
     errors = []
     date_format = str(
         self.request.get('date_format', snipper_user.date_format))
     snippet_format = self.request.get('snippet_format',
                                       snipper_user.snippet_format)
     snipper_user.mail_snippets = bool(
         self.request.get('mail_snippets', False))
     snipper_user.send_confirm = bool(
         self.request.get('send_confirm', False))
     snipper_user.reset_day = int(
         self.request.get('reset_day', snipper_user.reset_day))
     snipper_user.reset_hour = int(
         self.request.get('reset_hour', snipper_user.reset_hour))
     timezone = self.request.get('timezone')
     try:
         assert pytz.timezone(timezone)
     except pytz.UnknownTimeZoneError:
         logging.exception('Invalid timezone: %s', timezone)
         errors.append('Invalid timezone: %s.' % timezone)
     else:
         snipper_user.timezone = timezone
         # Convert to UTC for storage.
         utc_reset = util.ResetDatetimeToUtc(snipper_user.reset_day,
                                             snipper_user.reset_hour,
                                             snipper_user.timezone)
         snipper_user.utc_reset_day = utc_reset.weekday()
         snipper_user.utc_reset_hour = utc_reset.hour
     try:
         assert datetime.datetime.now().strftime(date_format)
     except (ValueError, TypeError):
         errors.append('Invalid date format "%s".' % date_format)
         logging.exception('date_format "%s" failed validation.',
                           date_format)
     else:
         snipper_user.date_format = date_format
     try:
         assert snippet_format % 'test snippet'
     except (ValueError, TypeError):
         errors.append('Invalid snippet format "%s".' % snippet_format)
         logging.exception('snippet_format "%s" is invalid.',
                           snippet_format)
     else:
         snipper_user.snippet_format = snippet_format
     logging.debug(
         'date:%s, snip:%s, mail:%s, conf:%s, day:%s, hour:%s, tz:%s'
         'utc_day:%s, utc_hour:%s', snipper_user.date_format,
         snipper_user.snippet_format, snipper_user.mail_snippets,
         snipper_user.send_confirm, snipper_user.reset_day,
         snipper_user.reset_hour, snipper_user.timezone,
         snipper_user.utc_reset_day, snipper_user.utc_reset_hour)
     try:
         db.put(snipper_user)
     except (db.Timeout, db.InternalError):
         logging.exception('Could not save settings.')
         errors.append('Could not save settings.')
     else:
         memcache_key = 'SnippetUser-' + str(user)
         memcache.set(memcache_key, snipper_user)
     if errors:
         errors = urllib.quote_plus(','.join(errors))
         return self.redirect('/settings?errors=' + errors)
     # Drop the last two weeks from memcache.
     memcache.delete_multi(
         ['snippets_%s_%d' % (str(user), x) for x in (0, 1)])
     self.redirect('/?msg=Settings+saved.')
예제 #7
0
def GetUserInfo(user):
  """Return the user's information."""
  snipper_user = models.GetSnippetUser(user)
  return '%s , %s' % (user.email(), snipper_user.timezone)
예제 #8
0
    def post(self):  # pylint: disable-msg=C6409
        """Fetch the snippets for this user and create a mail-worker if needed."""
        is_cron = bool(self.request.get('is_cron'))
        last_cursor = self.request.get('cursor')
        cursor = None
        utc_reset_day = int(self.request.get('utc_reset_day'))
        utc_reset_hour = int(self.request.get('utc_reset_hour'))
        offset = int(self.request.get('offset', 0))
        user = users.get_current_user()
        email = self.request.get('email')
        if email and not user:
            logging.info(email)
            user = users.User(email)
        use_force = False
        logging.info('fetch worker called. is_cron: %s, user: %s, cursor: %s',
                     is_cron, user, last_cursor)
        if user and users.is_current_user_admin(
        ):  # Only admins may use force.
            use_force = bool(self.request.get('use_force'))
            logging.info('admin %s requests use of force %s!', user.email(),
                         use_force)
        if last_cursor:  # If last_cursor exists, it must persist and continue.
            logging.info(
                'last_cursor exists, setting is_cron and use_force to True.')
            is_cron = True
            use_force = True

        if is_cron or use_force:  # Fetch all users.
            logging.info('fetching next user...')
            offset = 1
            user_query = models.SnippetUser.all()
            user_query.filter('mail_snippets =', True)
            user_query.filter('utc_reset_day =', utc_reset_day)
            user_query.filter('utc_reset_hour =', utc_reset_hour)
            if last_cursor:
                user_query.with_cursor(last_cursor)
            snipper_user = user_query.order('User').get()
            if not snipper_user:  # No more users, time to quit.
                logging.info('No more users, delete the cursor and quit.')
                return
            user = snipper_user.User
            cursor = user_query.cursor()
            logging.info('Found user %s and stored cursor %s.', user, cursor)
        else:
            logging.info('fetching single user...')
            offset = int(self.request.get('offset', default_value=0))
            snipper_user = models.GetSnippetUser(user)

        logging.info('User is %s', user)
        if user is None:
            return
        # Get snippets.
        if is_cron or use_force:
            # TODO(erichiggins): Clean this up. Consider verifying the dates from
            # GetLastWeekday and use that to determine the proper offset value.
            # Just get snippets from 7 days ago until now.
            start_date = (
                datetime.datetime.utcnow().replace(second=0, microsecond=0) -
                datetime.timedelta(days=7))
            query = models.Snippet.all().filter('User ='******'DateStamp >=', start_date)
            query.order('DateStamp')
            snippet_results = query.fetch(limit=1000)
        else:
            # Clear out memcache, the reset messes up results.
            memcache.delete_multi(
                ['snippets_%s_%d' % (str(user), x) for x in (0, 1)])
            snippet_results = models.FetchSnippets(user=user, offset=offset)
        logging.debug('%s has %s snippets.', user.nickname(),
                      len(snippet_results))

        if snippet_results:
            user_tz = pytz.timezone(snipper_user.timezone)
            datestamp = util.GetLastWeekDay(utc_reset_day,
                                            offset=offset,
                                            hour=utc_reset_hour,
                                            tz=pytz.utc)
            snippet_format = snipper_user.snippet_format
            date_format = str(snipper_user.date_format)
            datestamp = datestamp.astimezone(user_tz).strftime(date_format),
            # Format each snippet according to the user's preference.
            try:
                snippets = [
                    snippet_format % s.Snippet for s in snippet_results
                ]
            except TypeError:
                logging.debug('%s has an invalid snippet_format: "%s"', user,
                              snippet_format)
                snippets = ['- %s' % s.Snippet for s in snippet_results]
            if snippets:
                # Add a task to the queue to send an email to each snipper user.
                mail_params = {
                    'user': user.nickname(),
                    'email': user.email(),
                    'datestamp': datestamp,
                    'snippets': '\n'.join(snippets),
                }
                logging.info('Creating mail task with params: %s', mail_params)
                mail_task = taskqueue.Task(url='/report/mail',
                                           params=mail_params)
                mail_task.add(queue_name='snippet-mail-queue')
            else:
                logging.info('No snippets to mail...')
        else:
            logging.info('snippet_results is empty...')

        if is_cron:  # Run the next fetch worker.
            params = {
                'is_cron': is_cron,
                'offset': offset,
                'use_force': int(use_force),
                'utc_reset_day': utc_reset_day,
                'utc_reset_hour': utc_reset_hour,
                'cursor': cursor,
            }
            logging.info('params for next run: %s', params)
            fetch_task = taskqueue.Task(url='/report/fetch', params=params)
            fetch_task.add(queue_name='snippet-fetch-queue')