예제 #1
0
def validate_config():
    if 'config' not in request.form:
        return Response(response='There is no config to validate', status=400)
    
    # Preparing what will be returned:
    response = {
        'errors': [],
        'valid': True,
    }

    # Extract the config from the POST data and parse its JSON contents.
    # user_settings will be something like: {"name":"Alice", "lang":"english"}.
    user_settings = json.loads(request.form.get('config', {}))

    # If the user did not choose a language:
    if 'from_station' not in user_settings or user_settings['from_station'] == '':
        response['valid'] = False
        response['errors'].append('Kies een beginstation.')

    # If the user did not fill in the name option:
    if 'to_station' not in user_settings or user_settings['to_station'] == '':
        response['valid'] = False
        response['errors'].append('Kies een eindstation.')

    if 'time_slot_begin' not in user_settings or not valid_time(user_settings['time_slot_begin']):
        response['valid'] = False
        response['errors'].append('Kies een geldige begintijd in de vorm uu:mm.')

    if 'time_slot_end' not in user_settings or not valid_time(user_settings['time_slot_end']):
        response['valid'] = False
        response['errors'].append('Kies een geldige eindtijd in de vorm uu:mm.')

    if 'push_offset_minutes' not in user_settings or user_settings['push_offset_minutes'] == '':
        user_settings['push_offset_minutes'] = 0

    # check push specific settings
    if request.form.get('endpoint', '') == '':
        response['valid'] = False
        response['errors'].append('No Push endpoint was provided.')

    if request.form.get('subscription_id', '') == '':
        response['valid'] = False
        response['errors'].append('No Push subscription_id was provided.')

    if response['valid']:
        # Assuming the form validates, we store the endpoint, plus this user's
        # settings, keyed by their subscription_id.
        user_settings['endpoint'] = request.form.get('endpoint')
        db().hset('train_delays:subscriptions',
                    request.form.get('subscription_id'),
                    json.dumps(user_settings))

    return jsonify(**response)
예제 #2
0
def send_to_printer(subscription_id, delays, user_settings):
    content = render_template('edition.html', results=delays,
                              from_station=user_settings['from_station'],
                              to_station=user_settings['to_station'])

    # check if we have new content
    tag = '"%s"' % (
        hashlib.md5(
            content + dt.datetime.utcnow().strftime('%d%m%Y')
        ).hexdigest())


    stored_tag = db().hget('train_delays:content_tag', subscription_id)
    #print "stored: " + stored_content
    #print "content: " + content
    print "new content %s" % (stored_tag != tag)
    if not stored_tag or stored_tag != tag:
        db().hset('train_delays:content_tag', subscription_id, tag)
    elif stored_tag == tag:
        return

    print 'DO REQUEST'
    # Post this content to BERG Cloud using OAuth.
    response, data = client().request(
        user_settings['endpoint'],
        method='POST',
        body=content,
        headers={'Content-Type': 'text/html; charset=utf-8'})

    print 'RESPONSE STATUS: %d' % response.status
    if response.status == '410':
        # By sending a 410 status code, BERG Cloud has informed us this
        # user has unsubscribed. So delete their subscription from our
        # database.
        db().hdel('train_delays:subscriptions', subscription_id)
    else:
        pass
예제 #3
0
def push_post():
    subscribed_count = 0
    unsubscribed_count = 0

    for subscription_id, config in db().hgetall('train_delays:subscriptions').iteritems():
        # config contains the subscriber's language, name and endpoint.
        config = json.loads(config)

        # Get a random greeting in this subscriber's chosen language.
        #greeting = choice(app.config['GREETINGS'][ config['lang'] ])

        # Make the HTML content to push to the printer.
        content = render_template(
                                'edition.html')
                                #greeting="%s, %s" % (greeting, config['name']))

        # Post this content to BERG Cloud using OAuth.
        response, data = client().request(
                        config['endpoint'],
                        method='POST',
                        body=content,
                        headers={'Content-Type': 'text/html; charset=utf-8'})

        if response.status == '410':
            # By sending a 410 status code, BERG Cloud has informed us this
            # user has unsubscribed. So delete their subscription from our
            # database.
            db().hdel('push_example:subscriptions', subscription_id)
            unsubscribed_count += 1
        else:
            subscribed_count += 1

    # Show the same form again, with a message to confirm this worked.
    return render_template('push.html',
                            pushed=True,
                            subscribed_count=subscribed_count,
                            unsubscribed_count=unsubscribed_count)
예제 #4
0
def poll_api():
    with app.app_context():
        api = NSApi(app.config['NS_AUTH_STRING'])
        for subscription_id, config in db().hgetall('train_delays:api_queue').iteritems():
            user_settings = json.loads(config)

            today = dt.datetime.today()
            time_slot_begin = dt.datetime.combine(today, dt.datetime.strptime(user_settings['time_slot_begin'], '%H:%M').time())
            delays = api.get(user_settings['from_station'], user_settings['to_station'], time_slot_begin)
            time_slot_end = dt.datetime.combine(today, dt.datetime.strptime(user_settings['time_slot_end'], '%H:%M').time())

            # filter delays to match time frame
            delays = [d for d in delays if d['departure_actual'] <= time_slot_end.time()]
            if delays:
                send_to_printer(subscription_id, delays, user_settings)
예제 #5
0
def test():
    api = NSApi(app.config['NS_AUTH_STRING'])
    for subscription_id, config in db().hgetall('train_delays:api_queue').iteritems():
        user_settings = json.loads(config)
        today = datetime.today()
        time_slot_begin = datetime.combine(today, datetime.strptime(user_settings['time_slot_begin'], '%H:%M').time())
        delays = api.get(user_settings['from_station'], user_settings['to_station'], time_slot_begin)
        time_slot_end = datetime.combine(today, datetime.strptime(user_settings['time_slot_end'], '%H:%M').time())
        # filter delays to match time frame
        delays = [d for d in delays if d['departure_actual'] <= time_slot_end.time()]
        #if delays:
        print delays

        data = dict(results=delays, from_station=user_settings['from_station'], to_station=user_settings['to_station'])
        return render_edition(data)
예제 #6
0
def check_time_frames():
    with app.app_context():
        for subscription_id, config in db().hgetall('train_delays:subscriptions').iteritems():
            user_settings = json.loads(config)

            # create datetime objects
            now = dt.datetime.now().time()
            time_slot_begin = dt.datetime.strptime(user_settings['time_slot_begin'], '%H:%M').time()
            time_slot_end = dt.datetime.strptime(user_settings['time_slot_end'], '%H:%M').time()

            # check offset if we need to call api earlier
            minutes_delta = dt.timedelta(seconds=int(['push_offset_minutes']) * 60)
            offset_time = (dt.datetime.combine(dt.date(1,1,1), time_slot_begin) - minutes_delta).time()

            # within timeframe?
            if offset_time <= now <= time_slot_end:
                # exists already?
                if not db().hexists('train_delays:api_queue', subscription_id):
                    # add to api queue
                    db().hset('train_delays:api_queue', subscription_id, config)
            elif db().hexists('train_delays:api_queue', subscription_id):
                # otherwise delete
                db().hdel('train_delays:api_queue', subscription_id)