Ejemplo n.º 1
0
def root():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")

            data = render_template(RENDER_ROOT)

            rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return data, 200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 2
0
def __getMatchById(match_id):
    sqlRequest = """select date__c , 
       match__c.participant_home__c participant_home_id,
       match__c.participant_visitor__c participant_visitor_id,
       match__c.sfid match_id,
       match__c.gameactivity__c gameactivity__c,
       match__c.question__c question__c,
       participant__home.name participant_home_name,
       participant__home.image__c participant_home_image,
       participant__home.description__c participant_home_description,
       participant__visitor.name participant_visitor_name,
       participant__visitor.image__c participant_visitor_image,
       participant__visitor.description__c participant_visitor_description
       
        from salesforce.match__c, 
            salesforce.participant__c participant__home,
            salesforce.participant__c participant__visitor

        where match__c.sfid= %(match_id)s 
        and (participant__home.sfid = match__c.participant_home__c)
        and (participant__visitor.sfid = match__c.participant_visitor__c)"""

    key = {"sqlRequest": "__getMatchById", "match_id": match_id}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        data = __execRequest(sqlRequest, {'match_id': match_id})
        rediscache.__setCache(key, ujson.dumps(data), 60)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 3
0
def __getMatchsByGameActivityId(gameactivity__c):
    sqlRequest = """select match__c.sfid matchid ,
            match__c.date__c Date,
            match__c.question__c Question,
            participant__c_home.name as Participant_Home,
            participant__c_visitor.name Participant_Visitor
            
            from 
                    salesforce.match__c match__c, 
                    salesforce.participant__c participant__c_home , 
                    salesforce.participant__c participant__c_visitor
                    
            where match__c.gameactivity__c =  %(gameactivity__c)s
            and (participant__c_home.sfid = match__c.participant_home__c)
            and (participant__c_visitor.sfid = match__c.participant_visitor__c)
            
            order by 
            
            match__c.date__c DESC"""

    key = {
        "sqlRequest": "__getMatchsByGameActivityById",
        "activityId": gameactivity__c
    }
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        data = __execRequest(sqlRequest, {'gameactivity__c': gameactivity__c})
        rediscache.__setCache(key, ujson.dumps(data), 60)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 4
0
def root_photo():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data = render_template(RENDER_ROOT_PHOTO,
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 5
0
def getObjects():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        # output type
        output = 'html'
        if 'output' in request.args:
            output = request.args['output'].lower()

        # logs all attributes received
        logger.debug(get_debug_all(request))
        # gets object name
        object_name = ''
        if ('name' in request.args):
            object_name = request.args['name']
        else:
            return "Error, must specify a object name with ?name=xxx", 404

        key = {'url': request.url, 'output': output}
        tmp_dict = None
        data_dict = None
        tmp_dict = rediscache.__getCache(key)
        data = ""
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict = postgres.__getObjects(object_name)

            if (output == 'html'):
                logger.info(
                    "Treating request as a web request, output to Web page")
                data = render_template(RENDER_TABLE_DATA,
                                       columns=data_dict['columns'],
                                       object_name=object_name,
                                       entries=data_dict['data'])
            else:
                logger.info(
                    "Treating request as an API request, output to Json only")
                data = ujson.dumps(data_dict)

            if (postgres.HEROKU_LOGS_TABLE
                    not in request.url):  # we don't want to cache these logs
                rediscache.__setCache(key, data.encode('utf-8'), 300)

        else:
            logger.info("Data found in redis, using it directly")
            #logger.info(tmp_dict)
            if (output == 'html'):
                #data_dict = ujson.loads(tmp_dict)
                data = tmp_dict.decode('utf-8')
            else:
                #data = ujson.loads(tmp_dict)
                data = tmp_dict

        logger.info("returning data")
        return data, 200

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 6
0
def votes_placevote():
    try:
        if (postgres.__checkHerokuLogsTable()):
                postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        key = {'url' : request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            #gameactivity__c = request.args['gameactivity__c']            
            match_id = request.args['match_id']            
            resultMatch = postgres.__getMatchById(match_id)
            if (resultMatch['data'][0]['question__c'] == None):
                resultMatch['data'][0]['question__c'] = ""
            data = render_template(RENDER_PLACE_BET,
                entry = resultMatch['data'][0]
                )
            rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict
            

        return data, 200

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 7
0
def homepage():
    cookie, cookie_exists = utils.getCookie()
    logger.debug(utils.get_debug_all(request))

    key = {'cookie': cookie}
    tmp_dict = None
    #data_dict = None
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache")
        logger.debug(utils.get_debug_all(request))
        text = 'User is not authenticated, please log in ! <a href="%s">Authenticate with Salesforce</a>'

        state = str(uuid4())
        save_created_state(state)
        params = {
            "client_id": APP_CLIENT_ID,
            "response_type": "code",
            "state": state,
            "redirect_uri": REDIRECT_URI_CODE,
            "scope": "full refresh_token"
        }

        url = SF_AUTHORIZE_TOKEN_URL + urllib.parse.urlencode(params)
        logger.info(url)
        data = text % url
    else:
        data = tmp_dict

    return utils.returnResponse(data, 200, cookie, cookie_exists)
Ejemplo n.º 8
0
def votes_placevote():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            #gameactivity__c = request.args['gameactivity__c']
            match_id = request.args['match_id']
            resultMatch = postgres.__getMatchById(match_id)
            if (resultMatch['data'][0]['question__c'] == None):
                resultMatch['data'][0]['question__c'] = ""
            data = render_template(RENDER_PLACE_BET,
                                   entry=resultMatch['data'][0],
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 9
0
def is_valid_state(state):
    val = rediscache.__getCache(state)
    logger.info(val)
    return val != None and val != '' and val == b'created'


#if __name__ == '__main__':
#    app.run(debug=True, port=65010)
Ejemplo n.º 10
0
def __getImageAnalysis(tableName, objectName):
    key = {"sqlRequest" : "__getImageAnalysis", "objectName" : objectName}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        concat = SALESFORCE_SCHEMA + "." + tableName
        data = __execRequest("select * from {} where name='{}' ".format(concat, objectName), {})
        rediscache.__setCache(key, ujson.dumps(data), 120)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 11
0
def createTicket():
    try:
        cookie, cookie_exists =  utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        logger.debug(utils.get_debug_all(request))

        form = TicketForm(request.form)
        
        hosts = postgres.__getSFUsers()
        key = {'url' : MAIN_URL, 'cookie' : cookie}
        tmp_dict = rediscache.__getCache(key)
        data = ""
        if (request.method=="GET"):
            if ((tmp_dict != None) and (tmp_dict != '')):    
                #means user has already registered, forwarding him to the guest thanks
                data = render_template(CREATETICKETS, registered=True, form=form, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                # means it has to register
                return redirect("/",code=302)
        elif request.method == 'POST':
            if ((tmp_dict != None) and (tmp_dict != '')):    
                #means user has already registered, accepting this 
                Reason=request.form['Reason']
                Subject=request.form['Subject']
                Description=request.form['Description']
                postgres.__insertCase(cookie, Subject, Description, "Self Service", Reason)
                #postgres.__saveGuestEntry(Firstname, Lastname, Email, Company, PhoneNumber, Host, cookie, Picture)
                data = render_template(GUESTTHANKS, registered=True, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                #rediscache.__setCache(key, data.encode('utf-8'), 3600)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                # means user has not registered and is trying to post, .. 
                # so returning him the registration page first
                return redirect("/",code=302)
        else:
            # trying to hack someting ?
            return redirect("/",code=302)

        
        data = render_template(CREATETICKETS, form=form, hosts=hosts['data'],userid=cookie,PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)

        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists =  utils.getCookie()
        return utils.returnResponse("An error occured, check logDNA for more information", 200, cookie, cookie_exists)
Ejemplo n.º 12
0
def __getTables():

    key = {"sqlRequest": "__getTables"}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        sqlRequest = "SELECT table_schema, table_name FROM information_schema.tables where table_schema like '%%alesforce' ORDER BY table_schema,table_name"
        data = __execRequest(sqlRequest, {})

        rediscache.__setCache(key, ujson.dumps(data), 30)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 13
0
def __getObjects(tableName):
    key = {"sqlRequest": "__getObjects", "tableName": tableName}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : data not known")
        concat = SALESFORCE_SCHEMA + "." + tableName
        data = __execRequest("select * from {}".format(concat), {})
        logger.info("Data Returned")
        logger.info(data)
        rediscache.__setCache(key, utils.jsonencode(data), 30)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 14
0
def __getSFUsers():
    key = {"sqlRequest": "getSFUsers"}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):

        logger.info("Data not found in cache : heroku log data not known")
        sql = "select name, sfid from salesforce.user where CanAcceptGuest__c = 'True' order by name ASC"
        data = __execRequest(sql, {})

        rediscache.__setCache(key, utils.jsonencode(data), 60)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    logger.debug(data)
    return data
Ejemplo n.º 15
0
def bets_bygameactivity__c():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        has_voted = False
        if ('has_voted' in request.args):
            has_voted = bool(request.args['has_voted'])
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")

            gameactivity__c = request.args['gameactivity__c']
            resultActivityName = postgres.__getGameActivityById(
                gameactivity__c)
            result = postgres.__getMatchsByGameActivityId(gameactivity__c)

            data = render_template(
                RENDER_BETS_MATCHS,
                columns=result['columns'],
                entries=result['data'],
                category_name=resultActivityName['data'][0]['activityname'],
                category_id=gameactivity__c,
                hasvoted=has_voted,
                FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                userid=cookie,
                PUSHER_KEY=notification.PUSHER_KEY)

            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 16
0
def __checkHerokuLogsTable():
    key = {'checkHerokuLogTables' : "True"}
    tmp_dict = None
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        hasDatabase = False
    
        if (MANUAL_ENGINE_POSTGRES != None):
            sqlRequest = 'SELECT EXISTS( SELECT * FROM information_schema.tables  WHERE table_schema = %(schema)s AND table_name = %(tablename)s ) '
            result = MANUAL_ENGINE_POSTGRES.execute(sqlRequest, {'schema' : SALESFORCE_SCHEMA, 'tablename' : HEROKU_LOGS_TABLE} )
            for entry in result:
                logger.info(entry['exists'])
                hasDatabase = entry['exists']
            if (hasDatabase == True):
                rediscache.__setCache(key, "True", 3600)
        return hasDatabase
    else:
        return True 
Ejemplo n.º 17
0
def __getMatchs():
    sqlRequest = """
                    select   
                        salesforce.gameactivity__c.name , 
                        salesforce.gameactivity__c.sfid, 
                        (select count(*) from  salesforce.match__c where salesforce.match__c.gameactivity__c = salesforce.gameactivity__c.sfid) as nbMatchs 
                    from salesforce.gameactivity__c 
                    where salesforce.gameactivity__c.active__c = True
                    """
    key = {"sqlRequest": "__getMatchs"}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache : heroku log data not known")
        data = __execRequest(sqlRequest, None)
        rediscache.__setCache(key, ujson.dumps(data), 60)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data
Ejemplo n.º 18
0
def __getGameActivityById(gameactivity__c):
    key = {"sqlRequest" : "__getGameActivityById", "activityId" : gameactivity__c}
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):

        logger.info("Data not found in cache : heroku log data not known")
        sqlRequestActivityName = """
            select gameactivity__c.name ActivityName
            from 
                salesforce.gameactivity__c  
            where
                 gameactivity__c.sfid = %(gameactivity__c)s """

        data = __execRequest(sqlRequestActivityName, {'gameactivity__c':gameactivity__c}) 
        rediscache.__setCache(key, ujson.dumps(data), 60)
    else:
        logger.info("Data found in redis, using it directly")
        data = ujson.loads(tmp_dict)

    return data   
Ejemplo n.º 19
0
def contact():
    try:
        cookie, cookie_exists = utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))
        if ('phone' not in request.args):
            return utils.returnResponse("Please provide a phone number", 403,
                                        cookie, cookie_exists)
        entry_phone = request.args['phone']
        if (entry_phone == '' or entry_phone == None):
            return utils.returnResponse("Please provide a phone number", 403,
                                        cookie, cookie_exists)

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict = postgres.__execRequest(
                'select name, mobilephone, phone, email, sfid from salesforce.contact where phone = %(phone)s or mobilephone=%(phone)s',
                {'phone': entry_phone})
            logger.info(data_dict)
            rediscache.__setCache(key, data_dict, 60)

            data = ujson.dumps(data_dict)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 403, cookie,
            cookie_exists)
Ejemplo n.º 20
0
def FACE_API_CALLBACK(ch, method, properties, body):
    try:
        # transforms body into dict
        body_dict = ujson.loads(body)
        logger.info(body_dict)
        logger.info(" [x] Received id=%r" % (body_dict['id']))
        # gets the id of the image to retrieve in Redis
        image_id = body_dict['id']
        if (body_dict['UPLOAD_IN_REDIS'] == True):
            image_binary_data = rediscache.__getCache(image_id)
            # write binary data   into a file
            logger.debug("Writing file to disk")
            localfilename = '%s/%s' % (PATH_TO_TEST_IMAGES_DIR,
                                       "/rab_" + image_id + ".jpg")
            remotefilename = image_id + ".jpg"
            file = open(localfilename, "wb")
            file.write(image_binary_data)
            file.close()
            # sends data to AWS
            logger.debug("Starting AWS Upload")
            awsFilename = aws.uploadData(localfilename, remotefilename)
            logger.debug("uploaded file to amazon : {}".format(awsFilename))
            # deletes from redis
            rediscache.__delCache(image_id)
            # deletes local file
            os.remove(localfilename)
        else:
            awsFilename = body_dict['remote_url']
        # now detection !!
        logger.debug("Starting Face API")
        result, code = faceapi.face_http(awsFilename)
        logger.debug("Face API Result : {}".format(result))
        if (code != 200):
            logger.error("Can't  treat entry.")
            return
        else:
            img_width = body_dict['image_width']
            img_height = body_dict["image_height"]

            # now treats each result
            for entry in result:
                try:

                    personid = uuid.uuid4().__str__()
                    data = {
                        'MediaId__c':
                        image_id,
                        'image__c':
                        awsFilename,
                        'UserAgent__c':
                        body_dict['user-agent'],
                        'URL__c':
                        body_dict['url'],
                        'Name':
                        personid,
                        'PersonId__c':
                        personid,
                        'Gender__c':
                        entry['faceAttributes']['gender'],
                        'Age__c':
                        int(entry['faceAttributes']['age']),
                        'Smile_value__c':
                        entry['faceAttributes']['smile'],
                        'eyemakeup__c':
                        entry['faceAttributes']['makeup']['eyeMakeup'],
                        'lipmakeup__c':
                        entry['faceAttributes']['makeup']['lipMakeup'],
                        'Emotion_Value__c':
                        0.000
                    }
                    # now let's treat things in the right order ..
                    floatToBool(entry['faceAttributes'], 'smile', data,
                                'Smile__c', 0.5)
                    stringToBool(entry['faceAttributes'], 'glasses', data,
                                 'Glasses__c', ["ReadingGlasses"])
                    floatToBool(entry['faceAttributes']['hair'], 'bald', data,
                                'Bald__c', 0.5)

                    # face square
                    data['ImageWidth__c'] = img_width
                    data['ImageHeight__c'] = img_height
                    data['FaceTop__c'] = int(
                        (entry['faceRectangle']['top'] / img_height) * 100)
                    data['FaceLeft__c'] = int(
                        (entry['faceRectangle']['left'] / img_width) * 100)
                    data['FaceWidth__c'] = int(
                        (entry['faceRectangle']['width'] / img_width) * 100)
                    data['FaceHeight__c'] = int(
                        (entry['faceRectangle']['height'] / img_height) * 100)

                    if (entry['faceAttributes']['hair']['bald'] > 0.49):
                        data['Hair__c'] = "bald"

                    data['Haircolor__c'] = ''
                    if ('hairColor' in entry['faceAttributes']['hair']):
                        if (len(entry['faceAttributes']['hair']['hairColor'])
                                >= 1):
                            data['Haircolor__c'] = entry['faceAttributes'][
                                'hair']['hairColor'][0]['color']
                            data['Hair__c'] = entry['faceAttributes']['hair'][
                                'hairColor'][0]['color']
                        else:
                            data['Hair__c'] = "bald"
                    else:
                        data['Hair__c'] = "bald"

                    FacialHair = "None"
                    if (entry['faceAttributes']['facialHair']['moustache'] >
                            0.49):
                        FacialHair = 'moustache'
                    if (entry['faceAttributes']['facialHair']['beard'] > 0.49):
                        if (FacialHair != "None"):
                            FacialHair += ' or beard'
                        else:
                            FacialHair += 'beard'
                    data['FacialHair__c'] = FacialHair

                    data['Emotion__c'] = "neutral"
                    floatToBool(entry['faceAttributes']['facialHair'],
                                'moustache', data, 'Moustache__c', 0.5)
                    floatToBool(entry['faceAttributes']['facialHair'], 'beard',
                                data, 'Beard__c', 0.5)

                    floatToBool(entry['faceAttributes']['emotion'], 'anger',
                                data, 'Anger__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'contempt',
                                data, 'Contempt__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'disgust',
                                data, 'Disgust__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'fear',
                                data, 'Fear__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'],
                                'happiness', data, 'Happiness__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'neutral',
                                data, 'Neutral__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'sadness',
                                data, 'Sadness__c', 0.01)
                    floatToBool(entry['faceAttributes']['emotion'], 'surprise',
                                data, 'Surprise__c', 0.01)

                    data['Emotion_Value__c'] = 0.0
                    data['Emotion__c'] = 'neutral'

                    floatToString(entry['faceAttributes']['emotion'], 'anger',
                                  data['Emotion_Value__c'], data, 'Emotion__c',
                                  'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'contempt', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'disgust', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'], 'fear',
                                  data['Emotion_Value__c'], data, 'Emotion__c',
                                  'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'happiness', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'neutral', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'sadness', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')
                    floatToString(entry['faceAttributes']['emotion'],
                                  'surprise', data['Emotion_Value__c'], data,
                                  'Emotion__c', 'Emotion_Value__c')

                    data['Description__c'] = ujson.dumps(entry)

                    logger.debug(data)

                    postgres.__saveImageAnalysisEntry(data)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    logger.error("Error treating entry, going to the next")
            logger.info(" [x] Finished id=%r" % (body_dict['id']))
    except Exception as e:
        import traceback
        traceback.print_exc()
Ejemplo n.º 21
0
def singleguestbadgemanagement():
    try:
        logger.debug(utils.get_debug_all(request))
        cookie, cookie_exists = utils.getCookie()
        #data_dict = None
        key_fromCanvas = {'cookie': cookie, 'fromCanvas': True}
        tmp_dict_fromCanvas = rediscache.__getCache(key_fromCanvas)

        if ((tmp_dict_fromCanvas == None) or (tmp_dict_fromCanvas == '')):
            logger.info("Data not found in cache")
            logger.debug(utils.get_debug_all(request))
            text = 'User is not coming from canvas app !'
            return utils.returnResponse(text, 200, cookie, cookie_exists)
        else:
            struct_json = ujson.loads(tmp_dict_fromCanvas)
            guest_id = request.args['guest_id']

            # gest the record id

            if request.method == 'POST':
                logger.info("post detected")
                actionform = request.form['action']
                actiontype = actionform.split('.')[0]
                actionvalue = actionform.split('.')[1]
                sqlUpdate = "update public.badge set badge_status=%(status)s where id=%(id)s"
                postgres.__execRequestWithNoResult(sqlUpdate, {
                    'status': actiontype,
                    'id': actionvalue
                })

                # now updates the guest status
                # sf_getProducts(struct_json['client']['instanceUrl'] , struct_json['client']['oauthToken'])
                #def sf_updateBadge(sfurl, sftoken, guest, status)
                logger.info('actionType={}'.format(actiontype))
                sfinstanceurl = struct_json['client']['instanceUrl']
                sftoken = struct_json['client']['oauthToken']
                host_id = sf.sf_getGuestHost(sfinstanceurl, sftoken, guest_id)

                if (actiontype == 'INACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'SECURITY RISK')
                elif (actiontype == 'ACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'BADGE ISSUED')

                sf.sf_ChatterPost(sfinstanceurl, sftoken, guest_id, host_id,
                                  actiontype)

            sqlRequest = "select Id, guest_id, guest_firstname, guest_lastname, badge_status, creation_date from public.badge where guest_id = %(guest_id)s order by creation_date"
            sqlResult = postgres.__execRequest(sqlRequest,
                                               {'guest_id': guest_id})
            data = render_template(CANVAS_FILE,
                                   request_json=ujson.dumps(struct_json),
                                   columns=sqlResult['columns'],
                                   entries=sqlResult['data'])
            return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 22
0
def badgesmanagement():
    try:
        logger.debug(utils.get_debug_all(request))
        cookie, cookie_exists = utils.getCookie()
        key = {'cookie': cookie}
        tmp_dict = None
        #data_dict = None
        key_fromCanvas = {'cookie': cookie, 'fromCanvas': True}

        tmp_dict = rediscache.__getCache(key)
        tmp_dict_fromCanvas = rediscache.__getCache(key_fromCanvas)
        if (tmp_dict != None):
            pprint.pprint(ujson.loads(tmp_dict))
        logger.debug("############")
        if (tmp_dict_fromCanvas != None):
            pprint.pprint(ujson.loads(tmp_dict_fromCanvas))

        if (((tmp_dict == None) or (tmp_dict == '')) and
            ((tmp_dict_fromCanvas == None) or (tmp_dict_fromCanvas == ''))):
            logger.info("Data not found in cache")
            logger.debug(utils.get_debug_all(request))
            text = 'User is not authenticated, please log in ! <a href="%s">Authenticate with Salesforce</a>'

            state = str(uuid4())
            save_created_state(state)
            params = {
                "client_id": APP_CLIENT_ID,
                "response_type": "code",
                "state": state,
                "redirect_uri": REDIRECT_URI_CODE,
                "scope": "full refresh_token"
            }

            url = SF_AUTHORIZE_TOKEN_URL + urllib.parse.urlencode(params)
            logger.info(url)
            data = text % url
            return utils.returnResponse(data, 200, cookie, cookie_exists)
        else:
            if request.method == 'POST':
                struct_json = ujson.loads(tmp_dict)
                logger.info("post detected")
                actionform = request.form['action']
                actiontype = actionform.split('.')[0]
                actionvalue = actionform.split('.')[1]
                sqlUpdate = "update public.badge set badge_status=%(status)s where id=%(id)s"
                postgres.__execRequestWithNoResult(sqlUpdate, {
                    'status': actiontype,
                    'id': actionvalue
                })

                logger.info('actionType={}'.format(actiontype))
                sfinstanceurl = struct_json['instance_url']
                sftoken = struct_json['access_token']
                guest_id = postgres.getBadgeById(
                    actionvalue)['data'][0]['guest_id']
                host_id = sf.sf_getGuestHost(sfinstanceurl, sftoken, guest_id)

                if (actiontype == 'INACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'SECURITY RISK')
                elif (actiontype == 'ACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'BADGE ISSUED')

                sf.sf_ChatterPost(sfinstanceurl, sftoken, guest_id, host_id,
                                  actiontype)

            logger.info(tmp_dict)
            sqlRequest = "select Id, guest_firstname, guest_lastname, badge_status, creation_date from public.badge order by creation_date"
            sqlResult = postgres.__execRequest(sqlRequest, None)
            data = render_template(BADGE_FILE,
                                   columns=sqlResult['columns'],
                                   entries=sqlResult['data'])
            return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 23
0
def bet_vote():
    try:

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        # trick
        # ?matchid={{ entry.match_id }}&gameactivity__c={{ entry.gameactivity__c }}&vote_winner={{ entry.participant_home_id}}
        is_vote_through_get = False
        if ('matchid' in request.args and 
            'vote_winner' in request.args and
            'gameactivity__c' in request.args):
            is_vote_through_get = True

        if (request.method == 'POST' or is_vote_through_get == True):
            matchid = request.args['matchid']
            gameactivity__c=request.args['gameactivity__c']
            if (is_vote_through_get):
                winner = request.args['vote_winner']
            else:
                winner = request.form['vote_winner']
            useragent = request.headers['User-Agent']
            

            externalid = uuid.uuid4().__str__()
            createddate  = datetime.now()

            sqlRequest = """
                insert into salesforce.bet__c (winner__c, 
                useragent__c, 
                name, 
                externalid__c, 
                match__c,
                createddate) values 
                ( %(winner)s, %(useragent)s, %(externalid)s, %(externalid)s, %(matchid)s, %(createddate)s ) """
            
            postgres.MANUAL_ENGINE_POSTGRES.execute(sqlRequest,
                        {
                        'winner' : winner,
                        'useragent' : useragent,
                        'createddate':createddate,
                        'externalid' : externalid,
                        'matchid':matchid} )   
            logger.info('##### vote taken into account ####')
            return redirect('/matchs?gameactivity__c='+gameactivity__c+"&has_voted=True")
        else:            
            key = {'url' : request.url}
            tmp_dict = None
            data_dict = None
            tmp_dict = rediscache.__getCache(key)
            if ((tmp_dict == None) or (tmp_dict == '')):
                logger.info("Data not found in cache")
                sqlRequest = """
                    select   
                        salesforce.gameactivity__c.name , 
                        salesforce.gameactivity__c.sfid, 
                        (select count(*) from  salesforce.match__c where salesforce.match__c.gameactivity__c = salesforce.gameactivity__c.sfid) as nbMatchs 
                    from salesforce.gameactivity__c 

                    """
                data_dict = postgres.__execRequest(sqlRequest, None)
                
                data = render_template(RENDER_BETS_MAIN,
                    columns=data_dict['columns'],
                    entries = data_dict['data'])

                rediscache.__setCache(key, data, 60)
            else:
                logger.info("Data found in redis, using it directly")
                data = tmp_dict

            return data, 200

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 24
0
def guest():
    try:
        cookie, cookie_exists =  utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        logger.debug(utils.get_debug_all(request))

        form = ReusableForm(request.form)
        
        hosts = postgres.__getSFUsers()
        key = {'url' : MAIN_URL, 'cookie' : cookie}
        tmp_dict = rediscache.__getCache(key)
        data = ""
        if request.method == 'GET':
            if ((tmp_dict != None) and (tmp_dict != '')):    
                #means user has already registered, forwarding him to the guest thanks
                data = render_template(GUESTTHANKS, registered=True, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                # needs to register
                data = render_template(GUESTFILE, form=form, hosts=hosts['data'],userid=cookie,PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
        elif request.method == 'POST':
            if ((tmp_dict != None) and (tmp_dict != '')):  
                #user has gone through the registration process already, need to redirect him to the guest thanks page
                data = render_template(GUESTTHANKS, registered=True, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                #user has not registerd yet, it's the case now 
                Firstname=request.form['Firstname']
                Lastname=request.form['Lastname']
                Email=request.form['Email']
                Company=request.form['Company']
                PhoneNumber=request.form['PhoneNumber']
                Host=request.form['Host']
                Picture="https://3.bp.blogspot.com/-KIngJEZr94Q/Wsxoh-8kwuI/AAAAAAAAQyM/YlDJM1eBvzoDAUV79-0v_Us-amsjlFpkgCLcBGAs/s1600/aaa.jpg"
                if ("fileToUpload" in request.files):
                    Picture, rabbitData  =aws.AWS_upload(request.files['fileToUpload'], request)
                    rabbitData['cookie'] = cookie
                    rabbitData['UPLOAD_IN_REDIS'] = False
                    rabbitData['remote_url'] = Picture
                    logger.info(rabbitData)
                    rabbitmq.sendMessage(ujson.dumps(rabbitData), rabbitmq.CLOUDAMQP_QUEUE)


                postgres.__saveGuestEntry(Firstname, Lastname, Email, Company, PhoneNumber, Host, cookie, Picture)
                data = render_template(GUESTTHANKS, registered=False, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                rediscache.__setCache(key, ujson.dumps({"Status":"Logged In"}), 3600)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
                    
        else:
            #redirecting the user
            return redirect("/",code=302)

        if form.validate():
            # Save the comment here.
            flash('Hello ' + Firstname)
        else:
            flash('All the form fields are required. ')
        
        data = render_template(GUESTFILE, form=form, hosts=hosts['data'],userid=cookie,PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)

        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists =  utils.getCookie()
        return utils.returnResponse("An error occured, check logDNA for more information", 200, cookie, cookie_exists)

        
Ejemplo n.º 25
0
def photos_display():
    try:
        cookie, cookie_exists = utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        # output type
        output = 'html'
        if 'output' in request.args:
            output = request.args['output'].lower()

        # logs all attributes received
        logger.debug(utils.get_debug_all(request))
        # gets object name
        object_name = 'ImageAnalysis__c'

        key = {'url': request.url, 'output': output}
        tmp_dict = None
        data_dict = None
        tmp_dict = rediscache.__getCache(key)
        data = ""
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict = postgres.__getObjects(object_name)

            if (output == 'html'):
                logger.info(
                    "Treating request as a web request, output to Web page")
                if ('image__c' in data_dict['columns']):
                    data = render_template(
                        RENDER_PHOTOS_DISPLAY,
                        columns=data_dict['columns'],
                        object_name=object_name,
                        entries=data_dict['data'],
                        FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                        userid=cookie,
                        PUSHER_KEY=notification.PUSHER_KEY)
            else:
                logger.info(
                    "Treating request as an API request, output to Json only")
                data = ujson.dumps(data_dict)

            #if (postgres.HEROKU_LOGS_TABLE not in request.url): # we don't want to cache these logs
            #    rediscache.__setCache(key, data.encode('utf-8'), 60)

        else:
            logger.info("Data found in redis, using it directly")
            #logger.info(tmp_dict)
            if (output == 'html'):
                #data_dict = ujson.loads(tmp_dict)
                data = tmp_dict.decode('utf-8')
            else:
                #data = ujson.loads(tmp_dict)
                data = tmp_dict

        logger.info("returning data")
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 26
0
def image():
    try:

        logger.debug(utils.get_debug_all(request))

        i = request.files['fileToUpload']  # get the image
        imageid = uuid.uuid4().__str__()
        f = ('%s.jpeg' % (imageid))
        i.save('%s/%s' % (PATH_TO_TEST_IMAGES_DIR, f))
        completeFilename = '%s/%s' % (PATH_TO_TEST_IMAGES_DIR, f)

        try:
            filepath = completeFilename
            image = Image.open(filepath)

            img_width = image.size[0]
            img_height = image.size[1]

            for orientation in ExifTags.TAGS.keys():
                if ExifTags.TAGS[orientation] == 'Orientation':
                    break
            exif = dict(image._getexif().items())
            logger.debug(exif[orientation])
            if exif[orientation] == 3:
                image = image.rotate(180, expand=True)
                image.save(
                    filepath,
                    quality=50,
                    subsampling=0,
                )
            elif exif[orientation] == 6:
                image = image.rotate(270, expand=True)
                image.save(
                    filepath,
                    quality=50,
                    subsampling=0,
                )
            elif exif[orientation] == 8:
                image = image.rotate(90, expand=True)
                image.save(
                    filepath,
                    quality=50,
                    subsampling=0,
                )

            img_width = image.size[0]
            img_height = image.size[1]
            image.close()
        except Exception as e:
            import traceback
            traceback.print_exc()

        # ok the entry is correct let's add it in our db
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        # now upload
        logger.debug(completeFilename)

        #prepare rabbitmq data
        rabbitdata = {
            'id': imageid,
            'user-agent': request.headers['User-Agent'],
            'url': request.url,
            'image_width': img_width,
            "image_height": img_height,
            'cookie': cookie
        }

        if (UPLOAD_IN_REDIS == True):
            # Save the image into redis
            file = open(completeFilename, "rb")
            data = file.read()
            file.close()
            rediscache.__setCache(imageid, data, 3600)
            os.remove(completeFilename)
            logger.info("File saved in Redis")
            rabbitdata['UPLOAD_IN_REDIS'] = True
        else:
            # saves into AWS
            rabbitdata['UPLOAD_IN_REDIS'] = False
            remotefilename = imageid + ".jpg"
            awsFilename = aws.uploadData(completeFilename, remotefilename)
            os.remove(completeFilename)
            logger.info("File saved in AWS")
            rabbitdata['remote_url'] = awsFilename

        # Sends data to RabbitMQ
        logger.debug(rabbitdata)
        rabbitmq.sendMessage(ujson.dumps(rabbitdata), rabbitmq.CLOUDAMQP_QUEUE)
        #awsFilename = aws.uploadData(completeFilename, f)

        key = {
            'url': request.url,
            'status_upload': 'Thanks for participating',
            'error_upload': None
        }

        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data = render_template(RENDER_ROOT_PHOTO,
                                   status_upload="Thanks for participating",
                                   error_upload=None,
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        cookie, cookie_exists = utils.getCookie()
        data = render_template(
            RENDER_ROOT_PHOTO,
            status_upload=None,
            error_upload=
            "An error occured while saving your file, please try again",
            FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
            userid=cookie,
            PUSHER_KEY=notification.PUSHER_KEY)

        return utils.returnResponse(data, 200, cookie, cookie_exists)