Beispiel #1
0
def savePoleStats(update, type):
    username = update.message.from_user.name.replace("@", "")
    path = ''
    if type == 'pole':
        path += 'polestats.json'
    elif type == 'xero':
        path += 'polexerostats.json'
    elif type == 'nordis':
        path += 'polenordisstats.json'
    elif type == 'rae':
        path += 'poleraestats.json'
    elif type == 'yonki':
        path += 'poleyonki.json'

    data = Utils.loadFile(path, True, [
                          {'username': username, 'count': 0}])

    found = None
    i = 0
    while i < len(data):
        if data[i]['username'] == username:
            data[i]['count'] += 1
            found = True
        i += 1
    if found == None:
        data.append({'username': username, 'count': 1})

    Utils.saveFile(path, data)
Beispiel #2
0
def profile():
    # Variables locales
    error = None
    response = None
    id_client = None
    id_user = None

    try:
        # Revisar formato JSON
        valid_json_data = Utils.validateRequestJsonData(request)
        if valid_json_data:
            # Revisar existencia del token
            token = Utils.getTokenFromHeader(request)
            if token is not None:
                # Revisar validez del token
                auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)
                decoded_token = auth.decodeToken(token)
                if 'errno' not in decoded_token:
                    # Revisar argumentos válidos
                    json_data = request.get_json()
                    validate_arguments = Utils.allPostArgumentsExists(
                        json_data, ['id_user', 'id_client'])
                    if validate_arguments[0]:
                        # Crear db, tupla de args y llamada a SP
                        db = Database.getInstance(__dbHost, __dbUser, __dbPswd,
                                                  __dbName)
                        id_user = json_data['id_user']
                        id_client = json_data['id_client']
                        args = (id_user, id_client)
                        user_opt = db.callProc(Procedure.GET_USER_MENU_OPTIONS,
                                               args,
                                               True)  # Obtención de opciones

                        # Revisar que el usuario existe
                        if user_opt:
                            response = User.get_ordered_options(user_opt)
                        else:
                            # Usuario inválido
                            error = Error.INVALID_USER
                    else:
                        # Argumentos inválidos
                        error = copy.deepcopy(Error.REQUIRED_ARGUMENTS)
                        error['errmsg'] = error['errmsg'].format(
                            validate_arguments[1])
                else:
                    # Token inválido
                    error = decoded_token
            else:
                # Token inexistente
                error = Error.TOKEN_NOT_FOUND
        else:
            # Formato JSON inválido
            error = Error.INVALID_REQUEST_BODY
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(json.dumps(response if error is None else error),
                             200,
                             mimetype='application/json')
Beispiel #3
0
def test():
    error = None
    response = None

    try:
        # Revisamos si el token viene en el header de la peticion
        token = Utils.getTokenFromHeader(request)
        if token is not None:
            # Si esta, lo decodificamos
            auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)
            decodedToken = auth.decodeToken(token)

            if "errno" not in decodedToken:
                response = decodedToken
            else:
                error = decodedToken
        else:
            error = Error.TOKEN_NOT_FOUND
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(json.dumps(response if error is None else error),
                             200,
                             mimetype='application/json')
Beispiel #4
0
def callback_andalucia(bot, job):
    if str(job.context) == str(settings["main"]["groupid"]):
        restTime = Utils.getRandomByValue(2)
        now = datetime.now() + timedelta(days=1)
        now = now.replace(hour=17 + restTime, minute=Utils.getRandomByValue(59))
        j.run_once(callback_andalucia, now, context=job.context)
        bot.send_message(chat_id=job.context,
                         text="¡Buenos días, Andalucía! :D")
Beispiel #5
0
def get_auth():
    error = None
    response = None

    try:
        # Revisa que el body de la petición sea un json válido
        validJsonData = Utils.isValidJsonData(request)
        if validJsonData == True:
            jsonData = request.get_json()

            # Revisa que en el json esten los argumentos necesarios. En este caso, user y password
            validateArguments = Utils.areValidPostArguments(
                jsonData, ["username", "password"])
            if validateArguments['status'] == 'success':
                # Crea instancia de DB, arma tupla de argumentos y llama al SP correspondiente
                DATABASE = Database.getInstance(
                    Settings.PLATFORM_DB_HOST, 
                    Settings.PLATFORM_DB_USER, 
                    Settings.PLATFORM_DB_PSWD, 
                    Settings.PLATFORM_DB_NAME
                )
                username = jsonData["username"]
                password = jsonData["password"]
                args = (username, password, 0,)
                res = DATABASE.callProc(Procedure.GET_USER_API, args, False)

                # Si res es NONE, no trajo resultados el SP
                if res is None:
                    error = Error.INVALID_USER
                else:
                    # Si el usuario existe, genera el token
                    auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)

                    # 1: Cantidad de días de vigencia del token
                    # user-api-: SUBJECT del token, meramente informativo. Podemos usar el id del usuario y que es de la api
                    userId = res["id"]
                    token = auth.encodeToken(1, 'user-api-' + str(userId))
                    if token is not None:
                        response = OrderedDict([
                            ("token", token["token"]),
                            ("expires", token["expires"].isoformat())
                        ])
                    else:
                        error = Error.TOKEN_GENERATION_ERROR
            else:
                # Si hay que modificar algo del mensaje, se hace un deepcopy, no modificamos directamente la variable porque es estatica
                error = copy.deepcopy(Error.REQUIRED_ARGUMENTS)
                error["errmsg"] = error["errmsg"].format(validateArguments[1])
        else:
            error = Error.INVALID_REQUEST_BODY
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(
        json.dumps(response if error is None else error), 200, mimetype='application/json'
    )
Beispiel #6
0
def startJobs(bot, update):
    now = datetime.now() - timedelta(days=1)
    restTime = Utils.getRandomByValue(2)
    now = now.replace(hour=17 + restTime, minute=Utils.getRandomByValue(59))
    j.run_once(callback_andalucia, now, context=update.message.chat_id)
    # now = now.replace(hour=2, minute=00)
    # job_daily = j.run_daily(callback_bye, now.time(), days=(
    #     0, 1, 2, 3, 4, 5, 6), context=update.message.chat_id)
    data = loadMemories()
    for item in data:
        j.run_once(callback_remember, dateutil.parser.parse(item["when"]), context=update.message.chat_id)
Beispiel #7
0
 def typeMethodPostsVideos(
     method_name
 ):  #Numero de visitas a post o reproducciones de videos (VER)
     try:
         isValid = Utils.isValidJsonData(request)
         if isValid:
             jsonData = request.get_json()
             validArgs = Utils.areValidPostArguments(
                 jsonData, ["account", "date_since", "date_until", "posts"])
             if validArgs["status"] == "error":
                 return json.dumps(validArgs)
             if Utils.areValidDatesInputUnix(jsonData["date_since"],
                                             jsonData["date_until"]):
                 if Utils.areDatesDifferences90days(
                         jsonData["date_since"], jsonData["date_until"]
                 ):  #Chequeo diferencia 90 dias
                     res_token = Utils.getToken(Settings.PLATFORM_DB_HOST,
                                                Settings.PLATFORM_DB_USER,
                                                Settings.PLATFORM_DB_PSWD,
                                                Settings.PLATFORM_DB_NAME,
                                                jsonData["account"], 2)
                     token = res_token["message"]
                     pageId = Utils.getPageId(FbSettings.graphUrlId, token)
                     jRes = [
                     ]  #lista de datos que se muestran en json response
                     for post in jsonData["posts"]:
                         url = buildUrlPost(pageId, post, token,
                                            method_name,
                                            jsonData["date_since"],
                                            jsonData["date_until"])
                         print(url)
                         req = requests.get(url)
                         res = json.loads(req.text)
                         for data in res["data"]:
                             for value in data["values"]:
                                 valor_dato = value["value"]
                                 jRes.append({
                                     post: valor_dato  #idPost : valor
                                 })
                     jsonResponse = Utils.getResponseJson(
                         "success", "", False)
                     jsonResponse["data"] = jRes
                     return json.dumps(jsonResponse)
                 else:
                     return getResponseJson("error",
                                            "The maximum range is 90 days",
                                            False)
         else:
             return getResponseJson(
                 "error", "Invalid data format or not data available")
     except:
         Utils.setLog()
         return Utils.getResponseJson("error", "Programming failure")
 def switch(self):
     utils = Utils()
     dice = self.dice
     while 1:
         print("Your dice are:")
         for die in dice:
             print(die.name)
         answer = utils.ask("What do you want to equip?").lower()
         if answer in [die.name.lower() for die in dice]:
             new = [die for die in dice if die.name.lower() == answer][0]
             print("Equipped " + new.name + '!')
             return new
         else:
             print("You don't have that die.")
Beispiel #9
0
def auth2():
    error = None
    response = None
    try:
        # Revisa que esten los argumentos necesarios en la peticion. En este caso, user y password
        validateArguments = Utils.allGetArgumentsExists(
            request, ["username", "password"])
        if validateArguments[0] == True:
            # Crea instancia de DB, arma tupla de argumentos y llama al SP correspondiente
            DATABASE = Database.getInstance(__dbHost, __dbUser, __dbPswd,
                                            __dbName)
            username = request.args.get("username")
            password = request.args.get("password")
            args = (
                username,
                password,
                0,
            )
            res = DATABASE.callProc(Procedure.GET_USER_API, args, False)

            # Si res es NONE, no trajo resultados el SP
            if res is None:
                error = Error.INVALID_USER
            else:
                # Si el usuario existe, genera el token
                auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)

                # 1: Cantidad de días de vigencia del token
                # user-api-: SUBJECT del token, meramente informativo. Podemos usar el id del usuario y que es de la api
                userId = res["id"]
                token = auth.encodeToken(1, 'user-api-' + str(userId))
                if token is not None:
                    response = OrderedDict([("token", token["token"]),
                                            ("expires",
                                             token["expires"].isoformat())])
                else:
                    error = Error.TOKEN_GENERATION_ERROR
        else:
            error = copy.deepcopy(Error.REQUIRED_ARGUMENTS)
            error["errmsg"] = error["errmsg"].format(validateArguments[1])
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(json.dumps(response if error is None else error),
                             200,
                             mimetype='application/json')
Beispiel #10
0
def addDataToJson(text):
    global downloadData
    msg = Utils.replaceStr(text, "miguelito mete")
    msgSplitted = msg.split("#")
    msg = Utils.replaceStr(msg, msgSplitted[0])
    # add randoms messages
    if msgSplitted[0] == "random":
        botDict['randomMsg'].append(msgSplitted[1])
    elif msgSplitted[0] == "dinosaurio":
        botDict['dinofaurioPath'].append(msg)
    elif msgSplitted[0] == "mimimi":
        botDict['mimimimiStickerPath'].append(msg)
    else:
        msgToCheck = []
        for item in msgSplitted[2].split("--"):
            print(item)
            itemSplitted = item.split("__")
            print(itemSplitted)
            msgToCheck.append(
                {"text": itemSplitted[0], "type": itemSplitted[1]})

        downloadData = {
            "type": msgSplitted[0],
            "regexpValue": [msgSplitted[1].split("--")] if len(msgSplitted[1]) > 0 else [],
            "msgToCheck": msgToCheck,
            "randomMaxValue": int(msgSplitted[3]),
            "lastTimeSentIt": msgSplitted[4],
            "timeToIncrement": int(msgSplitted[5]),
            "kindTime": msgSplitted[6],
            "doubleMsg": bool(msgSplitted[7]),
            "doubleObj": {},
            "notIn": [msgSplitted[8].split("--")] if len(msgSplitted[1]) > 0 else [],
            "isReply": False
        }
        if len(msgSplitted) > 10 and msgSplitted[10] == "true":
            downloadData["doubleObj"] = {
                "type": msgSplitted[11],
                "path": [],
                "isReply": False
            }

    if msgSplitted[0] == "text":
        downloadData["path"] = msgSplitted[9].split("--")
        botDict["keywords"].append(downloadData)

    saveDictionary()
Beispiel #11
0
def loop():
    global activeScreen
    global oldActiveScreen
    global screensaverNeedsUpdate

    if activeScreen:
        if oldActiveScreen != activeScreen:
            coffeeBot.state.needs_render = True
            coffeeBot.apps[coffeeBot.get_active_app()].state.needs_render = True
            oldActiveScreen = activeScreen
        coffeeBot.update('fg')
    else:
        coffeeBot.update('bg')
        if screensaverNeedsUpdate:
            screen.fill('black')
            screen.image('icon.png', xy=screensaverCoordinates, max_width=90, max_height=90, scale='fit', align="center")
            screen.text(
                datetime.datetime.now(settings['timezone']).strftime('%H:%M'),
                xy=(screensaverCoordinates[0], screensaverCoordinates[1] + 55),
                color=(255, 255, 255),
                font_size=16, font=Utils.get_font_resource('akkuratstd-bold.ttf')
            )
            screensaverNeedsUpdate = False
Beispiel #12
0
 def typeMethodTypeOfOrdered(
     method_name
 ):  #Datos agrupados y ordenados por tipo de.. (reacciones, num. de veces, etc)
     try:
         isValid = Utils.isValidJsonData(request)
         if isValid:
             jsonData = request.get_json()
             validArgs = Utils.areValidPostArguments(
                 jsonData, ["account", "date_since", "date_until"])
             if validArgs["status"] == "error":
                 return json.dumps(validArgs)
             if Utils.areValidDatesInputUnix(jsonData["date_since"],
                                             jsonData["date_until"]):
                 if Utils.areDatesDifferences90days(
                         jsonData["date_since"], jsonData["date_until"]
                 ):  #Chequeo diferencia 90 dias
                     res_token = Utils.getToken(Settings.PLATFORM_DB_HOST,
                                                Settings.PLATFORM_DB_USER,
                                                Settings.PLATFORM_DB_PSWD,
                                                Settings.PLATFORM_DB_NAME,
                                                jsonData["account"], 2)
                     token = res_token["message"]
                     url = Utils.buildUrl(graphUrl, token, method_name,
                                          jsonData["date_since"],
                                          jsonData["date_until"])
                     req = requests.get(url)
                     res = json.loads(req.text)
                     jRes = [
                     ]  #lista de datos que se muestran en json response
                     for data in res["data"]:
                         if data["period"] == "day":
                             for values in data["values"]:
                                 fecha_temp = values["end_time"].split(
                                     'T')  #end_time
                                 fecha = fecha_temp[0]
                                 dic_info = {}
                                 claves = values["value"].keys()
                                 for c in claves:
                                     valor_dato = values["value"][
                                         c]  #valor de la clave 1, valor de la clave 2..
                                     clave_dato = c
                                     dic_info[clave_dato] = valor_dato
                                 dic_resultado = Utils.orderDictionary(
                                     dic_info)
                                 jRes.append({fecha: dic_resultado})
                     jsonResponse = Utils.getResponseJson(
                         "success", "", False)
                     jsonResponse["data"] = jRes
                     return json.dumps(jsonResponse)
                 else:
                     return Utils.getResponseJson(
                         "error", "The maximum range is 90 days", False)
         else:
             return Utils.getResponseJson(
                 "error", "Invalid data format or not data available")
     except:
         Utils.setLog()
         return Utils.getResponseJson("error", "Programming failure")
Beispiel #13
0
 def typeMethodNumberOf(
     method_name
 ):  #Datos agrupados por numero de.. (personas, veces, clicks, milisegundos)
     try:
         isValid = Utils.isValidJsonData(request)
         if isValid:
             jsonData = request.get_json()
             validArgs = Utils.areValidPostArguments(
                 jsonData, ["account", "date_since", "date_until"])
             if validArgs["status"] == "error":
                 return json.dumps(validArgs)
             if Utils.areValidDatesInputUnix(jsonData["date_since"],
                                             jsonData["date_until"]):
                 if Utils.areDatesDifferences90days(
                         jsonData["date_since"], jsonData["date_until"]
                 ):  #Chequeo diferencia 90 dias
                     res_token = Utils.getToken(Settings.PLATFORM_DB_HOST,
                                                Settings.PLATFORM_DB_USER,
                                                Settings.PLATFORM_DB_PSWD,
                                                Settings.PLATFORM_DB_NAME,
                                                jsonData["account"], 2)
                     token = res_token["message"]
                     url = Utils.buildUrl(graphUrl, token, method_name,
                                          jsonData["date_since"],
                                          jsonData["date_until"])
                     req = requests.get(url)
                     res = json.loads(req.text)
                     jRes = [
                     ]  #lista de datos que se muestran en json response
                     for data in res["data"]:
                         if data["period"] == "day":
                             for values in data["values"]:
                                 value = values[
                                     "value"]  #value (nro de personas)
                                 fecha_temp = values["end_time"].split(
                                     'T')  #end_time
                                 fecha = fecha_temp[0]
                                 jRes.append({fecha: value})
                     jsonResponse = Utils.getResponseJson(
                         "success", "", False)
                     jsonResponse["data"] = jRes
                     return json.dumps(jsonResponse)
                 else:
                     return Utils.getResponseJson(
                         "error", "The maximum range is 90 days", False)
         else:
             return Utils.getResponseJson(
                 "error", "Invalid data format or not data available")
     except:
         Utils.setLog()
         return Utils.getResponseJson("error", "Programming failure")
Beispiel #14
0
def rememberJobs(bot, update, msg):
    #compare time with the dateConfig.json
    timeObject = checkTimeToRemember(msg)
    # check is have username in the msg
    usernameToNotify, msg = getUsernameToNotify(msg, update)
    # with key words in config json
    if timeObject != None:
        msg = msg.replace(timeObject["name"] + " ", "", 1)
        msg, timeObject = checkHourToRemember(msg, timeObject)

        msgArray = msg.split(" ")
        msg = Utils.replaceStr(msg, "que")

        now = datetime.now()
        now = Utils().checkRememberDate(now, timeObject, None)
        if datetime.now() > now:
            now = now + timedelta(days=1)

    # with dd/mm/yyyy config
    elif re.search(r'([0-9]+/[0-9]+/[0-9]+)', msg):
        msgArray = msg.split(" ")
        msg = Utils.replaceStr(msg, "el")

        dateWithoutSplit = re.search(r'([0-9]+/[0-9]+/[0-9]+)', msg)
        dateString = dateWithoutSplit.group(0)
        dateSplitted = dateString.split('/')
        now = datetime.now()

        msg = Utils.replaceStr(msg, dateString)
        msg = Utils.replaceStr(msg, "que")

        now = now.replace(int(dateSplitted[2]), int(
            dateSplitted[1]), int(dateSplitted[0]))
        timeObject = {}
        msg, timeObject = checkHourToRemember(msg, timeObject)
        now = Utils().checkRememberDate(now, timeObject, None)
        if datetime.now() > now:
            now = now + timedelta(days=1)

    # with weekday config or hh:mm
    else:
        msgArray = msg.split(" ")
        msg = Utils.replaceStr(msg, "el")

        found = None
        index = 0
        while index < len(weekdayConstant) and found != True:
            if weekdayConstant[index] in msg:
                found = True
                msg = msg.replace(weekdayConstant[index] + " ", "", 1)
            else:
                index += 1
        now = datetime.now()
        todayNumber = now.weekday()
        diffDayCount = 0
        # check how many days is from today
        if found:
            if int(todayNumber) < index:
                diffDayCount = index - int(todayNumber) + 1
            else:
                diffDayCount = (6 - int(todayNumber)) + index + 1

        msg = Utils.replaceStr(msg, "que")

        timeObject = {}
        msg, timeObject = checkHourToRemember(msg, timeObject)
        now = Utils().checkRememberDate(now, timeObject, True)
        diffDayCount = checkDayDifference(
            diffDayCount, datetime.now(), timeObject)
        now = now + timedelta(days=diffDayCount)

    update.message.reply_text(
        "Vale", reply_to_message_id=update.message.message_id)
    now = now.replace(second=0)
    saveMessageToRemember(
        usernameToNotify, msg, now.isoformat())
    return now
Beispiel #15
0
class User:
    def __init__(self):
        self.db = Database()
        self.utils = Utils()

    def _select_all(self):
        return self.db.query('SELECT * FROM User')

    def _select_count_by_email(self, email):
        return int(
            self.db.query(
                'SELECT COUNT(*) AS COUNT FROM User WHERE email = "' + email +
                '"')[0]['COUNT'])

    def _select_count_by_email_password(self, email, password):
        return int(
            self.db.query(
                'SELECT COUNT(*) AS COUNT FROM User WHERE email = "' + email +
                '" AND password = "******"')[0]['COUNT'])

    def _insert(self, fullname, email, password):
        return self.db.sql(
            'INSERT INTO User(fullname, email, password) VALUES ("' +
            fullname + '", "' + email + '", "' + self.utils.md5(password) +
            '")')

    def _delete_user(self, email, password):
        return self.db.sql('DELETE FROM User WHERE email = "' + email +
                           '" AND password = "******"')

    def _select_id_by_email(self, email):
        return self.db.query('SELECT iduser FROM User WHERE email = "' +
                             email + '"')[0]['iduser']

    def _select_all_by_userid(self, userid):
        return self.db.query('SELECT * FROM User WHERE iduser = "******"')

    def _update_but_password(self, fullname, email, description, userid):
        return self.db.sql('UPDATE User SET fullname="' + fullname +
                           '", email="' + email + '", description="' +
                           description + '" WHERE iduser = "******"')

    def _update_password(self, password, userid):
        return self.db.sql('UPDATE User SET password="******" WHERE iduser = "******"')

    def _delete(self, user_id):
        self.db.sql('DELETE FROM VoteAnswer WHERE iduser = "******"')
        self.db.sql('DELETE FROM VoteQuestion WHERE iduser = "******"')
        self.db.sql('DELETE FROM Answer WHERE iduser = "******"')
        self.db.sql(
            'DELETE a FROM Answer a INNER JOIN Question q ON a.idquestion = q.idquestion WHERE q.iduser = "******"')
        self.db.sql('DELETE FROM Question WHERE iduser = "******"')
        self.db.sql('DELETE FROM User WHERE iduser = "******"')

    def get_by_id(self, id):
        data = self._select_all_by_userid(id)
        if len(data) == 1:
            return data[0]
        else:
            return False

    def validate_register(self, fullname, email, password):
        if not self.utils.validate_not_empty([fullname, email, password]):
            return False
        if self._select_count_by_email(email) == 0:
            if self._insert(fullname, email, password) == 1:
                return True
        return False

    def validate_login(self, email, password):
        if not self.utils.validate_not_empty([email, password]):
            return False
        if self._select_count_by_email_password(email, password) == 1:
            return True
        return False

    def validate_update(self, fullname, email, password, description, userid):
        if not self.utils.validate_not_empty([fullname, email, userid]):
            return False
        r = False
        if password != '':
            self._update_password(password, userid)
        self._update_but_password(fullname, email, description, userid)
        return True
Beispiel #16
0
class Answer:
    def __init__(self):
        self.db = Database()
        self.utils = Utils()

    def _select_all(self):
        return self.db.query('SELECT * FROM Answer')

    def _select_all_by_questionid(self, questionid):
        return self.db.query(
            'SELECT a.idanswer, a.idquestion, a.iduser, a.description, (CASE WHEN b.rating IS NULL THEN 0 ELSE b.rating END) AS rating, DATE_FORMAT(a.data, "%d/%m/%Y %H:%i:%s") AS data, u.fullname AS user_fullname FROM Answer a LEFT JOIN (SELECT idanswer, SUM(vote) AS rating FROM VoteAnswer GROUP BY idanswer) b ON b.idanswer = a.idanswer INNER JOIN User u on a.iduser = u.iduser WHERE a.idquestion = "'
            + questionid + '"')

    def _select_count_by_author(self, author):
        return int(
            self.db.query(
                'SELECT COUNT(*) AS COUNT FROM Answer WHERE author = "' +
                author + '"')[0]['COUNT'])

    def _insert_vote(self, idanswer, iduser, vote):
        return self.db.sql(
            'INSERT INTO VoteAnswer(idanswer, iduser, vote) VALUES (' +
            idanswer + ',' + iduser + ',' + vote + ')')

    def _insert(self, idquestion, iduser, description):
        return self.db.sql(
            'INSERT INTO Answer(idquestion, iduser, description) VALUES ("' +
            idquestion + '", "' + str(iduser) + '", "' + description + '")')

    def _delete(self, answer_id, user_id):
        return self.db.sql('DELETE FROM Answer WHERE idanswer = ' +
                           str(answer_id) + ' AND iduser = '******'UPDATE Answer SET description="' +
                           answer_description + '" WHERE idanswer = "' +
                           str(answer_id) + '"')

    def get_by_user(self, user_id):
        return self.db.query(
            'SELECT a.idquestion, a.idanswer, a.description, DATE_FORMAT(a.data, "%d/%m/%Y %H:%i:%s") AS data, q.title, u.fullname FROM Answer a INNER JOIN Question q ON a.idquestion = q.idquestion INNER JOIN User u ON a.iduser = u.iduser WHERE a.iduser = "******"')

    def remove_by_question_id(self, question_id):
        return self.db.sql('DELETE FROM Answer WHERE idquestion = ' +
                           str(question_id))

    def get_iduser_by_idanswer(self, answer_id):
        return self.db.sql('SELECT iduser FROM Answer WHERE idanswer = "' +
                           str(answer_id) + '"')

    def get_by_id(self, answer_id):
        return self.db.query(
            'SELECT q.title, a.iduser, a.description FROM Answer a INNER JOIN Question q ON a.idquestion = q.idquestion WHERE a.idanswer = "'
            + str(answer_id) + '"')[0]

    def remove(self, answer_id, user_id):
        self._delete(answer_id, user_id)
        return True

    def validate_answer_edit(self, description, user_id, answer_id):
        if not self.utils.validate_not_empty([description, user_id, answer_id
                                              ]):
            return False
        if user_id:
            return self._edit(description, answer_id)
        else:
            return False

    def validate_answer_post(self, idquestion, iduser, description):
        if not self.utils.validate_not_empty([idquestion, iduser, description
                                              ]):
            return False
        if iduser:
            return self._insert(idquestion, iduser, description)
        else:
            return False

    def vote(self, idanswer, iduser, vote):
        self._insert_vote(idanswer, iduser, vote)
Beispiel #17
0
from chatbots.facebook import facebook_blueprint
from chatbots.instagram import instagram_blueprint
from chatbots.web import web_blueprint
from chatbots.whatsapp import whatsapp_blueprint

__appHostname = '0.0.0.0'
__appPort = 5001
app = Flask(__name__)
CORS(app)

app.register_blueprint(auth_blueprint, url_prefix='/auth')
app.register_blueprint(chatbots_blueprint, url_prefix='/chatbots')
app.register_blueprint(facebook_blueprint, url_prefix='/chatbots/fb')
app.register_blueprint(instagram_blueprint, url_prefix='/chatbots/ig')
app.register_blueprint(web_blueprint, url_prefix='/chatbots/wb')
app.register_blueprint(whatsapp_blueprint, url_prefix='/chatbots/wa')

if __name__ == '__main__':
    try:
        reload(sys)

        # EN PRODUCCION, CON LOS CERTIFICADOS CORRESPONDIENTES
        # context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        # context.load_cert_chain(__sslCert, __sslKey)
        # serving.run_simple(__appHostname, __appPort, app, threaded=True, ssl_context=context)

        # DESARROLLO
        serving.run_simple(__appHostname, __appPort, app)
    except:
        Utils.setLog()
Beispiel #18
0
def update_user():
    # Variables locales
    error = None
    response = None
    id_user = None
    user_name = None
    email = None
    password = None
    id_hub = None
    options = None

    try:
        # Revisar formato JSON válido
        valid_json_data = Utils.validateRequestJsonData(request)
        if valid_json_data:
            # Revisar existencia del token
            token = Utils.getTokenFromHeader(request)
            if token is not None:
                # Revisar validez del token
                auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)
                decoded_token = auth.decodeToken(token)
                if 'errno' not in decoded_token:
                    # Revisar argumentos válidos
                    json_data = request.get_json()
                    validate_arguments = Utils.allPostArgumentsExists(
                        json_data, [
                            'id_user', 'user_name', 'email', 'password',
                            'id_hub', 'options'
                        ])
                    if validate_arguments[0]:
                        # Crear db, tupla de args y llamada a SP
                        db = Database.getInstance(__dbHost, __dbUser, __dbPswd,
                                                  __dbName)
                        id_user = json_data['id_user']
                        user_name = json_data['user_name']
                        email = json_data['email']
                        password = json_data['password']
                        id_hub = json_data['id_hub']
                        options = json_data['options']
                        args = (id_user, user_name, email, password, id_hub,
                                options)
                        creation_result = db.callProc(
                            Procedure.UPDATE_USER, args,
                            True)  # Creación de usuario

                        # Revisar que la creación sea exitosa
                        if creation_result:
                            response = OrderedDict([
                                ('status', 'success'),
                                ('message', 'User updated successfully')
                            ])
                        else:
                            # Creación de usuario fallida
                            error = Error.USER_CREATION_ERROR
                    else:
                        # Argumentos inválidos
                        error = copy.deepcopy(Error.REQUIRED_ARGUMENTS)
                        error['errmsg'] = error['errmsg'].format(
                            validate_arguments[1])
                else:
                    # Token inválido
                    error = decoded_token
            else:
                # Token inexistente
                error = Error.TOKEN_NOT_FOUND
        else:
            # Formato JSON inválido
            error = Error.INVALID_REQUEST_BODY
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(json.dumps(response if error is None else error),
                             200,
                             mimetype='application/json')
Beispiel #19
0
def saveDictionary():
    Utils.saveFile('dataDictionary.json', botDict)
 def setUpClass(self):
     self.an = Answer()
     self.utils = Utils()
Beispiel #21
0
def login():
    # Variables locales
    error = None
    response = None
    email = None
    password = None

    try:
        # Revisar formato JSON válido
        valid_json_data = Utils.validateRequestJsonData(request)
        if valid_json_data:
            # Revisar existencia del token
            token = Utils.getTokenFromHeader(request)
            if token is not None:
                # Revisar validez del token
                auth = JWTAuth(__jwtPrivateKey, __jwtPublicKey)
                decoded_token = auth.decodeToken(token)
                if 'errno' not in decoded_token:
                    # Revisar argumentos válidos
                    json_data = request.get_json()
                    validate_arguments = Utils.allPostArgumentsExists(
                        json_data, ['email', 'password'])
                    if validate_arguments[0]:
                        # Crear db, tupla de args y llamada a SP
                        db = Database.getInstance(__dbHost, __dbUser, __dbPswd,
                                                  __dbName)
                        email = json_data['email']
                        password = json_data['password']
                        args = (email, password)
                        user_results = db.callProc(
                            Procedure.GET_USER_PLATFORM, args,
                            True)  # Obtención de usuario

                        # Revisar que el usuario existe
                        if user_results:
                            response = OrderedDict([
                                ('id', user_results[0]['id']),
                                ('id_cliente', user_results[0]['id_cliente']),
                                ('nombre', user_results[0]['nombre']),
                                ('email', user_results[0]['email']),
                                ('canales',
                                 User.get_user_channels(user_results))
                            ])
                        else:
                            # Usuario inválido
                            error = Error.INVALID_USER
                    else:
                        # Argumentos inválidos
                        error = copy.deepcopy(Error.REQUIRED_ARGUMENTS)
                        error['errmsg'] = error['errmsg'].format(
                            validate_arguments[1])
                else:
                    # Token inválido
                    error = decoded_token
            else:
                # Token inexistente
                error = Error.TOKEN_NOT_FOUND
        else:
            # Formato JSON inválido
            error = Error.INVALID_REQUEST_BODY
    except:
        Utils.setLog()
        error = Error.PROGRAMMING_ERROR

    return wrappers.Response(json.dumps(response if error is None else error),
                             200,
                             mimetype='application/json')
Beispiel #22
0
from classes.utils import Utils

current_ip = "109.64.186.249"
web_servers = [{"hostname": "s1.impospace.com", "user": "******", "pass": "******"}]

command = ["iptables -I INPUT 8 -s {0} -p tcp -j ACCEPT".format(current_ip)]

for x in web_servers:
    Utils.execute_remote_commands(x["hostname"], x["user"], x["pass"], command)
from classes.utils import Utils
from classes.utils import Fight
from classes.die import Die
from classes.player import Player

utils = Utils()

class Manager():
    D4 = Die(1, 4, "D4")
    D6 = Die(1, 6, "D6")
    D8 = Die(1, 8, "D8")
    D10 = Die(1, 10, "D10")
    D12 = Die(1, 12, "D12")
    D20 = Die(1, 20, "D20")
    WD4 = Die(3, 4, "Weighted D4")
    WD6 = Die(4, 6, "Weighted D6")
    WD8 = Die(5, 8, "Weighted D8")
    WD10 = Die(6, 10, "Weighted D10")
    WD12 = Die(7, 12, "Weighted D12")
    WD20 = Die(11, 20, "Weighted D20")
    possibleDice = [D4, D6, D8, D10, D12, D20, WD4, WD6, WD8, WD10, WD12, WD20]

    encounterMessages = ["You see a guy sitting around doing much.",
    "You stumble across a jerk. Mainly cause they tripped you.",
    "You approach a random person.", "That person looks like they want trouble.",
    "Someone is looking at you funny."]

    def printGameDetails(self):
        print("You can have this Weighted D6. It was my favourite die when I was your age.")
        print("Obtained Weighted D6!")
        print("Take good care of it.")
Beispiel #24
0
import datetime
from random import randint
import subprocess
from classes.utils import Utils
import json
from dateutil import parser as date_parser
from dateutil.tz import gettz

screen.fill((0, 0, 0))
screen.image('icon.png', xy=(160, 120), max_width=150, max_height=150, scale='fit', align="center")
screen.text(
    'loading...',
    xy=(160, 210),
    align='center',
    color=(255, 255, 255),
    font_size=16, font=Utils.get_font_resource('akkuratstd-bold.ttf')
)
screen.update()

settings = {
    'ticksPerSecond': 20,
    'countdownSeconds': 300,
    'sleepAfterSeconds': 300,
    'timezone': gettz(tingbot.app.settings['coffeeBot']['timezone']),
    'musicFolder': tingbot.app.settings['coffeeBot']['musicFolder']
}
startup = True
activeScreen = True
oldActiveScreen = activeScreen
lastActionAt = datetime.datetime.now(settings['timezone'])
coffeeBot = CoffeeBot(screen, settings['countdownSeconds'], settings['ticksPerSecond'], settings['timezone'], settings['musicFolder'])
Beispiel #25
0
 def typeMethodGenderAge(
         method_name):  #Datos agrupados por genero en rango de edades.
     try:
         isValid = Utils.isValidJsonData(request)
         if isValid:
             jsonData = request.get_json()
             validArgs = Utils.areValidPostArguments(
                 jsonData, ["account", "date_since", "date_until"])
             if validArgs["status"] == "error":
                 return json.dumps(validArgs)
             if Utils.areValidDatesInputUnix(
                     jsonData["date_since"],
                     jsonData["date_until"]):  #Chequeo fechas UNIX validas
                 if Utils.areDatesDifferences90days(
                         jsonData["date_since"], jsonData["date_until"]
                 ):  #Chequeo diferencia 90 dias
                     res_token = Utils.getToken(Settings.PLATFORM_DB_HOST,
                                                Settings.PLATFORM_DB_USER,
                                                Settings.PLATFORM_DB_PSWD,
                                                Settings.PLATFORM_DB_NAME,
                                                jsonData["account"], 2)
                     token = res_token["message"]
                     url = Utils.buildUrl(graphUrl, token, method_name,
                                          jsonData["date_since"],
                                          jsonData["date_until"])
                     req = requests.get(url)
                     res = json.loads(req.text)
                     jRes = []
                     for data in res["data"]:
                         if data["period"] == "day":
                             for values in data["values"]:
                                 fecha_temp = values["end_time"].split(
                                     'T')  #end_time
                                 fecha = fecha_temp[0]
                                 dic_male = {}
                                 dic_female = {}
                                 dic_undefined = {}
                                 claves = values["value"].keys()
                                 for c in claves:  #c es la clave
                                     valor_dato = values["value"][
                                         c]  #valor de la clave 1, valor de la clave 2..
                                     clave_dato = c
                                     clave_dato_splitted = clave_dato.split(
                                         '.')
                                     clave_genero = clave_dato_splitted[
                                         0]  #Genero
                                     clave_info = clave_dato_splitted[
                                         1]  #Info del genero
                                     #DATOS A MOSTRAR clave_genero, clave_info, valor_dato
                                     if (clave_genero == 'M'):
                                         dic_male[clave_info] = valor_dato
                                     if (clave_genero == 'F'):
                                         dic_female[clave_info] = valor_dato
                                     if (clave_genero == 'U'):
                                         dic_undefined[
                                             clave_info] = valor_dato
                                 jRes.append({
                                     fecha: {
                                         "female": dic_female,
                                         "male": dic_male,
                                         "undefined": dic_undefined
                                     }
                                 })
                     jsonResponse = Utils.getResponseJson(
                         "success", "", False)
                     jsonResponse["data"] = jRes
                     return json.dumps(jsonResponse)
                 else:
                     return Utils.getResponseJson(
                         "error", "The maximum range is 90 days", False)
         else:
             return Utils.getResponseJson(
                 "error", "Invalid data format or not data available")
     except:
         Utils.setLog()
         return Utils.getResponseJson("error", "Programming failure")
Beispiel #26
0
from dotenv import load_dotenv, find_dotenv

from classes.database import Database
from classes.utils import Utils
from models.base import TableBase

if __name__ == "__main__":
    load_dotenv(find_dotenv())

    Utils.load_config()
    lotofacil = TableBase(name="lotofacil")
    Database().create_table(lotofacil)
Beispiel #27
0
    def typeMethodCity(method_name):  #Datos agrupados por ciudad
        try:
            isValid = Utils.isValidJsonData(request)
            if isValid:
                jsonData = request.get_json()
                validArgs = Utils.areValidPostArguments(
                    jsonData, ["account", "date_since", "date_until"])
                if validArgs["status"] == "error":
                    return json.dumps(validArgs)
                if Utils.areValidDatesInputUnix(jsonData["date_since"],
                                                jsonData["date_until"]):
                    if Utils.areDatesDifferences90days(
                            jsonData["date_since"], jsonData["date_until"]
                    ):  #Chequeo diferencia 90 dias
                        res_token = Utils.getToken(Settings.PLATFORM_DB_HOST,
                                                   Settings.PLATFORM_DB_USER,
                                                   Settings.PLATFORM_DB_PSWD,
                                                   Settings.PLATFORM_DB_NAME,
                                                   jsonData["account"], 2)
                        token = res_token["message"]
                        url = Utils.buildUrl(graphUrl, token, method_name,
                                             jsonData["date_since"],
                                             jsonData["date_until"])
                        req = requests.get(url)
                        res = json.loads(req.text)
                        jRes = [
                        ]  #lista de datos que se muestran en json response
                        for data in res["data"]:
                            if data["period"] == "day":
                                for values in data["values"]:
                                    fecha_temp = values["end_time"].split(
                                        'T')  #end_time
                                    fecha = fecha_temp[0]
                                    claves = values["value"].keys(
                                    )  #Ciudad, provincia, pais.
                                    lista_paises = []
                                    lista_provincias = []
                                    lista_ciudades = []
                                    for c in claves:  #c es la clave
                                        valor_dato = values["value"][
                                            c]  #valor de la clave 1, valor de la clave 2..
                                        clave_dato = c
                                        clave_dato_splitted = clave_dato.split(
                                            ',')
                                        cantidad_divisiones = len(
                                            clave_dato_splitted)
                                        if cantidad_divisiones > 3:
                                            ciudad = clave_dato_splitted[0]
                                            provincia = clave_dato_splitted[
                                                1]  #Provincia compuesta
                                            provincia = provincia.strip()
                                            for i in range(
                                                    2,
                                                (len(clave_dato_splitted) -
                                                 1)):
                                                provincia = provincia + clave_dato_splitted[
                                                    i]
                                            pais = clave_dato_splitted[3]
                                            pais = pais.strip()
                                            if pais not in lista_paises:
                                                lista_paises.append(pais)
                                            t_provincia = (provincia, pais
                                                           )  #prov, pais
                                            if t_provincia not in lista_provincias:
                                                lista_provincias.append(
                                                    t_provincia)

                                            t_ciudad = (
                                                (ciudad,
                                                 valor_dato), provincia, pais
                                            )  #ciudad y valor, provincia, pais
                                            if t_ciudad not in lista_ciudades:
                                                lista_ciudades.append(t_ciudad)

                                        if (cantidad_divisiones == 3):
                                            ciudad = clave_dato_splitted[0]
                                            provincia = clave_dato_splitted[1]
                                            provincia = provincia.strip()
                                            pais = clave_dato_splitted[2]
                                            pais = pais.strip()
                                            if pais not in lista_paises:
                                                lista_paises.append(pais)

                                            t_provincia = (provincia, pais
                                                           )  #prov, pais
                                            if t_provincia not in lista_provincias:
                                                lista_provincias.append(
                                                    t_provincia)

                                            t_ciudad = (
                                                (ciudad,
                                                 valor_dato), provincia, pais
                                            )  #ciudad y valor, provincia, pais
                                            if t_ciudad not in lista_ciudades:
                                                lista_ciudades.append(t_ciudad)
                                        else:
                                            if (cantidad_divisiones == 2):
                                                ciudad = clave_dato_splitted[0]
                                                pais = clave_dato_splitted[1]
                                                pais = pais.strip()
                                                if pais not in lista_paises:
                                                    lista_paises.append(pais)

                                                t_ciudad = (
                                                    (ciudad,
                                                     valor_dato), None, pais
                                                )  #ciudad y valor, nada, pais
                                                if t_ciudad not in lista_ciudades:
                                                    lista_ciudades.append(
                                                        t_ciudad)
                                    #Estructuro jerarquicamente localidad, con provincia , con pais.
                                    lista_pa = []
                                    for pais in lista_paises:
                                        lista_pr = []
                                        for provincia in lista_provincias:
                                            lista_ci = []
                                            for ciudad in lista_ciudades:  #ciudades con provincia
                                                if ciudad[1] != None and ciudad[
                                                        1] == provincia[
                                                            0] and ciudad[
                                                                2] == pais:
                                                    lista_ci.append(ciudad[0])
                                            if len(lista_ci) > 0:
                                                lista_pr.append(
                                                    (provincia[0], lista_ci))
                                        for ciudad in lista_ciudades:  #ciudades sin provincia
                                            if ciudad[1] == None and ciudad[
                                                    2] == pais:
                                                lista_pr.append(
                                                    (ciudad[0], None))
                                        lista_pa.append((pais, lista_pr))

                                    dic_pais = {}
                                    for pais in lista_pa:
                                        dic_provincia = {}
                                        for prov in pais[
                                                1]:  #prov puede ser una ciudad y su valor, o una tupla (provincia,lista_ci)
                                            dic_ciudad = {}
                                            if prov[1] != None:  #lista_ci
                                                for ciud in prov[
                                                        1]:  #itero en lista ciudades para esa prov
                                                    dic_ciudad[
                                                        ciud[0]] = ciud[1]
                                                dic_provincia[
                                                    prov[0]] = dic_ciudad
                                            else:
                                                dic_provincia[prov[0]
                                                              [0]] = prov[0][1]
                                        dic_pais[pais[0]] = dic_provincia
                                    jRes.append({fecha: dic_pais})
                        jsonResponse = Utils.getResponseJson(
                            "success", "", False)
                        jsonResponse["data"] = jRes
                        return json.dumps(jsonResponse)
                    else:
                        return Utils.getResponseJson(
                            "error", "The maximum range is 90 days", False)
            else:
                return Utils.getResponseJson(
                    "error", "Invalid data format or not data available")
        except:
            Utils.setLog()
            return Utils.getResponseJson("error", "Programming failure")
Beispiel #28
0
 def __init__(self):
     self.db = Database()
     self.utils = Utils()
Beispiel #29
0
def loadDictionary(bot, update):
    global botDict
    botDict = Utils.loadFile('dataDictionary.json', False, {})