예제 #1
0
def handleCommunicationCommand(cmd, cargs):
    """Handles all user communication commands

    Keyword arguments:
    cmd -- the command to be executed (say, tell, yell)
    cargs -- The arguments for the command
    Returns: JSON - A status after executing the command
    """
    if cmd == "tell":  #Send message to a specific user
        if len(cargs) < 3:
            return jsonify(status="Command Not Found")
        user = cargs[1]
        msg = " ".join(cargs[2:])
        usersInRoom = getUsersInRoom()
        if user in usersInRoom:  #Check if the target user is in the same room (a user might leave the room at anytime)
            userRef = db.collection(u'users').document(user)
            userRef.update({
                "messages":
                ArrayUnion([{
                    'from': session.get('user_id').decode('utf-8'),
                    'msg': msg,
                    'type': u'tell'
                }])
            })
            return jsonify(status="success", roomInfo={'text': 'message sent'})
        else:
            return jsonify(status="User Not Visible")
    elif cmd == "yell":  #Send message to all the users in the world
        if len(cargs) < 2:
            return jsonify(status="Command Not Found")
        msg = " ".join(cargs[1:])
        allUsers = db.collection(u'users').get()
        for user in allUsers:
            user_id = user.id
            userRef = db.collection(u'users').document(user_id)
            userRef.update({
                "messages":
                ArrayUnion([{
                    'from': session.get('user_id').decode('utf-8'),
                    'msg': msg,
                    'type': u'yell'
                }])
            })
        return jsonify(status="success", roomInfo={'text': 'message sent'})
    elif cmd == "say":  #Send message to all the users in the room
        if len(cargs) < 2:
            return jsonify(status="Command Not Found")
        msg = " ".join(cargs[1:])
        usersInRoom = getUsersInRoom()
        for user in usersInRoom:
            userRef = db.collection(u'users').document(user)
            userRef.update({
                "messages":
                ArrayUnion([{
                    'from': session.get('user_id').decode('utf-8'),
                    'msg': msg,
                    'type': u'say'
                }])
            })
        return jsonify(status="success", roomInfo={'text': 'message sent'})
예제 #2
0
def setUserToRoom():
    """Sets the user to the current location in the firebase map
    This helps in determining the list of users in a particular location
    """
    userLocation = session.get("user_location")
    uid = session.get("user_id")
    worldRef = db.collection(u'world').document(session.get("world_id"))
    worldRef.update(
        {userLocation.decode('utf-8'): ArrayUnion([uid.decode('utf-8')])})
    return "done"
예제 #3
0
 def post(self, request):
     if request.POST['type'] == 'P':
         photos = request.POST['path']
         photos = photos.split(',')
         ref = db.collection('stfq').document('page')
         ref.update({"image": ArrayUnion(photos)})
     elif request.POST['type'] == 'V':
         video = request.POST['path']
         title = request.POST['title']
         data = {'link': video, 'title': title, 'status': True}
         ref = db.collection('stfq').document('page').collection(
             'video').document()
         ref.set(data)
     return HttpResponse('OK')
예제 #4
0
def update_user(data, user_id):
    try:
        user_ref = db.collection('users').document(user_id)
    except google.cloud.exceptions.NotFound:
        return Response('failed', 'User does not exist!', 401)

    if 'transaction' in data:
        transaction = data['transaction']
        user_ref.update({
            'balance': Increment(-transaction['price']),
            'transaction_history': ArrayUnion([transaction])
        })
    if 'load' in data:
        load = data['load']
        user_ref.update({'gross_loaded': Increment(load)})

    return Response('User data successfully updated', 200)
예제 #5
0
def update_food_status_active(db, public_id, uid, body):
    hour_id = body["hour_id"]
    food_id = body["food_id"]
    hour_ref = db.collection(u'restaurants').document(
        public_id).collection(u'hours').document(hour_id)

    if body["food_active"] == True:
        try:
            hour_ref.update({u'foods_active': ArrayUnion([food_id])})
        except Exception as e:
            return api_db_error(e)
    else:
        try:
            hour_ref.update({u'foods_active': ArrayRemove([food_id])})
        except Exception as e:
            return api_db_error(e)

    return api_success()
예제 #6
0
def result():
    if request.method == 'POST':
        # parsing the search term that the user entered
        term = request.form.getlist('searchbox')[0]
        # tweets = tweepy.Cursor(api.search, q=term).items(5)
        # using api.search cause Cursor started causing problems on adding more content to the page -- todo
        tweets = api.search(term, count=30)

        # adding individial tweets to an array before adding to firestore --this could be improved
        array_of_tweets = []
        for tweet in tweets:
            array_of_tweets.append(tweet.text)

        # query firestore for tweet data
        # todo: check firestore docs to see if both the operations can be done in one query
        doc_ref = db.collection(u'tweet_collection').document(term)
        doc = doc_ref.get()

        # query firestore to check for search terms
        search_terms = db.collection(u'tweet_collection').get()

        # adding previous search terms to array so that they can be rendered
        array_of_search_terms = []
        for terms in search_terms:
            array_of_search_terms.append(terms.id)

        if doc.exists:
            # update the tweet array with latest batch of tweets
            doc_ref.update({
                u'tweets': ArrayUnion(array_of_tweets),
                u'timestamp': datetime.datetime.now()
            })
        else:
            # create a new doc and array of tweets
            doc_ref.set({
                u'tweets': array_of_tweets,
                u'timestamp': datetime.datetime.now()
            })

        return render_template("result.html",
                               tweets=tweets,
                               search_terms=array_of_search_terms)
예제 #7
0
def cron():
    if request.method == 'GET':
        # get the search terms in collection
        searched_terms = db.collection(u'tweet_collection').get()
        for term in searched_terms:
            # after getting the terms, run twitter search for each and add tweets to array
            new_tweets = api.search(term.id, count=30)
            array_of_new_tweets = []
            for results in new_tweets:
                array_of_new_tweets.append(results.text)

            # add new results to db for each term
            # todo: use bulk update operation
            db.collection(u'tweet_collection').document(term.id).update({
                u'tweets':
                ArrayUnion(array_of_new_tweets),
                u'timestamp':
                datetime.datetime.now()
            })
    print('cron job done!!')
    return render_template('index.html')
예제 #8
0
def create_account(email, passw, full_name, trofi_code):
    # Setup initial user account
    try:
        user = authe.create_user_with_email_and_password(email, passw)

        uid = user['localId']

        res_ref = db.collection(u'restaurants').document("trofi-res-" +
                                                         trofi_code)

        res_private_ref = res_ref.collection(u'private').document(uid)

        logs_ref = res_ref.collection(u'logs')

        foods_ref = db.collection(u'foods').where(u'restaurant_id', u'==',
                                                  trofi_code)

        batch = db.batch()

        food_data = foods_ref.get()
        menu = []
        for food in food_data:
            try:
                menu.append(food.id)
                single_food_ref = db.collection(u'foods').document(food.id)
                single_food_private_ref = db.collection(u'foods').document(
                    food.id).collection(u'private')
                private_docs = single_food_private_ref.get()
                for doc in private_docs:
                    old_food_private_ref = single_food_private_ref.document(
                        doc.id)
                    private_food_data = doc.to_dict()

                new_food_private_ref = single_food_private_ref.document(uid)
                batch.set(new_food_private_ref, private_food_data)
                old_food_private_ref.delete()
                batch.update(single_food_ref,
                             {"restaurant_id": "trofi-res-" + trofi_code})
            except Exception as e:
                return None, e

        batch.set(
            res_ref, {
                "is_active": False,
                "name": "",
                "logo": "",
                "opening_hour": 0,
                "closing_hour": 0,
                "menu": menu,
                "tags": [],
                "desc": "",
                "address": "",
                "contact_email": "",
                "contact_phone": "",
            })

        now = datetime.datetime.now()

        batch.set(
            res_private_ref, {
                "accepted_code": trofi_code,
                "user_name": full_name,
                "allow_in": False,
                "payment_id": "",
                "total_orders": 0,
                "credit_card_percentage": 0,
                "credit_card_constant": 0,
                "joined": now,
                "last_login": now,
            })

        batch.set(logs_ref.document("00-00-0000"), {
            "discounts": [],
        })

        general_ref = db.collection(u'general').document("trofi-verification")
        batch.update(general_ref,
                     {u'accepted_codes_unused': ArrayRemove([trofi_code])})
        batch.update(general_ref,
                     {u'accepted_codes_used': ArrayUnion([trofi_code])})

        map_ref = db.collection(u'general').document(
            "trofi-verification").collection(uid).document("map")
        batch.set(map_ref, {
            "public_id": "trofi-res-" + trofi_code,
        })

        # Commit the batch
        batch.commit()
    except Exception as e:
        return None, e

    print("Restaurant successfully written!")
    return user, None
예제 #9
0
def handleNavigationCommand(cmd, query):
    """Handles all user navigation commands

    Keyword arguments:
    cmd -- the command to be executed (up, north etc.)
    query -- The query string
    Returns: the status, room information, users in the room
    """
    #Initialize some temporary variables
    text = ""
    progress = False  #Check if the user has actually progressed or not in the end
    negIndex = False
    roomInfo = dict()
    usersInRoom = list()
    status = "success"
    if cmd == "up":  #Move one position up
        query[0] += 1
    elif cmd == "down":  #Move one position down
        if query[0] - 1 >= 0:  #Should always be greater than zero (no negative indexes)
            query[0] -= 1
        else:
            negIndex = True
    elif cmd == "north":  #Move one position forward
        query[1] += 1
    elif cmd == "south":  #Move one position backward
        if query[1] - 1 >= 0:  #Should always be greater than zero (no negative indexes)
            query[1] -= 1
        else:
            negIndex = True
    elif cmd == "east":  #Move one position to right
        query[2] += 1
    elif cmd == "west":  #Move one position to left
        if query[2] - 1 >= 0:  #Should always be greater than zero (no negative indexes)
            query[2] -= 1
        else:
            negIndex = True
    if negIndex == True:
        roomInfo[
            'text'] = "Umm...you cant make that move...try something else."
        return "Progress Failed", roomInfo, usersInRoom
    world = loadWorld(session.get("world_id"))
    old_location = session.get('user_location')
    try:
        #Get the room info of the new room
        roomInfo = getRoomInfo(query, world["floors"])
        if roomInfo["type"] == "solid":  #You can't enter a room of type solid
            text = "Oops...this room is locked (solid room) ! try something else."
            status = "Progress Failed"
        else:
            progress = True
            session['user_location'] = roomInfo["id"]
    except Exception as e:
        text = "Umm...you cant make that move...try something else."
        status = "Progress Failed"
    if progress == True:  #If the user has progressed
        new_location = session['user_location']
        usersInRoom = getUsersInRoom()
        worldRef = db.collection(u'world').document(session.get("world_id"))
        #Remove user from current map location in db and relocate the user to the new location in db
        worldRef.update({
            old_location.decode('utf-8'):
            ArrayRemove([session.get("user_id").decode('utf-8')])
        })
        worldRef.update({
            new_location.decode('utf-8'):
            ArrayUnion([session.get("user_id").decode('utf-8')])
        })
        roomInfo['text'] = generateRoomInfoText(roomInfo)
    else:
        roomInfo['text'] = text
    return status, roomInfo, usersInRoom
예제 #10
0
def interaction(request):

    if (request.method == "POST"):

        user_text = request.POST['user_text']
        print(user_text)

        list_of_emo_conv = []

        doc = conversations.document(request.session['emailid'])

        doc2 = records.document(request.session['emailid'])

        custom_user_conv = doc2.get().to_dict()['userConv']
        custom_bot_conv = doc2.get().to_dict()['botConv']

        if (user_text in custom_user_conv):
            index = custom_user_conv.index(user_text)
            return HttpResponse(custom_bot_conv[index])

        if (user_text != "Bye" and user_text != "bye"):
            reply, list_of_emo_conv = modelwork.callme(user_text)
        else:
            import time
            time.sleep(10)
            reply = modelwork.task3(list_of_emo_conv)

        print(reply)

        user_conv_old = doc.get().to_dict()['Uppermost'][-1]['UserConv']
        bot_conv_old = doc.get().to_dict()['Uppermost'][-1]['BotConv']
        time = doc.get().to_dict()['Uppermost'][-1]['time']

        doc.update({
            u'Uppermost':
            ArrayRemove([{
                u'time': time,
                u'BotConv': bot_conv_old,
                u'UserConv': user_conv_old,
                #u'Uppermost.Time': firestore.SERVER_TIMESTAMP
            }])
        })

        user_conv_old.append(user_text)
        bot_conv_old.append(reply)

        print(user_conv_old)

        doc.update({
            u'Uppermost':
            ArrayUnion([{
                u'time': time,
                u'BotConv': bot_conv_old,
                u'UserConv': user_conv_old,
            }])
        })

        return HttpResponse(reply)

    else:
        doc = conversations.document(request.session['emailid'])

        doc.update({
            u'Uppermost':
            ArrayUnion([{
                u'time': datetime.datetime.now(),
                u'BotConv': [],
                u'UserConv': []
            }])
        })
        return render(request, 'chatbot.html', {"trial": "Added"})