Marc-Alexandre Chan avatar Marc-Alexandre Chan committed 3d43502

Fixed SuggestionThreadQueueMaintainer date calculation; harmonise logged times to UTC

Fixes issue 5.

Comments (0)

Files changed (1)

minibot/events.py

 from datetime import timedelta
 from calendar import timegm
 from urlparse import urlparse
-from time     import strftime, localtime
+from time     import strftime, localtime, gmtime
 import re
 
 # TODO: Organise these events into files/modules
         """ Return info string on a message for use in exceptions. """
         return 'message "{subject}" from {author} at {time}'.format(
             subject=msg.subject, author=msg.author.name,
-            time=strftime('%Y-%m-%d %H:%M:%S',
-                localtime(msg.created_utc)))
+            time=strftime('%Y-%m-%d %H:%M:%S UTC', gmtime(msg.created_utc)))
 
 
 class CheckPostQueueEvent(object):
         queued_ids = [ev.post_id for ev in
                       self.owner.get_events(PostPromptCommand)]
 
-        for id_, t_post in self.db.query(Prompt.id, Prompt.post_time).\
+        for id_, utc_post in self.db.query(Prompt.id, Prompt.post_time).\
                 filter(Prompt.post_time <= dt_limit).\
                 filter(Prompt.status == Prompt.STATUS_QUEUED).\
                 order_by(Prompt.post_time)[0:int(self.queue_rate)]:
             if id_ not in queued_ids:
-                self.log.info("%s: Queuing prompt %d at %s", classname(self),
-                id_, t_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
-                new_cmd = PostPromptCommand(id_, t_post)
+                self.log.info("%s: Queuing prompt %d at %s",
+                    classname(self), id_,
+                    utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
+                new_cmd = PostPromptCommand(id_, utc_post)
                 self.owner.queue_event(new_cmd)
         self.db.close()
 
         queued_ids = [ev.post_id for ev in
                         self.owner.get_events(PostSuggestionThreadCommand)]
 
-        for id_, t_post in\
+        for id_, utc_post in\
                 self.db.query(SuggestionThread.id, SuggestionThread.time).\
                 filter(SuggestionThread.time <= dt_limit).\
                 filter(SuggestionThread.status==SuggestionThread.STATUS_QUEUED).\
                 order_by(SuggestionThread.time)[0:int(self.queue_rate)]:
             if id_ not in queued_ids:
-                self.log.info(
-                    "%s: Queuing thread %d at %s", classname(self),
-                    id_, t_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
+                self.log.info("%s: Queuing thread %d at %s", classname(self),
+                id_, utc_post.strftime("%Y-%m-%d %H:%M:%S UTC"))
                 new_cmd = PostSuggestionThreadCommand(id_, t_post)
                 self.owner.queue_event(new_cmd)
         self.db.close()
     def run(self):
         reddit = self.res['reddit']
         db     = self.res['dbsession']
+
+        # target day configuration
         post_time = self._parse_datetime(
             time_str=self.res['config.minibot'].suggestions_time)
         post_day = self.res['config.minibot'].suggestions_day
-        # calculate some important times
+
+        # current date
         lo_dt_now = datetime.now()
-        delta_next = timedelta(days=(lo_dt_now.date().weekday() - post_day) % 7)
+        lo_today = lo_dt_now.weekday()
+
+        # calculate next thread's date + start/end times for that day
+        delta_next = timedelta(days=(post_day - lo_today) % 7)
         day_next = lo_dt_now.date() + delta_next
-        # start of the day for the next thread
         utc_dt_next = self._utctime(datetime.combine(day_next, dt_time(0,0,0)))
-        # end of the day for the next thread
         utc_dt_next_end = utc_dt_next + timedelta(days=1)
-        self.log.debug("%s: Checking %s to %s", classname(self),
-            utc_dt_next.strftime("%Y-%m-%d %H:%M:%S"),
-            utc_dt_next_end.strftime("%Y-%m-%d %H:%M:%S"))
 
         # find any thread on the next post date
+        self.log.debug("%s: Checking %s to %s", classname(self),
+            utc_dt_next.strftime("%Y-%m-%d %H:%M:%S UTC"),
+            utc_dt_next_end.strftime("%Y-%m-%d %H:%M:%S UTC"))
         num_threads = db.query(SuggestionThread).\
                     filter(SuggestionThread.time >= utc_dt_next).\
                     filter(SuggestionThread.time <  utc_dt_next_end).\
             utc_post_dt = self._utctime(datetime.combine(day_next, post_time))
             new_thread = SuggestionThread(utc_post_dt)
             db.add(new_thread)
-            self.log.info("%s: Added thread for %s to database", classname(self),
-            utc_post_dt.strftime("%Y-%m-%d %H:%M:%S"))
+            self.log.info("%s: Added thread for %s to database",
+            classname(self), utc_post_dt.strftime("%Y-%m-%d %H:%M:%S UTC"))
             self.log.debug("%s: %s", classname(self), repr(new_thread))
             db.commit()
         else: # if a thread is found on that day, no action to take
         return "<{cls}: post_id={id_}, post_time={time}>".format(
                 cls=classname(self),
                 id_=self.post_id,
-                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S'))
+                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S UTC'))
 
     def _get_title(self):
         """ Return the submission title for the prompt stored in
 
                 u"* A few words like \"a love affair\" isn't so much a "
                 u"specific _theme_ as it is just a vague subject. Try to avoid "
-                u"those—there are more interesting prompts to be found!\n\n"
+                u"those—there are more interesting prompts to be found!\n"
 
                 u"{text}"
 
         return "<{cls}: post_id={id_}, post_time={time}>".format(
                 cls=classname(self),
                 id_=self.post_id,
-                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S'))
+                time=self.post_time.strftime('%Y-%m-%d %H:%M:%S UTC'))
 
     def _get_title(self):
         """ Return the submission title for the thread stored in
     def _get_text(self):
         """ Return the submission text for the thread stored in
         ``self.thread``. """
-        prev_date_str = (self.post_time.date() - timedelta(days=7)).\
-                        strftime('%d %B %Y')
-        curr_date_str = self.post_time.date().strftime('%d %B %Y')
-        next_date_str = (self.post_time.date() + timedelta(days=7)).\
-                        strftime('%d %B %Y')
+        lo_post_date = self._localtime(self.post_time).date()
+        prev_date_str = (lo_post_date - timedelta(days=7)).strftime('%d %B %Y')
+        curr_date_str = lo_post_date.strftime('%d %B %Y')
+        next_date_str = (lo_post_date + timedelta(days=7)).strftime('%d %B %Y')
 
         if self.prev_thread is not None and\
                 self.prev_thread.r_post_id is not None:
         if thread:
             self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
                     classname(self), thread.id,
-                    self._localtime(thread.time).strftime("%Y-%m-%d %H:%M:%S"),
+                    thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                     get_reddit_url(thread.r_post_id, self.res['reddit']))
             self.prev_thread = thread
             return thread
         if thread:
             self.log.info("%s: Found previous suggestion thread %d (%s) <%s>",
                     classname(self), thread.id,
-                    self._localtime(thread.time).strftime("%Y-%m-%d %H:%M:%S"),
+                    thread.time.strftime("%Y-%m-%d %H:%M:%S UTC"),
                     get_reddit_url(thread.r_post_id, self.res['reddit']))
             self.prev_thread = thread
             return thread
             # the date fmt inside regex and strftime regex must correspond
             oldlink_re = re.compile(ur'\| \d{1,2} [A-Za-z][a-z]* \d{4} » \|')
 
-            date_str = self.post_time.date().strftime('%d %B %Y')
+            date_str = self._localtime(self.post_time).strftime('%d %B %Y')
             post_url = get_reddit_url(self.thread.r_post_id, self.res['reddit'])
             newlink = u' '.join([u'|', self.md_link(date_str, post_url), u'» |'])
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.