Example #1
0
 def check_twitter(self, diff, launch):
     if launch.last_twitter_post is not None:
         time_since_last_twitter_update = (
             datetime.datetime.utcnow() -
             datetime.datetime.utcfromtimestamp(
                 int(launch.last_twitter_post))).total_seconds()
         log(
             TAG, 'Seconds since last update on Twitter %d for %s' %
             (time_since_last_twitter_update, launch.launch_name))
         if diff < 86400:
             if diff > 3600:
                 if time_since_last_twitter_update > 43200:
                     self.send_to_twitter(
                         '%s launching from %s in %s' %
                         (launch.launch_name, launch.location['name'],
                          seconds_to_time(diff)), launch)
             if diff < 3600:
                 if time_since_last_twitter_update > 3600:
                     self.send_to_twitter(
                         '%s launching from %s in %s' %
                         (launch.launch_name, launch.location['name'],
                          seconds_to_time(diff)), launch)
     else:
         log(TAG, '%s has not been posted to Twitter.' % launch.launch_name)
         self.send_to_twitter(
             '%s launching from %s in %s' %
             (launch.launch_name, launch.location['name'],
              seconds_to_time(diff)), launch)
Example #2
0
    def send_notification(self, launch):
        self.onesignal.user_auth_key = self.app_auth_key
        self.onesignal.app_id = APP_ID
        log(TAG, 'Creating notification for %s' % launch.launch_name)

        # Create a notification
        contents = '%s launching from %s' % (launch.launch_name,
                                             launch.location['name'])
        kwargs = dict(content_available=True,
                      included_segments=['Debug'],
                      isAndroid=True,
                      data={"silent": True})
        url = 'https://launchlibrary.net'
        heading = 'Space Launch Now'
        response = self.onesignal.create_notification(contents, heading, url,
                                                      **kwargs)
        assert response.status_code == 200

        notification_data = response.json()
        notification_id = notification_data['id']
        assert notification_data['id'] and notification_data['recipients']

        # Get the notification
        response = self.onesignal.get_notification(APP_ID, notification_id,
                                                   self.app_auth_key)
        notification_data = response.json()
        assert notification_data['id'] == notification_id
        assert notification_data['contents']['en'] == contents
    def create_notification(self,
                            contents=None,
                            heading='',
                            url='',
                            included_segments=('All', ),
                            app_id=None,
                            player_ids=None,
                            **kwargs):
        """
        Creates a notification by sending a notification to https://onesignal.com/api/v1/notifications
        :param heading: push notification heading / title
        :param url: target url for push notification. User will be redirected to this url on clicking
        push notification
        :param app_id: App's ID
        :param contents: Contents of the message
        :param player_ids: list of player_ids to whom we specifically want to send notifications
        :param included_segments: segments to be included to send push notification
        :param kwargs: There can be more arguments as given on
        https://documentation.onesignal.com/docs/notifications-create-notification
        :return: Returns a HTTP response object which, per docs, will contain response like:

        .. Response::

            {
                  "id": "458dcec4-cf53-11e3-add2-000c2940e62c",
                  "recipients": 5
            }
        """
        app_id = app_id if app_id else self.app_id
        assert app_id
        data = {"app_id": app_id}
        if isinstance(contents, dict):
            data['contents'] = contents
        elif contents:
            data['contents'] = {'en': contents}
        if url and is_valid_url(url):
            data['url'] = url
        if isinstance(heading, dict):
            data['headings'] = heading
        else:
            data['headings'] = {'en': heading}

        if player_ids and isinstance(player_ids, (list, tuple)):
            data['include_player_ids'] = player_ids
        elif isinstance(included_segments,
                        (list, tuple)) and len(included_segments):
            data['included_segments'] = included_segments

        if kwargs:
            data.update(kwargs)

        api_url = self.api_url + "/notifications"
        data = json.dumps(data)
        log("OneSignal SDK", 'URL: %s' % api_url)
        log("OneSignal SDK", 'DATA: %s' % data)
        return send_request(api_url,
                            method='POST',
                            headers=self.get_headers(),
                            data=data)
 def send_twitter_update(self, message):
     try:
         if len(message) > 120:
             end = message[-5:]
             if re.search("([1-9]*/[1-9])", end):
                 message = (message[:111] + '... ' + end)
             else:
                 message = (message[:117] + '...')
         log(TAG, message + " | " + str(len(message)))
         self.twitter.statuses.update(status=message)
     except TwitterHTTPError as e:
         log_error(TAG, str(e) + " - " + message)
Example #5
0
 def run(self):
     """The daemon's main loop for doing work"""
     self.check_next_launch()
     if self.time_to_next_launch > 600:
         log(
             TAG, 'Next launch %s in %i hours, sleeping for %d seconds.' %
             (self.next_launch.launch_name, self.time_to_next_launch / 3600,
              DAEMON_SLEEP))
         self.scheduler.add_job(self.run,
                                'date',
                                run_date=datetime.datetime.now() +
                                datetime.timedelta(seconds=DAEMON_SLEEP))
     elif self.time_to_next_launch is not None and self.time_to_next_launch > 0:
         log(
             TAG, 'Next launch %s is imminent, sleeping for %d seconds.' %
             (self.time_to_next_launch / 3600, self.time_to_next_launch))
         self.scheduler.add_job(
             self.run,
             'date',
             run_date=datetime.datetime.now() +
             datetime.timedelta(seconds=self.time_to_next_launch))
     else:
         log(TAG, 'Sleeping for %d seconds.' % DAEMON_SLEEP)
         self.scheduler.add_job(self.run,
                                'date',
                                run_date=datetime.datetime.now() +
                                datetime.timedelta(seconds=DAEMON_SLEEP))
 def send_daily_to_twitter(self, launches):
     log(TAG, "Size %s" % launches)
     header = "Daily Digest %s:" % time.strftime("%-m/%d")
     if len(launches) == 0:
         message = "%s There are currently no launches confirmed Go for Launch within the next 24 hours." % header
         self.send_twitter_update(message)
     if len(launches) == 1:
         launch = launches[0]
         current_time = datetime.datetime.utcnow()
         launch_time = datetime.datetime.utcfromtimestamp(
             int(launch.net_stamp))
         message = "%s %s launching from %s in %s hours." % (
             header, launch.launch_name, launch.location['name'],
             '{0:g}'.format(
                 float(
                     round(
                         abs(launch_time - current_time).total_seconds() /
                         3600.0))))
         self.send_twitter_update(message)
     if len(launches) > 1:
         message = "%s There are %i confirmed launches within the next 24 hours...(1/%i)" % (
             header, len(launches), len(launches) + 1)
         self.send_twitter_update(message)
         for index, launch in enumerate(launches, start=1):
             current_time = datetime.datetime.utcnow()
             launch_time = datetime.datetime.utcfromtimestamp(
                 int(launch.net_stamp))
             message = "%s launching from %s in %s hours. (%i/%i)" % (
                 launch.launch_name, launch.location['name'],
                 '{0:g}'.format(
                     float(
                         round(
                             abs(launch_time -
                                 current_time).total_seconds() / 3600.0))),
                 index + 1, len(launches) + 1)
             self.send_twitter_update(message)
Example #7
0
 def check_next_launch(self):
     response = self.launchLibrary.get_next_launches()
     launch_data = response.json()
     if response.status_code is 200:
         log(TAG, "Found %i launches." % len(launch_data["launches"]))
         for launches in launch_data["launches"]:
             launch = Launch(launches)
             log(TAG, launch.launch_name)
             if launch.net_stamp > 0:
                 current_time = datetime.datetime.utcnow()
                 launch_time = datetime.datetime.utcfromtimestamp(
                     int(launch.net_stamp))
                 if current_time <= launch_time:
                     diff = int(
                         (launch_time - current_time).total_seconds())
                     if self.time_to_next_launch is None:
                         self.time_to_next_launch = diff
                         self.next_launch = launch
                     elif diff < self.time_to_next_launch:
                         self.time_to_next_launch = diff
                         self.next_launch = launch
                     self.check_launch_window(diff, launch)
     else:
         log(TAG, response)
import time

from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from apscheduler.schedulers.background import BackgroundScheduler

import Notifications
from DailyDigest import run_daily, run_weekly
from utils.util import log

TAG = 'Space Launch Now'

if __name__ == '__main__':
    log(TAG, "Initializing server...")
    scheduler = BackgroundScheduler()
    scheduler.start()
    log(TAG, "Created background scheduler.")
    scheduler.add_job(run_daily,
                      trigger='cron',
                      day_of_week='mon-sun',
                      hour=10,
                      minute=30)
    scheduler.add_job(run_weekly,
                      trigger='cron',
                      day_of_week='fri',
                      hour=12,
                      minute=30)
    log(TAG, "Added cronjobs to background scheduler.")
    Notifications.NotificationServer(scheduler).run()
    log(TAG, "Notification Server started.")
    try:
        while True:
Example #9
0
 def send_to_twitter(self, message, launch):
     self.twitter.statuses.update(status=message)
     log(TAG, message)
     self.launch_table.update({'last_twitter_update': time.time()},
                              Query().launch == launch.launch_id)
 def check_launch_weekly(self):
     launch_data = self.launchLibrary.get_next_launches().json()['launches']
     log(TAG, launch_data)
def run_weekly():
    log(TAG, 'Running Daily Digest - Weekly...')
    daily_digest = DailyDigestServer()
    daily_digest.run(weekly=True)