<reponame>dlzou/baby-interpreter<gh_stars>0
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

from flask import Flask, render_template, request
# from flask.ext.sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from forms import *
import os
import sys
from sys import stderr
import json
import threading
from exponent_server_sdk import PushClient
from exponent_server_sdk import PushMessage
from exponent_server_sdk import PushResponseError
from exponent_server_sdk import PushServerError
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from babyClass import loop

#----------------------------------------------------------------------------#
# Data
#----------------------------------------------------------------------------#
tokens = []
TEST_TOKEN = 'ExponentPushToken[<KEY>
EXTENSIONS = ['wav', 'mp3']
events = []

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
app.config.from_object('config')
#db = SQLAlchemy(app)

# Automatically tear down SQLAlchemy.
'''
@app.teardown_request
def shutdown_session(exception=None):
    db_session.remove()
'''

# Login required decorator.
'''
def login_required(test):
    @wraps(test)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return test(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap
'''

# Methods

# Basic arguments. You should extend this function with the push features you
# want to use, or simply pass in a `PushMessage` object.
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token,
                        body=message,
                        data=extra))
    except PushServerError as exc:
        # Encountered some likely formatting/validation error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'errors': exc.errors,
                'response_data': exc.response_data,
            })
        raise
    except (ConnectionError, HTTPError) as exc:
        # Encountered some Connection or HTTP error - retry a few times in
        # case it is transient.
        rollbar.report_exc_info(
            extra_data={'token': token, 'message': message, 'extra': extra})
        raise self.retry(exc=exc)

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        # Mark the push token as inactive
        from notifications.models import PushToken
        PushToken.objects.filter(token=token).update(active=False)
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'push_response': exc.push_response._asdict(),
            })
        raise self.retry(exc=exc)

def valid_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in EXTENSIONS
#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#

    
@app.route('/')
def home():
    return render_template('pages/placeholder.home.html')

@app.route('/getdata', methods=['GET'])
def getData():
    return json.dumps(events)

@app.route('/sendaudio', methods=['POST'])
def send_audio():
    print(request.files)
    f = request.files.get('file', None)
    if f and valid_file(f.filename):
        f.save('../classfier/sound-downloader/testing/recording.wav')
    return '''<h1>Audio sent</h1>'''

@app.route('/notify', methods=['POST'])
def notify():
    notify_type = request.json['type']
    print(notify_type, 'NOTIFIED', file=stderr)
    # if (len(tokens) > 0):
    send_push_message(TEST_TOKEN, notify_type)
    events.append(notify_type)
    # else:
    # print('Notification not sent: no token found', file=stderr)
        
    return '''<h1>notified {}</h1>'''.format(notify_type)

@app.route('/register', methods=['POST'])
def register():
    tokens.append(request.json['token']['value'])
    print(request.json['token']['value'], 'TOKEN RECEIVED', file=stderr)
    return '''<h1>token received. tokens now {}'''.format(tokens)

@app.route('/about')
def about():
    return render_template('pages/placeholder.about.html')
# Error handlers.


@app.errorhandler(500)
def internal_error(error):
    #db_session.rollback()
    return render_template('errors/500.html'), 500


@app.errorhandler(404)
def not_found_error(error):
    return render_template('errors/404.html'), 404

if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    threading.Thread(target=loop).start()
    app.run(host='bigrip.ocf.berkeley.edu')

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''

#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

from flask import Flask, render_template, request
# from flask.ext.sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from forms import *
import os
import sys
from sys import stderr
import json
import threading
from exponent_server_sdk import PushClient
from exponent_server_sdk import PushMessage
from exponent_server_sdk import PushResponseError
from exponent_server_sdk import PushServerError
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from babyClass import loop

#----------------------------------------------------------------------------#
# Data
#----------------------------------------------------------------------------#
tokens = []
TEST_TOKEN = 'ExponentPushToken[<KEY>
EXTENSIONS = ['wav', 'mp3']
events = []

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
app.config.from_object('config')
#db = SQLAlchemy(app)

# Automatically tear down SQLAlchemy.
'''
@app.teardown_request
def shutdown_session(exception=None):
    db_session.remove()
'''

# Login required decorator.
'''
def login_required(test):
    @wraps(test)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return test(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login'))
    return wrap
'''

# Methods

# Basic arguments. You should extend this function with the push features you
# want to use, or simply pass in a `PushMessage` object.
def send_push_message(token, message, extra=None):
    try:
        response = PushClient().publish(
            PushMessage(to=token,
                        body=message,
                        data=extra))
    except PushServerError as exc:
        # Encountered some likely formatting/validation error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'errors': exc.errors,
                'response_data': exc.response_data,
            })
        raise
    except (ConnectionError, HTTPError) as exc:
        # Encountered some Connection or HTTP error - retry a few times in
        # case it is transient.
        rollbar.report_exc_info(
            extra_data={'token': token, 'message': message, 'extra': extra})
        raise self.retry(exc=exc)

    try:
        # We got a response back, but we don't know whether it's an error yet.
        # This call raises errors so we can handle them with normal exception
        # flows.
        response.validate_response()
    except DeviceNotRegisteredError:
        # Mark the push token as inactive
        from notifications.models import PushToken
        PushToken.objects.filter(token=token).update(active=False)
    except PushResponseError as exc:
        # Encountered some other per-notification error.
        rollbar.report_exc_info(
            extra_data={
                'token': token,
                'message': message,
                'extra': extra,
                'push_response': exc.push_response._asdict(),
            })
        raise self.retry(exc=exc)

def valid_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in EXTENSIONS
#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#

    
@app.route('/')
def home():
    return render_template('pages/placeholder.home.html')

@app.route('/getdata', methods=['GET'])
def getData():
    return json.dumps(events)

@app.route('/sendaudio', methods=['POST'])
def send_audio():
    print(request.files)
    f = request.files.get('file', None)
    if f and valid_file(f.filename):
        f.save('../classfier/sound-downloader/testing/recording.wav')
    return '''<h1>Audio sent</h1>'''

@app.route('/notify', methods=['POST'])
def notify():
    notify_type = request.json['type']
    print(notify_type, 'NOTIFIED', file=stderr)
    # if (len(tokens) > 0):
    send_push_message(TEST_TOKEN, notify_type)
    events.append(notify_type)
    # else:
    # print('Notification not sent: no token found', file=stderr)
        
    return '''<h1>notified {}</h1>'''.format(notify_type)

@app.route('/register', methods=['POST'])
def register():
    tokens.append(request.json['token']['value'])
    print(request.json['token']['value'], 'TOKEN RECEIVED', file=stderr)
    return '''<h1>token received. tokens now {}'''.format(tokens)

@app.route('/about')
def about():
    return render_template('pages/placeholder.about.html')
# Error handlers.


@app.errorhandler(500)
def internal_error(error):
    #db_session.rollback()
    return render_template('errors/500.html'), 500


@app.errorhandler(404)
def not_found_error(error):
    return render_template('errors/404.html'), 404

if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    threading.Thread(target=loop).start()
    app.run(host='bigrip.ocf.berkeley.edu')

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''
#----------------------------------------------------------------------------# # Imports #----------------------------------------------------------------------------# # from flask.ext.sqlalchemy import SQLAlchemy #----------------------------------------------------------------------------# # Data #----------------------------------------------------------------------------# #----------------------------------------------------------------------------# # App Config. #----------------------------------------------------------------------------# #db = SQLAlchemy(app) # Automatically tear down SQLAlchemy. @app.teardown_request def shutdown_session(exception=None):     db_session.remove() # Login required decorator. def login_required(test):     @wraps(test)     def wrap(*args, **kwargs):         if 'logged_in' in session:             return test(*args, **kwargs)         else:             flash('You need to login first.')             return redirect(url_for('login'))     return wrap # Methods # Basic arguments. You should extend this function with the push features you # want to use, or simply pass in a `PushMessage` object. # Encountered some likely formatting/validation error. # Encountered some Connection or HTTP error - retry a few times in # case it is transient. # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. # Mark the push token as inactive # Encountered some other per-notification error. #----------------------------------------------------------------------------# # Controllers. #----------------------------------------------------------------------------# <h1>Audio sent</h1> # if (len(tokens) > 0): # else: # print('Notification not sent: no token found', file=stderr) <h1>notified {}</h1> <h1>token received. tokens now {} # Error handlers. #db_session.rollback() #----------------------------------------------------------------------------# # Launch. #----------------------------------------------------------------------------# # Default port: # Or specify port manually: if __name__ == '__main__':     port = int(os.environ.get('PORT', 5000))     app.run(host='0.0.0.0', port=port)