Beispiel #1
0
def dashboard():
    ''' Codigo que maneja el dashboard de la aplicacion. '''

    createDB()
    products = queryDB('SELECT id, name FROM products;')

    kwargs = {}
    kwargs['title'] = PAGE_DASHBOARD[1]
    kwargs['serverAddr'] = CONFIG['NC_ADDRESS']
    kwargs['serverPort'] = CONFIG['SERVER_PORT']
    kwargs['products'] = products
    kwargs['selected_product'] = CONFIG['CURRENT_PRODUCT']

    if request.method == 'POST':

        currentProduct = int(request.form['currentProduct'])
        min_weight, max_weight = queryDB(
            'SELECT min_weight, max_weight FROM products WHERE id = ?',
            (currentProduct, ),
            one=True)

        if app.mutex.acquire(False):
            CONFIG['CURRENT_PRODUCT'] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs['selected_product'] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash('Se cambio el producto actual!')
            app.mutex.release()
        else:
            flash(u'Dispositivo ocupado, alguien más intenta actualizarlo!')

    destroyDB()

    return render_template('dashboard.html', **kwargs)
Beispiel #2
0
def dashboard():
    """ Codigo que maneja el dashboard de la aplicacion. """

    createDB()
    products = queryDB("SELECT id, name FROM products;")

    kwargs = {}
    kwargs["title"] = PAGE_DASHBOARD[1]
    kwargs["serverAddr"] = CONFIG["NC_ADDRESS"]
    kwargs["serverPort"] = CONFIG["SERVER_PORT"]
    kwargs["products"] = products
    kwargs["selected_product"] = CONFIG["CURRENT_PRODUCT"]

    if request.method == "POST":

        currentProduct = int(request.form["currentProduct"])
        min_weight, max_weight = queryDB(
            "SELECT min_weight, max_weight FROM products WHERE id = ?", (currentProduct,), one=True
        )

        if app.mutex.acquire(False):
            CONFIG["CURRENT_PRODUCT"] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs["selected_product"] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash("Se cambio el producto actual!")
            app.mutex.release()
        else:
            flash(u"Dispositivo ocupado, alguien más intenta actualizarlo!")

    destroyDB()

    return render_template("dashboard.html", **kwargs)
def oauth2callback():
    flow = client.flow_from_clientsecrets(
        'client_secrets.json',
        scope='https://www.googleapis.com/auth/calendar',
        redirect_uri=URL + 'oauth2callback')
    flow.params['approval_prompt'] = 'force'
    flow.params['access_type'] = 'offline'
    if 'code' not in flask.request.args:
        auth_uri = flow.step1_get_authorize_url()
        return flask.redirect(auth_uri)
    else:
        auth_code = flask.request.args.get('code')
        credentials = flow.step2_exchange(auth_code)
        flask.session['credentials'] = credentials.to_json()
        cur_cred = json.loads(flask.session['credentials'])
        refresh_token = cur_cred['refresh_token']
        cur_token = cur_cred['access_token']
    if refresh_token == None:
        flask.session.pop('credentials', None)
        bot.send_text_message(flask.session['user_id'],
                              "Suis désolé - do you mind logging in again?")
        return flask.redirect(
            flask.url_for('login?user_id=' + flask.session['user_id']))
    else:
        bot.send_text_message(
            flask.session['user_id'],
            "Google calendar successfully setup - we're good to go woot! :D ")
        queryDB('google_token_enter', [
            flask.session['user_id'],
            str(cur_token) + '||' + str(refresh_token)
        ])
        return flask.redirect(flask.url_for('calendar_connect_done'))
def login():
    user_id = request.args.get('user_id')
    flask.session['user_id'] = user_id
    if 'credentials' not in flask.session:
        return flask.redirect(flask.url_for('oauth2callback'))
    else:
        credentials = None
        try:
            credentials = client.OAuth2Credentials.from_json(
                flask.session['credentials'])
        except:
            return flask.redirect(flask.url_for('oauth2callback'))
        if credentials.access_token_expired:
            return flask.redirect(flask.url_for('oauth2callback'))
        else:
            cur_cred = json.loads(flask.session['credentials'])
            print(cur_cred)
            refresh_token = cur_cred['refresh_token']
            cur_token = cur_cred['access_token']
            if refresh_token == None:
                print(str(cur_token))
            else:
                queryDB('google_token_enter', [
                    flask.session['user_id'],
                    str(cur_token) + '||' + str(refresh_token)
                ])
                bot.send_text_message(
                    flask.session['user_id'],
                    "Google calendar successfully setup - we're good to go woot! :D "
                )
    return flask.redirect(flask.url_for('calendar_connect_done'))
Beispiel #5
0
def welcome():
    if request.method == 'GET':
        try:
            if request.args['hub.verify_token'] == VALIDATION_TOKEN:
                return request.args['hub.challenge'], 200
            else:
                return 'Error - invalid token supplied', 403
        except:
            return 'Hey there! How about you try message me from Facebook Messenger?', 200

    elif request.method == 'POST':
        data = request.json
        messages = data['entry'][0]['messaging']
        print(messages)
        for msg in messages:
            if (msg.get('message') and msg['message'].get('text') and not 'is_echo' in msg['message'] and not 'delivery' in msg):
                if not 'quick_reply' in msg['message'] and not 'attachments' in msg['message']:
                    message = msg['message']['text']
                    user_id = msg['sender']['id']
                    #state_info.set_user(user_id)
                    print(message)
                    bot.send_mark_seen(user_id)
                    bot.send_typing(user_id, True)
                    if (message[0] == '/'):
                        message = message[1:].lower()
                        if (message in COMMANDS):
                            if message == "clear":
                                queryDB("del_user", user_id)
                                bot.send_text_message(user_id, "Your ID " + user_id + " has been removed from the database.")
                            elif message == "howdy":
                                bot.send_text_message(user_id, "Howdy fella")
                            elif message == "waddup":
                                bot.send_text_message(user_id, "it's ya boi")
                        else:
                            bot.send_text_message(user_id, "Command not recognised :( ")
                    else:
                        # login on our server and on google
                        #jacqueslog(user_id, bot)

                        # call NLP and state machine
                        #flow(message)
                        pass
                    bot.send_typing(user_id, False)
                else:
                    #Handle custom reply
                    if 'quick_reply' in msg['message']:
                        payload = msg['message']['quick_reply']['payload']
                        print(payload)
                        #Quick replies
                    elif 'attachments' in msg['message']:
                        if  msg['message']['attachments']['type'] == 'location':
                            payload = msg['message']['attachments']['payload']['coordinates']
                            latitude = payload['lat']
                            longitude = payload['long']
                            #Location
            else:
                pass
    return 'Success!', 200
Beispiel #6
0
def products(page):
    """ Codigo que maneja el listado de productos de la aplicacion. """

    createDB()
    count = queryDB("SELECT count(*) from products;", one=True)[0]

    kwargs = {}

    minID = (page - 1) * CONFIG["PRODUCTS_PER_PAGE"] + 1
    maxID = page * CONFIG["PRODUCTS_PER_PAGE"]
    kwargs["products"] = queryDB("SELECT id, name FROM products WHERE id >= ? and id <= ?", (str(minID), str(maxID)))
    destroyDB()

    if not kwargs["products"] and page != 1:
        abort(404)

    kwargs["page"] = page
    kwargs["pagination"] = Pagination(page, CONFIG["PRODUCTS_PER_PAGE"], count)
    kwargs["title"] = PAGE_PRODUCTS[1]

    return render_template("products.html", **kwargs)
Beispiel #7
0
def jacqueslog(user_id, bot):
    if (queryDB('new_user_check', user_id) == False):
        bot.send_text_message(user_id, "Hey there " + user_id + " It's looking like this is your first message!")
        queryDB('add_user', user_id)
    else:
        bot.send_text_message(user_id, "Welcome back " + user_id + "!")

    if (queryDB('google_cal_check', user_id) == False):
        # edit the url below to be blackbox.../login flow
        # define the function in another flask file
        # this can redirect to google cloud login api
        # oauth callback on google logs you in, allows the blackbox app to use the calendar
        oauth_request_button = [
            {
                "type": "web_url",
                "url": URL + "login?user_id=" + str(user_id),
                "title": "Connect?",
                "webview_height_ratio": "compact"
            }
        ]
        bot.send_button_message(user_id, "How about you connect your Google Calendar? :)",
                                oauth_request_button)
Beispiel #8
0
def products(page):
    ''' Codigo que maneja el listado de productos de la aplicacion. '''

    createDB()
    count = queryDB('SELECT count(*) from products;', one=True)[0]

    kwargs = {}

    minID = (page - 1) * CONFIG['PRODUCTS_PER_PAGE'] + 1
    maxID = page * CONFIG['PRODUCTS_PER_PAGE']
    kwargs['products'] = queryDB(
        'SELECT id, name FROM products WHERE id >= ? and id <= ?',
        (str(minID), str(maxID)))
    destroyDB()

    if not kwargs['products'] and page != 1:
        abort(404)

    kwargs['page'] = page
    kwargs['pagination'] = Pagination(page, CONFIG['PRODUCTS_PER_PAGE'], count)
    kwargs['title'] = PAGE_PRODUCTS[1]

    return render_template('products.html', **kwargs)
Beispiel #9
0
def doGet(entity, request_args, role="default"):
    result = {}

    entityDict = entityMap.get(entity)

    if entityDict is not None:
        select_statement = __construct_select(request_args,
                                              entityDict["tableName"],
                                              entityDict["formatter"])
        result[entityDict["entityPlural"]] = queryDB(select_statement, role)
        # result[entityDict["entityPlural"]] = reverseFormatJSON(
        #     queryDB(select_statement, role))
    else:
        result["error"] = "Unknown entity"

    return result
Beispiel #10
0
def con_set_date(state_info):
    state_info.bot.send_text_message(
        state_info.user.get_user(),
        "I'm adding the event to your Google calendar! Have fun ;)")
    return 'start_no_name'
    # event = state_info.recommended_event
    # print(event)
    # # event[0] - name
    # # event[1] - URL
    # # event[2] - venue
    # # event[3] - time and date
    # ev = {
    #     'summary': event[0],
    #     'location': event[2],
    #     'description': event[1],
    #     'start':
    #         {
    #         'dateTime': (event[3]),
    #         'timeZone': 'America/New_York',
    #         },
    #     'end':
    #         {
    #         #'dateTime': '2015-05-28T17:00:00-07:00',
    #         #'timeZone': 'America/New_York',
    #         },
    #     'reminders':
    #         {
    #         'useDefault': False,
    #         'overrides':
    #             [
    #               {'method': 'email', 'minutes': 24 * 60},
    #               {'method': 'popup', 'minutes': 10},
    #             ],
    #         },
    # }
    credentials = queryDB('google_cal_check', state_info.user.get_user())
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)
    ev = service.events().insert(calendarId='primary', body=ev).execute()
    print('Event created: %s' % (ev.get('htmlLink')))
Beispiel #11
0
def product(id=None):
    """ Codigo que maneja un producto. """

    createDB()

    kwargs = {}
    kwargs["product"] = (None, "", "", "")
    kwargs["measurements"] = []
    kwargs["title"] = "Crear producto"
    kwargs["mode"] = "insert"
    kwargs["serverAddr"] = CONFIG["NC_ADDRESS"]
    kwargs["serverPort"] = CONFIG["SERVER_PORT"]

    if id is not None:
        kwargs["mode"] = "update"
        if request.method == "GET":
            product = queryDB("SELECT * FROM products WHERE id = ?;", (id,))
            if product:
                kwargs["product"] = product[0]
                measurements = queryDB("SELECT * FROM measurements WHERE product_id = ? LIMIT 25;", (id,))
                kwargs["measurements"] = measurements
                kwargs["title"] = product[0][1]
            else:
                abort(404)
        else:
            # Leemos el formulario y actualizamos.
            name = request.form["name"]
            minWeight = request.form["minWeight"]
            maxWeight = request.form["maxWeight"]
            if isFloat(minWeight) and isFloat(maxWeight) and float(minWeight) < float(maxWeight) and len(name) > 0:
                alterDB(
                    "UPDATE products SET name = ?, min_weight = ?, max_weight = ? WHERE id = ?;",
                    (name, minWeight, maxWeight, id),
                )
                flash("Producto actualizado!")
            else:
                flash("Datos invalidos!")

            kwargs["product"] = (id, name, minWeight, maxWeight)
            kwargs["title"] = name
            kwargs["mode"] = "update"
            measurements = queryDB("SELECT * FROM measurements WHERE product_id = ? LIMIT 25;", (id,))
            kwargs["measurements"] = measurements
    else:
        if request.method == "POST":
            # Creamos el producto.
            name = request.form["name"]
            minWeight = request.form["minWeight"]
            maxWeight = request.form["maxWeight"]
            if isFloat(minWeight) and isFloat(maxWeight) and float(minWeight) < float(maxWeight) and len(name) > 0:
                id = alterDB(
                    "INSERT INTO products(name, min_weight, max_weight) VALUES (?,?,?);", (name, minWeight, maxWeight)
                )
                flash("Producto creado!")
                return redirect(url_for("products"))
            else:
                flash("Datos invalidos!")
                kwargs["product"] = (None, name, minWeight, maxWeight)

    destroyDB()

    return render_template("product.html", **kwargs)
Beispiel #12
0
def product(id=None):
    ''' Codigo que maneja un producto. '''

    createDB()

    kwargs = {}
    kwargs['product'] = (None, '', '', '')
    kwargs['measurements'] = []
    kwargs['title'] = 'Crear producto'
    kwargs['mode'] = 'insert'
    kwargs['serverAddr'] = CONFIG['NC_ADDRESS']
    kwargs['serverPort'] = CONFIG['SERVER_PORT']

    if (id is not None):
        kwargs['mode'] = 'update'
        if request.method == 'GET':
            product = queryDB('SELECT * FROM products WHERE id = ?;', (id, ))
            if product:
                kwargs['product'] = product[0]
                measurements = queryDB(
                    'SELECT * FROM measurements WHERE product_id = ? LIMIT 25;',
                    (id, ))
                kwargs['measurements'] = measurements
                kwargs['title'] = product[0][1]
            else:
                abort(404)
        else:
            # Leemos el formulario y actualizamos.
            name = request.form['name']
            minWeight = request.form['minWeight']
            maxWeight = request.form['maxWeight']
            if isFloat(minWeight) and isFloat(maxWeight) and float(
                    minWeight) < float(maxWeight) and len(name) > 0:
                alterDB(
                    'UPDATE products SET name = ?, min_weight = ?, max_weight = ? WHERE id = ?;',
                    (name, minWeight, maxWeight, id))
                flash('Producto actualizado!')
            else:
                flash('Datos invalidos!')

            kwargs['product'] = (id, name, minWeight, maxWeight)
            kwargs['title'] = name
            kwargs['mode'] = 'update'
            measurements = queryDB(
                'SELECT * FROM measurements WHERE product_id = ? LIMIT 25;',
                (id, ))
            kwargs['measurements'] = measurements
    else:
        if request.method == 'POST':
            # Creamos el producto.
            name = request.form['name']
            minWeight = request.form['minWeight']
            maxWeight = request.form['maxWeight']
            if isFloat(minWeight) and isFloat(maxWeight) and float(
                    minWeight) < float(maxWeight) and len(name) > 0:
                id = alterDB(
                    'INSERT INTO products(name, min_weight, max_weight) VALUES (?,?,?);',
                    (name, minWeight, maxWeight))
                flash('Producto creado!')
                return redirect(url_for('products'))
            else:
                flash('Datos invalidos!')
                kwargs['product'] = (None, name, minWeight, maxWeight)

    destroyDB()

    return render_template('product.html', **kwargs)
def welcome():
    if request.method == 'GET':
        try:
            if request.args['hub.verify_token'] == VALIDATION_TOKEN:
                return request.args['hub.challenge'], 200
            else:
                return 'Error - invalid token supplied', 403
        except:
            return 'Hey there! How about you try message me from Facebook Messenger?', 200

    elif request.method == 'POST':
        data = request.json
        messages = data['entry'][0]['messaging']
        for msg in messages:
            if (msg.get('message') and msg['message'].get('text')
                    and not 'is_echo' in msg['message']
                    and not 'delivery' in msg):
                if not 'quick_reply' in msg[
                        'message'] and not 'attachments' in msg['message']:
                    message = msg['message']['text']
                    user_id = msg['sender']['id']
                    state_info.set_user(user_id)
                    print(message)
                    bot.send_mark_seen(user_id)
                    bot.send_typing(user_id, True)
                    if (message[0] == '/'):
                        message = message[1:].lower()
                        if (message in COMMANDS):
                            if message == "clear":
                                queryDB("del_user", user_id)
                                bot.send_text_message(
                                    user_id, "Your ID " + user_id +
                                    " has been removed from the database.")
                            elif message == "howdy":
                                bot.send_text_message(user_id, "Howdy fella")
                            elif message == "waddup":
                                bot.send_text_message(user_id, "it's ya boi")
                            elif message == "neg":
                                bot.send_text_message(
                                    user_id,
                                    "You look like you're going to spend your life having one epiphany after another, always thinking you've finally figured out what's holding you back, and how you can finally be productive and creative and turn your life around. But nothing will ever change. That cycle of mediocrity isn't due to some obstacle. It's who you are. The thing standing in the way of your dreams is; that the person having them is you."
                                )

                        else:
                            bot.send_text_message(
                                user_id, "Command not recognised :( ")
                    else:
                        if (queryDB('new_user_check', user_id) == False):
                            bot.send_text_message(
                                user_id, "Hey there " + user_id +
                                " It's looking like this is your first message!"
                            )
                            queryDB('add_user', user_id)
                            if queryDB('get_user_name', user_id) == False:
                                bot.send_text_message(
                                    user_id,
                                    "Hmm, I'm not a fan of calling you by your ID. How about you give me a proper name?"
                                )
                        else:
                            set = False
                            if queryDB('get_user_name',
                                       user_id) == '_is_updating_':
                                queryDB('set_user_name', [user_id, message])
                                bot.send_text_message(
                                    user_id, 'Great, I\'ll call you ' +
                                    message + ' from now on!')
                                set = True
                            name = queryDB('get_user_name', user_id)
                            if (message.lower() in GREETINGS):
                                if set == False:
                                    bot.send_text_message(
                                        user_id, "Hey there " + name)
                            else:
                                # login on our server and on google
                                jacqueslog(user_id, bot)
                                # call NLP and state machine

                                try:
                                    flow(message)
                                    pass
                                except Exception as e:
                                    print(e)
                                    print('DEBUG')
                    bot.send_typing(user_id, False)
                else:
                    #Handle custom reply
                    if 'quick_reply' in msg['message']:
                        payload = msg['message']['quick_reply']['payload']
                        print(payload)
                        #Quick replies
                        flow_hack(payload)
                    elif 'attachments' in msg['message']:
                        if msg['message']['attachments']['type'] == 'location':
                            payload = msg['message']['attachments']['payload'][
                                'coordinates']
                            latitude = payload['lat']
                            longitude = payload['long']
                            #Location
            else:
                pass
    return 'Success!', 200