Esempio n. 1
0
 def post(self, id,data):
     print(data)
     newitem = Assets()
     newitem.assets_id = id
     newitem.data = data
     DBSession.add(newitem)
     DBSession.flush()
     return dict(id=id,data=data)
Esempio n. 2
0
 def post(self, name, breed):
     newitem = Pets()
     newitem.name = name
     newitem.breed = breed
     DBSession.add(newitem)
     DBSession.flush()
     print("Post Name: {} Breed: {}".format(name, breed))
     return dict(name=name, breed=breed, id=newitem.id)
Esempio n. 3
0
    def addTraffic(self, **kw):
        event_id = int(kw['event_id'])
        imei = kw['imei']
        vehicle = kw['vehicle']
        comment = kw['comment']
        listener = 0
        position = getTracker.location(imei=imei)
        latitude = position['latitude']
        print("Latitude:{}".format(latitude))
        longitude = position['longitude']
        print("Longitude:{}".format(longitude))
        speed = position['speed']
        azimuth = position['heading']

        priority = int(kw['priority'])
        if kw['client_id'] == "None":
            client_id = -1
            user_name = "Inexistente=CLIENT_ID=none"
        else:
            parameters = {}
            parameters['imei'] = imei
            connection = requests.get(app_globals.domainpluto + "/services/imeiInfo", parameters)
            imeiData = connection.json()
            if imeiData["error"] == "ok":
                user_name=imeiData["application"]
            else:
                user_name="Inexistente=CLIENT_ID=none"

        currentEvent = DBSession.query(Events).filter_by(event_id=event_id).first()
        if currentEvent is not None:
            nd = currentEvent.event_desc
        else:
            nd = ""

        user = request.identity['repoze.who.userid']
        user = DBSession.query(User).filter_by(user_name=user).first()
        newTraffic = Traffic()
        newTraffic.priority = priority
        newTraffic.event_id = event_id
        newTraffic.user_name = user_name
        newTraffic.imei = imei
        newTraffic.vehicle = vehicle
        newTraffic.callercomment = comment
        newTraffic.event_desc = nd
        newTraffic.latitude = latitude
        newTraffic.longitude = longitude
        newTraffic.azimuth = int(float(azimuth))
        newTraffic.speed = int(float(speed))
        newTraffic.listener = listener
        newTraffic.attended_state = 'A'
        newTraffic.user_id = user.user_id
        newTraffic.user=kw["group"]
        DBSession.add(newTraffic)
        DBSession.flush()


        Message.post("trafficlistener_" + kw["group"], 'RELOAD' + "|")
        return dict(error="ok", id=str(newTraffic.id))
Esempio n. 4
0
 def redirector(self, **kw):
     error = {"Error": "none", "Password": "******"}
     if not ('imei' in kw and 'account' in kw and 'token' in kw
             and 'platform' in kw and 'gate_user' in kw
             and 'gate_password' in kw):
         error = {"Error": "Parametros faltantes"}
     else:
         r = requests.get(app_globals.domainsun + "/app_log/login?user="******"account"])
         j = r.json()
         print(j)
         if j["error"] != "password Not Found":
             error = {"Error": "Cuenta de grupo inexistente"}
         else:
             look = DBSession.query(Smartphones).filter_by(
                 gate_user=kw['gate_user']).first()
             if look is not None:
                 error = {"Error": "Usuario de plataforma ya registrado"}
             else:
                 query = DBSession.query(Smartphones).filter_by(
                     account=kw['account'], imei=kw['imei']).first()
                 if query is not None:
                     if query.token != kw["token"]:
                         error = {
                             "Error":
                             "Este telefono esta asignado a otro dispositivo"
                         }
                 else:
                     root = "23456789AaBbCcDdEeFfGgHhJjKkLlMmNnPpQqRrSsTtUuVvWwXxYyZz"
                     pswd = ""
                     for x in range(0, 4):
                         pswd = pswd + root[random.randint(0, 55)]
                     url = "http://testggs.dwim.mx/GPScontrol/Services/Auth.ashx/login?jsonp=&appId=2&strUsername="******"gate_user"] + "&strPassword="******"gate_password"]
                     r = requests.get(url)
                     j = r.json()
                     print(j)
                     #{'result': True, 'id': -1}
                     if j["result"]:
                         print("Paso!!!")
                         newitem = Smartphones()
                         newitem.imei = kw["imei"]
                         newitem.account = kw["account"]
                         newitem.token = kw["token"]
                         newitem.platform = kw["platform"]
                         newitem.gate_user = kw["gate_user"]
                         newitem.gate_password = kw["gate_password"]
                         newitem.gate_app = "2"
                         newitem.password = pswd
                         DBSession.add(newitem)
                         DBSession.flush()
                         error['Password'] = pswd
                     else:
                         error = {"Error": "Usuario o Password Incorrecto"}
     print(error)
     Message.post("Smartphonesfrom", 'RELOAD' + "|")
     return error
Esempio n. 5
0
 def save_image_app(self, **kw):
     reserved = ReservedImages()
     reserved.code = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
     reserved.extra = "APP"
     reserved.w = 450
     reserved.h = 450
     reserved.job_id = kw["jobid"]
     reserved.image = base64.decodebytes(bytes(kw["image"], 'utf-8'))
     DBSession.add(reserved)
     DBSession.flush()
     return dict(error="ok")
Esempio n. 6
0
 def addPending(self, **kw):
     traffic_id = int(kw['traffic_id'])
     #OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.putPending, traffic_id=traffic_id)
     newPending = Pending()
     newPending.traffic_id = traffic_id
     # newPending.pending_date = datetime.datetime.utcnow()
     newPending.data = kw['comment']
     DBSession.add(newPending)
     DBSession.flush()
     Message.post("trafficlistener_" + kw["group"], 'RELOAD' + "|")
     return dict(error='ok')
Esempio n. 7
0
    def notification(self, **kw):
        if "user" in kw:
            origin = [
                'System', 'Administrator', 'Guest', 'Bob', 'Louisa', 'Mark'
            ]
            action = [
                'Requests', 'Needs', 'Appreciate', 'Speaks', 'Share', 'Insist'
            ]
            category = [
                'Alert Manager', 'Stop Alarm', 'Extinguish Fire',
                'Invite to dinner', 'Rest', 'Take Vacation'
            ]
            title = [
                'Attend Alarm', 'Kill System', 'Start Procedure',
                'Find dodumentation', 'Press Button', 'End procedure'
            ]
            subtitle = [
                'For Neza', 'For Neto Stores', 'For Mexico News',
                'For Alestra', 'For HSBC', 'For Bancomer'
            ]
            pushDate = str(datetime.utcnow())
            icon = [
                'glyphicon glyphicon-tags', 'glyphicon glyphicon-book',
                'glyphicon glyphicon-bookmark', 'glyphicon glyphicon-eye-open',
                'glyphicon glyphicon-warning-sign',
                'glyphicon glyphicon-comment'
            ]

            message = origin[randomNumber()] + "," + action[
                randomNumber()] + "," + category[randomNumber()] + "," + title[
                    randomNumber()] + "," + subtitle[randomNumber(
                    )] + "," + pushDate + "," + icon[randomNumber()]
            userSession = DBSession.query(User).filter_by(
                user_name=kw['user']).first()
            newItem = Notification()
            newItem.user_id = userSession.user_id
            newItem.attended_state = 'N'
            newItem.time_stamp = datetime.utcnow()
            newItem.message = message
            DBSession.add(newItem)
            DBSession.flush()
            counter = DBSession.query(Notification).filter_by(
                user_id=userSession.user_id, attended_state="N").count()
            if counter == 0:
                value = ""
            else:
                value = str(counter)
            message = 'NOT' + "|" + value
            Message.post(kw['user'], message)
            return dict(error='ok')
        else:
            return dict(error='user parameter missing')
Esempio n. 8
0
 def uploadImage(self,**kw):
     if "userfile" in kw:
         fileitem = kw["userfile"]
         if fileitem.file:
             fileName = fileitem.filename
             if fileName.find(".png") > 0 or fileName.find(".jpeg") > 0 or fileName.find(".jpg") > 0:
                 newImage = Images()
                 newImage.traffic_id = kw["traffic_id"]
                 newImage.data = fileitem.file.read()
                 DBSession.add(newImage)
                 DBSession.flush()
                 OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.addImage,traffic_id=kw['traffic_id'])
     return dict(dummy="")
Esempio n. 9
0
 def setUp(self):
     """Setup test fixture for each model test method."""
     try:
         new_attrs = {}
         new_attrs.update(self.attrs)
         new_attrs.update(self.do_get_dependencies())
         self.obj = self.klass(**new_attrs)
         DBSession.add(self.obj)
         DBSession.flush()
         return self.obj
     except:
         DBSession.rollback()
         raise
Esempio n. 10
0
    def updateGrid(self):
        if "oper" in self.kw:
            if self.kw['oper'] == "edit":
                print("edit")
                # print("id:{}".format(self.kw['id']))
                # for key, value in self.kw.iteritems():
                #     print "%s = %s" % (key, value)

                my_filters = {self.indexkey: self.kw['id']}
                query = DBSession.query(self.model)

                for attr, value in my_filters.items():
                    query = query.filter(getattr(self.model, attr) == value)
                item = query.first()
                if item is not None:
                    #print("None Edit")
                    for column in item.__table__.columns:
                        if column.name != self.indexkey:
                            if column.name in self.kw:
                                if str(column.type) == "BOOLEAN":
                                    newvalue = True if self.kw[
                                        column.name] == "True" else False
                                else:
                                    newvalue = self.kw[column.name]
                                #print("updating: {} to {} type:{}".format(column.name, self.kw[column.name],str(column.type)))
                                setattr(item, column.name, newvalue)
                    DBSession.flush()
            if self.kw['oper'] == "add":
                item = self.model()
                #print("add")
                for column in item.__table__.columns:
                    if column.name in self.kw:
                        #print("{}={}".format(str(column.name),str(self.kw[column.name])))
                        if (self.indexkey == column.name):
                            pass
                        else:
                            setattr(item, column.name, self.kw[column.name])

                DBSession.add(item)
                DBSession.flush()

            if self.kw['oper'] == "del":
                my_filters = {self.indexkey: self.kw['id']}
                query = DBSession.query(self.model)
                for attr, value in my_filters.items():
                    query = query.filter(getattr(self.model, attr) == value)
                item = query.first()
                if item is not None:
                    DBSession.delete(item)
                    DBSession.flush()
            return dict(error="")
Esempio n. 11
0
 def addTicket(self, **kw):
     traffic_id = int(kw['traffic_id'])
     comment = kw['comment']
     OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.createTicket,traffic_id=traffic_id)
     ticket = DBSession.query(Traffic).filter_by(id=traffic_id).first()
     if traffic_id != 0:
         kw['imei'] = ticket.imei
     if kw['imei'] is not None:
         imeiInfo = Rest()
         imeiData = imeiInfo.get(app_globals.domainpluto + "/services/imeiInfo", {"imei": kw['imei']})
         if imeiData["error"] == "ok":
             #print("IMEI:"+kw['imei'])
             client_id = imeiData["client_id"]
             if client_id is not None:
                 last_report = imeiData["last_report"]
                 url = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str(
                     client_id) + "&last_report=" + str(last_report) + "&folio=" + str(kw['traffic_id']) + "&imei=" + str(
                     kw['imei']) + "&comm=" + urllib.parse.quote_plus(comment)
                 print("URL:{}".format(url))
                 newTicket = Rest()
                 #print("URL:{}".format(url))
                 ticketData = newTicket.get(url, {})
                 #print("data:{}".format(ticketData))
                 ## Insert if error="ok"
                 #response = requests.get(url)
                 #print("Response:{}".format(ticketData))
                 iticket = ticketData['Ticket']
                 searchticket = DBSession.query(Tickets).filter_by(ticket=iticket).first()
                 if searchticket is None:
                     newTickets = Tickets()
                     if id != 0:
                         newTickets.traffic_id = id
                     newTickets.last_report = last_report
                     newTickets.ticket = iticket
                     newTickets.comment = kw['comment']
                     DBSession.add(newTickets)
                     DBSession.flush()
                     try:
                         newTickets = DBSession.query(imeiTicket).filter_by(imei=kw['imei']).one()
                         newTickets.imei = kw['imei']
                         newTickets.ticket = iticket
                     except:
                         newTickets = imeiTicket()
                         newTickets.imei = kw['imei']
                         newTickets.ticket = iticket
                         DBSession.add(newTickets)
                     DBSession.flush()
                 return ticketData
     else:
         return dict(Ticket=0)
Esempio n. 12
0
 def addTraffic(self, **kw):
     fields = 'event_id,event_desc,user_name,user,latitude,longitude,imei,speed,azimuth,priority,vehicle,valid,dedicated_id'
     error = 'Campos faltantes:'
     errorName = ""
     for item in fields.split(","):
         if not item in kw:
             errorName = errorName + item + ","
     if errorName == "":
         newTraffic = Traffic()
         for item in fields.split(","):
             setattr(newTraffic, item, kw[item])
         DBSession.add(newTraffic)
         DBSession.flush()
         Message.post("trafficlistener_" + kw['user'], 'RELOAD' + "|")
         return dict(error="ok")
     return dict(error=error + errorName[:-1])
Esempio n. 13
0
 def storePosition(self, **kw):
     if 'latitude' in kw and 'longitude' in kw:
         query = DBSession.query(Position).filter_by(id=1).first()
         if query is None:
             new = Position()
             new.id = 1
             new.latitude = kw['latitude']
             new.longitude = kw['longitude']
             DBSession.add(new)
             print("added")
         else:
             query.latitude = kw['latitude']
             query.longitude = kw['longitude']
             print("moded")
         DBSession.flush()
         return dict(error="ok")
     else:
         return dict(error="nok")
Esempio n. 14
0
 def uploadImage2(self, **kw):
     if 'traffic_id' in kw:
         traffic_id = int(kw['traffic_id'])
         file = request.POST['file']
         if file != '':
             # permanent_file = open(os.path.join('/var/www/python.dispatch', file.filename.lstrip(os.sep)), 'w')
             #print(app_globals.app_dir)
             permanent_file = open(os.path.join(app_globals.app_dir+'/', file.filename.lstrip(os.sep)), 'wb')
             copyfileobj(file.file, permanent_file)
             file.file.close()
             permanent_file.close()
             filename = request.params["file"].filename
             (this_file_name, this_file_extension) = os.path.splitext(filename)
             # format=imghdr.what(filename)
             # if format=='jpeg'or format=='bmp' or format=='png':
             if (this_file_extension == '.jpeg' or this_file_extension == '.bmp' or this_file_extension == '.png'):
                 # f = open('/var/www/python.dispatch/' + filename, 'rb').read()
                 f = open(app_globals.app_dir+'/' + filename, 'rb').read()
                 newImage = Images()
                 newImage.traffic_id = traffic_id
                 newImage.data = f
                 DBSession.add(newImage)
                 DBSession.flush()
     redirect("/index")
Esempio n. 15
0
    def listener(self, listenerID, **kw):
        currentListener = DBSession.query(Listeners).filter_by(
            listener_id=listenerID).first()
        if currentListener is None:
            newListener = Listeners()
            newListener.listener_id = listenerID
            newListener.name = "Not Defined"
            DBSession.add(newListener)
            DBSession.flush()
            if newListener.id is not None:
                for key, value in kw.items():
                    newfielditem = ListenerFields()
                    newfielditem.field = key
                    newfielditem.value = value
                    newListener.fields.append(newfielditem)
                    DBSession.add(newfielditem)
                    DBSession.flush()
                #print("Admin LISTENER")
                Message.post("adminlistener", 'NEW' + "|")
        else:
            if currentListener.state == 1:
                #print("listern on")
                if currentListener.logstate == 1:
                    # Enabled Logging
                    currentListenerFields = DBSession.query(
                        ListenerFields).filter_by(
                            listeners_id=currentListener.id).all()
                    mapper = {}
                    for eachListenerField in currentListenerFields:
                        if eachListenerField.assign != 0:
                            mapper[eachListenerField.
                                   assign] = eachListenerField.field
                    newListenerLog = ListenerLog()
                    newListenerLog.time_stamp = datetime.utcnow()
                    newListenerLog.listener_id = currentListener.listener_id
                    newListenerLog.mapper_state = 1
                    if 1 in mapper:
                        newListenerLog.imei = kw[mapper[1]]
                    DBSession.add(newListenerLog)
                    DBSession.flush()
                    currentLog = newListenerLog.id
                allListenerUsers = DBSession.query(ListenerUsers).filter_by(
                    userlisteners_id=currentListener.id).all()
                globalExpressionsRequiredbyListener = []
                activeListenerUsers = []
                for each_user in allListenerUsers:
                    # Getting Users to know which expressions must evaluate
                    #print("Getting users")
                    if each_user.state == 1:
                        #print("USER-->{} userlistener_id{}".format(each_user.user_name,each_user.userlisteners_id))
                        # If the user is active ---> get all the triggers requested by the user
                        activeListenerUsers.append(
                            dict(id=each_user.id,
                                 user_name=each_user.user_name))
                        currentUseId = each_user.id
                        allUserTriggers = DBSession.query(
                            UserTriggers).filter_by(
                                listener_users_id=currentUseId).all()
                        for eachUserTriger in allUserTriggers:
                            # id=1 / Expression = EVENT_DESC=SOS and CLIENT_ID-510
                            # id=2 Expression = EVENT_DESC=Paro de Motor and CLIENT_ID=510
                            currenUserId = eachUserTriger.id
                            allUserGlobalExpressions = DBSession.query(
                                UserGlobalExp).filter_by(
                                    usertriggers_id=currenUserId).all()
                            for eachGlobalExpression in allUserGlobalExpressions:
                                found = False
                                for eitem in globalExpressionsRequiredbyListener:
                                    if eitem[
                                            0] == eachGlobalExpression.global_exp_id:
                                        found = True
                                if not found:
                                    globalExpressionsRequiredbyListener.append(
                                        (eachGlobalExpression.global_exp_id,
                                         each_user.userlisteners_id))
                                    #print((eachGlobalExpression.global_exp_id,each_user.userlisteners_id))
                globalExpState = {}
                for eachExpression in globalExpressionsRequiredbyListener:
                    # id=1 /Expression EVENT_DESC=SOS /expression_id=3 /expression_op = / expression_value = SOS
                    currentGlobalExpression = DBSession.query(
                        ListenerExpressions).filter_by(
                            id=eachExpression[0]).first()
                    if currentListener.logstate == 1:
                        currentListenerLog = DBSession.query(
                            ListenerLog).filter_by(id=currentLog).first()
                    if currentGlobalExpression is not None:
                        # EVAL EXPRESSIONS
                        currentField = DBSession.query(
                            ListenerFields).filter_by(
                                assign=currentGlobalExpression.expression_id,
                                listeners_id=eachExpression[1]).first()
                        if currentField is not None:
                            currentFieldName = currentField.field
                            operator = "==" if currentGlobalExpression.expression_op == "=" else currentGlobalExpression.expression_op
                            if currentFieldName in kw:
                                utf8 = URLunicode()
                                currentFieldvalue = utf8.decode(
                                    kw[currentFieldName])
                                #evalexpression='kw["'+currentFieldName+'"]'+operator+'"'+currentGlobalExpression.expression_value+'"'
                                evalexpression = '"' + currentFieldvalue + '"' + operator + '"' + currentGlobalExpression.expression_value + '"'
                                isfieldfound = '"' + currentFieldName + '" in kw'
                            else:
                                evalexpression = ""
                                isfieldfound = False
                            # print("EVAL EXPRESSION:{}".format(evalexpression))
                            # print("Field Exists:{} ---> {}".format(isfieldfound,eval(isfieldfound)))
                            # print("Value:{}".format(currentFieldvalue))
                            try:
                                booleanEvalState = eval(evalexpression)
                            except Exception as e:
                                #print("ERROR:{}".format(e))
                                booleanEvalState = False
                            #print("id:{} Exp:{} {} --> {} ".format(eachExpression,currentGlobalExpression.expression,evalexpression,booleanEvalState))
                            globalExpState[
                                eachExpression[0]] = booleanEvalState
                            #
                            #  Listener Log Fields
                            #
                            if currentListener.logstate == 1:
                                newLogFields = ListenerLogFields()
                                newLogFields.field = currentFieldName
                                newLogFields.assigned_to = currentGlobalExpression.expression_id
                                newLogFields.value = currentGlobalExpression.expression_value
                                newLogFields.isfieldfound = eval(isfieldfound)
                                newLogFields.expression = currentGlobalExpression.expression
                                newLogFields.expression_state = booleanEvalState
                                newLogFields.received = kw[currentFieldName]
                                currentListenerLog.fields.append(newLogFields)
                                DBSession.add(newLogFields)
                                DBSession.flush()
                if currentListener.logstate == 1:
                    currentListenerLog = DBSession.query(
                        ListenerLog).filter_by(id=currentLog).first()
                #for k,v in globalExpState.items():
                #print("KEY :{} VALUE:{}".format(k,v))
                ####
                ###   GET IMEI and pluto once
                ####
                currentIMEI = DBSession.query(ListenerFields).filter_by(
                    listeners_id=currentListener.id, assign=1).first()
                if currentIMEI.field in kw:
                    imei = kw[currentIMEI.field]
                else:
                    imei = ""
                #print("IMEI:{}".format(imei))
                pluto = Rest()
                parameters = {}
                parameters['imei'] = imei
                venusTicket = ""
                attended_state = "N"
                sound = 1
                imeiData = pluto.get(
                    app_globals.domainpluto + "/services/imeiInfo", parameters)
                for eachActiveUser in activeListenerUsers:
                    #print("{} {}".format(eachActiveUser['id'],eachActiveUser['user_name']))
                    toEvalUserTriggers = DBSession.query(
                        UserTriggers).filter_by(
                            listener_users_id=eachActiveUser['id']).all()
                    for eachEvalTriggers in toEvalUserTriggers:
                        priority = eachEvalTriggers.priority

                        globalExpToEval = DBSession.query(
                            UserGlobalExp).filter_by(
                                usertriggers_id=eachEvalTriggers.id).all()
                        sumOfexpressionsResult = True
                        for eachGlobalExpToEval in globalExpToEval:
                            #print("Expression:{} --> {}".format(eachGlobalExpToEval.global_exp_id,globalExpState[eachGlobalExpToEval.global_exp_id]))
                            k = eachGlobalExpToEval
                            if globalExpState[eachGlobalExpToEval.
                                              global_exp_id] == False:
                                sumOfexpressionsResult = False
                                break
                        encoded = eachEvalTriggers.expression.encode('utf8')
                        #print("Global Expression:{} Traffic -->: {}".format(encoded,sumOfexpressionsResult))
                        currentUserFiltersExpression = ''
                        ####################
                        #                  #
                        # Checar el valor  #
                        # de abajo         #
                        ####################
                        userTriggerExpressionState = True
                        currentUserFilters = DBSession.query(
                            UserFilters).filter_by(
                                user_trigger_id=eachEvalTriggers.id).first()
                        if currentUserFilters is not None:
                            eventCounter = currentUserFilters.counter + 1
                            currentUserFiltersExpression = currentUserFilters.expression
                            senTicketVenusExp = currentUserFilters.reset_expression
                            #### Checar

                            #print("UserFilters ID: {} For this group{} Eval:{} --->{}".format(currentUserFilters.id,eachActiveUser['user_name'],currentUserFiltersExpression,userTriggerExpressionState))
                            #print("Imei:{}".format(imei))
                            #print("send to discarded when: {}".format(currentUserFiltersExpression))
                            #print("Send Ticket to venus when:{}".format(senTicketVenusExp))

                        else:
                            userTriggerExpressionState = True
                            currentUserFiltersExpression = 'Not Defined'
                        #
                        # Listener Log Users
                        #
                        if currentListener.logstate == 1:
                            newLogUsers = ListenerLogUsers()
                            newLogUsers.user_name = eachActiveUser['user_name']
                            newLogUsers.trigger_expr = eachEvalTriggers.expression
                            newLogUsers.trigger_expr_state = sumOfexpressionsResult
                            newLogUsers.filter_expr = currentUserFiltersExpression
                            newLogUsers.filter_expr_state = userTriggerExpressionState
                            currentListenerLog.users.append(newLogUsers)
                            DBSession.add(newLogUsers)
                            DBSession.flush()
                            Message.post("logListener", 'NEW' + "|")
                        if sumOfexpressionsResult and userTriggerExpressionState:
                            ################
                            # CHECK REPEAT only if there are filters to evaluete #
                            ################
                            if currentUserFilters is not None:
                                venusTicket = ''
                                localtz = 'America/Mexico_City'
                                oper_localtime = datetime.now(
                                    pytz.timezone(localtz))
                                logImeiEvent = DBSession.query(
                                    logImei).filter_by(
                                        imei=imei,
                                        event_desc=eachEvalTriggers.
                                        expression[11:],
                                        group_name=eachActiveUser['user_name']
                                    ).first()
                                if logImeiEvent is None:
                                    newLogImei = logImei()
                                    newLogImei.imei = imei
                                    newLogImei.event_desc = eachEvalTriggers.expression[
                                        11:]
                                    newLogImei.group_name = eachActiveUser[
                                        'user_name']
                                    newLogImei.counter = 1
                                    newLogImei.hour = datetime.utcnow().hour
                                    newLogImei.hour_counter = 1
                                    newLogImei.weekday = oper_localtime.strftime(
                                        "%A")
                                    newLogImei.user_filters_id = currentUserFilters.id
                                    hour = oper_localtime.strftime("%H:%M")
                                    if hour >= "06:00" and hour <= "12:00":
                                        newLogImei.morning = 1
                                    else:
                                        if hour >= "12:00" and hour <= "18:00":
                                            newLogImei.afternoon = 1
                                        else:
                                            if hour >= "18:00" and hour <= "23:59":
                                                newLogImei.night = 1
                                            else:
                                                if hour >= "00:00" and hour <= "06:00":
                                                    newLogImei.early_morning = 1
                                    DBSession.add(newLogImei)
                                else:
                                    time_stamp = logImeiEvent.time_stamp
                                    time_diff = datetime.utcnow() - time_stamp
                                    days_difference = time_diff.days
                                    #print("Time difference since last time stamp in days:{}".format(time_diff.days))
                                    if logImeiEvent.hour == datetime.utcnow(
                                    ).hour:
                                        logImeiEvent.hour_counter += 1
                                        if logImeiEvent.hour_counter > 15:
                                            #send to Venus
                                            venus = Rest()
                                            venusUrl = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str(
                                                imeiData['client_id']
                                            ) + "&last_report=" + str(
                                                imeiData['last_report']
                                            ) + "&folio=0" + "&imei=" + imei + "&comm=" + "Se detecto una inconcistencia en las alertas"
                                            res = requests.get(venusUrl)
                                            if res is not None:
                                                response = res.json()
                                                if 'Ticket' in response:
                                                    venusTicket = response[
                                                        'Ticket']
                                    else:
                                        logImeiEvent.hour = datetime.utcnow(
                                        ).hour
                                        logImeiEvent.hour_counter = 1
                                    if days_difference > 0:
                                        logImeiEvent.morning = 0
                                        logImeiEvent.afternoon = 0
                                        logImeiEvent.night = 0
                                        logImeiEvent.early_morning = 0
                                        logImeiEvent.counter = 1
                                        logImeiEvent.weekday = oper_localtime.strftime(
                                            "%A")
                                        logImeiEvent.time_stamp = datetime.utcnow(
                                        )
                                    else:
                                        logImeiEvent.counter = logImeiEvent.counter + 1
                                        hour = oper_localtime.strftime("%H:%M")
                                        if hour >= "06:00" and hour <= "12:00":
                                            logImeiEvent.morning += 1
                                        else:
                                            if hour >= "12:00" and hour <= "18:00":
                                                logImeiEvent.afternoon += 1
                                            else:
                                                if hour >= "18:00" and hour <= "23:59":
                                                    logImeiEvent.night += 1
                                                else:
                                                    if hour >= "00:00" and hour <= "06:00":
                                                        logImeiEvent.early_morning += 1
                                        logImeiEvent.weekday = oper_localtime.strftime(
                                            "%A")
                                        newLogExpression = "logImeiEvent." + currentUserFiltersExpression
                                        evalnewLogExp = eval(newLogExpression)
                                        userTriggerExpressionState = True
                                        #print("EXPRESSION REJECTED:{} --->  {}".format(newLogExpression,evalnewLogExp))
                                        if evalnewLogExp:
                                            attended_state = "R"
                                            #if venusTicket=='':

                                            #else:
                                            #    attended_state = "N"
                                DBSession.flush()

                            # resetExpText=currentUserFilters.reset_expression
                            # #print("Reset exp:{}".format(resetExpText))
                            # resetExpText=resetExpText.replace("=","==")
                            # resetExpression=eval(resetExpText)
                            # if resetExpression:
                            #     eventCounter=0
                            # if sumOfexpressionsResult:
                            #     currentUserFilters.counter=eventCounter

                            ################
                            # END REPEAT   #
                            ################

                            #CREATE TRAFFIC FOR THE USER
                            currentListenerFields = DBSession.query(
                                ListenerFields).filter_by(
                                    listeners_id=currentListener.id).all()
                            mapper = {}
                            for eachListenerField in currentListenerFields:
                                if eachListenerField.assign != 0:
                                    mapper[eachListenerField.
                                           assign] = eachListenerField.field

                            newTraffic = Traffic()
                            sound = eachEvalTriggers.sound
                            #print("SOUND: {}".format(sound))
                            newTraffic.attended_state = attended_state
                            if imeiData["error"] == "ok":
                                newTraffic.user_name = imeiData['application']
                            if 1 in mapper:
                                newTraffic.imei = kw[mapper[1]]
                            if 2 in mapper:
                                if kw[mapper[2]] == "":
                                    newTraffic.event_id = 0
                                else:
                                    newTraffic.event_id = kw[mapper[2]]
                            if 3 in mapper:
                                newTraffic.event_desc = kw[mapper[3]]
                            else:
                                eventsid = kw[mapper[2]]
                                events = DBSession.query(Events).filter_by(
                                    event_id=eventsid).first()
                                if events is not None:
                                    newTraffic.event_desc = events.event_desc
                                else:
                                    newTraffic.event_desc = ""
                            if 4 in mapper:
                                newTraffic.latitude = kw[mapper[4]]
                            if 5 in mapper:
                                newTraffic.longitude = kw[mapper[5]]
                            if 6 in mapper:
                                if kw[mapper[6]] == "":
                                    speed = 0
                                else:
                                    speed = int(float(kw[mapper[6]]))
                                newTraffic.speed = speed
                            if 7 in mapper:
                                newTraffic.azimuth = kw[mapper[7]]
                            if 8 in mapper:
                                newTraffic.valid = kw[mapper[8]]
                            if 9 in mapper:
                                newTraffic.event_time = kw[mapper[9]]
                            if 10 in mapper:
                                newTraffic.client_id = kw[mapper[10]]
                            if 11 in mapper:
                                vehicleData = kw[mapper[11]]
                                vehicleCheck = vehicleData.replace(" ", "")
                                if len(vehicleData) > 0:
                                    newTraffic.vehicle = vehicleData
                                else:
                                    if imeiData["error"] == "ok":
                                        if imeiData[
                                                "brand"] is not None and imeiData[
                                                    "model"] is not None:
                                            newTraffic.vehicle = imeiData[
                                                "brand"] + ' ' + imeiData[
                                                    "model"] + ' '
                            else:
                                if imeiData["error"] == "ok":
                                    if imeiData[
                                            "brand"] is not None and imeiData[
                                                "model"] is not None:
                                        newTraffic.vehicle = imeiData[
                                            "brand"] + ' ' + imeiData[
                                                "model"] + ' '

                            if 12 in mapper:
                                if kw[mapper[12]] == '':
                                    kw[mapper[12]] = '0'
                                newTraffic.voltage = kw[mapper[12]]
                            if 13 in mapper:
                                newTraffic.internal_id = kw[mapper[13]]
                            if 14 in mapper:
                                if kw[mapper[14]] == '':
                                    newTraffic.mcc = 0
                                else:
                                    newTraffic.mcc = kw[mapper[14]]
                            if 15 in mapper:
                                if kw[mapper[15]] == '':
                                    newTraffic.mnc = 0
                                else:
                                    newTraffic.mnc = kw[mapper[15]]
                            if 16 in mapper:
                                if kw[mapper[16]] == '':
                                    newTraffic.lac = 0
                                else:
                                    newTraffic.lac = kw[mapper[16]]
                            if 17 in mapper:
                                if kw[mapper[17]] == '':
                                    newTraffic.cellid = 0
                                else:
                                    newTraffic.cellid = kw[mapper[17]]
                            newTraffic.user = eachActiveUser['user_name']
                            newTraffic.priority = priority
                            localtz = 'America/Mexico_City'
                            if 9 in mapper:
                                cuda = kw[mapper[9]]
                                cuda = cuda[:19]
                                dateconversion = datetime.strptime(
                                    cuda, '%Y-%m-%dT%H:%M:%S')
                                oper_utc = arrow.get(dateconversion)
                                oper_localtime = oper_utc.to(localtz)
                            else:
                                oper_localtime = datetime.now(
                                    pytz.timezone(localtz))
                            nd = "Evento no definido"
                            if 3 in mapper:
                                nd = kw[mapper[3]]
                                nd = nd.lstrip().rstrip()
                                if len(nd) == 0:
                                    nd = "Evento no definido:" + newTraffic.event_desc
                            else:
                                eventsid = kw[mapper[2]]
                                events = DBSession.query(Events).filter_by(
                                    event_id=eventsid).first()
                                if events is not None:
                                    nd = events.event_desc
                            #print("-------->>> user:{}".format(eachActiveUser['user_name']))

                            ############################
                            # logImeiRecord = DBSession.query(logImei).filter_by(imei=parameters['imei'],event_desc=nd,group_name=eachActiveUser['user_name']).first()
                            # if mapper[2] in kw:
                            #     if kw[mapper[2]]=="99":
                            #         logImeiRecord = None
                            # if logImeiRecord is not None:
                            #     #print("FOUND!!!!->{}".format(eachActiveUser['user_name']))
                            #     newTraffic.attended_state = "R"
                            #     hour = oper_localtime.strftime("%H:%M")
                            #     if hour >= "06:00" and hour <= "12:00":
                            #         logImeiRecord.morning += 1
                            #     else:
                            #         if hour >= "12:00" and hour <= "18:00":
                            #             logImeiRecord.afternoon += 1
                            #         else:
                            #             if hour >= "18:00" and hour <= "23:59":
                            #                 logImeiRecord.night += 1
                            #             else:
                            #                 if hour >= "00:00" and hour <= "06:00":
                            #                     logImeiRecord.early_morning += 1
                            #     logImeiRecord.counter=logImeiRecord.counter+1
                            #     if logImeiRecord.counter>100:
                            #         logImeiRecord.counter=0
                            #         logImeiRecord.morning = 0
                            #         logImeiRecord.afternoon = 0
                            #         logImeiRecord.night = 0
                            #         logImeiRecord.early_morning = 0
                            #         logImeiRecord.group_name = eachActiveUser['user_name']
                            #     if logImeiRecord.counter==2:
                            #         if 'client_id' in imeiData and 'last_report' in imeiData:
                            #             venus=Rest()
                            #             venusUrl = "http://venus.gpscontrol.com.mx/dispatch/create_ticket?client_id=" + str(imeiData['client_id']) + "&last_report=" + str(imeiData['last_report']) + "&folio=0" + "&imei=" + imei + "&comm=" + "Ignorar Rodo... Cierrala,.. Se detecto una inconcistencia en las alertas"
                            #             res = requests.get(venusUrl)
                            #             if res is not None:
                            #                 response=res.json()
                            #                 if 'Ticket' in response:
                            #                     venusTicket = response['Ticket']
                            #
                            # else:
                            #     nd = "Evento no definido"
                            #     if 3 in mapper:
                            #         nd = kw[mapper[3]]
                            #         nd = nd.lstrip().rstrip()
                            #         if len(nd) == 0:
                            #             nd = "Evento no definido:" + newTraffic.event_desc
                            #     else:
                            #         eventsid = kw[mapper[2]]
                            #         events = DBSession.query(Events).filter_by(event_id=eventsid).first()
                            #         if events is not None:
                            #             nd = events.event_desc
                            #     newLogImei=logImei()
                            #     newLogImei.imei=parameters['imei']
                            #     newLogImei.event_desc=nd
                            #     newLogImei.counter=1
                            #     newLogImei.weekday = oper_localtime.strftime("%A")
                            #     newLogImei.group_name = eachActiveUser['user_name']
                            #     DBSession.add(newLogImei)
                            #
                            ############################

                            DBSession.add(newTraffic)
                            DBSession.flush()
                            #print("Sound: {}".format(sound))
                            if newTraffic.attended_state == "N":
                                Message.post(
                                    "trafficlistener_" +
                                    eachActiveUser['user_name'],
                                    'RELOAD' + "|" + str(sound))
                            elif newTraffic.attended_state == "R":
                                Message.post(
                                    "rejectedlistener_" +
                                    eachActiveUser['user_name'],
                                    'RELOAD' + "|" + str(sound))
                            if venusTicket != "":
                                searchticket = DBSession.query(
                                    Tickets).filter_by(
                                        ticket=venusTicket).first()
                                if searchticket is None:
                                    newTickets = Tickets()
                                    newTickets.traffic_id = newTraffic.id
                                    newTickets.ticket = venusTicket
                                    newTickets.comment = "Se detecto una inconcistencia en las alertas"
                                    DBSession.add(newTickets)
                                    DBSession.flush()

        return 'ok'
Esempio n. 16
0
def read_email_from_gmail(FROM_EMAIL, FROM_PWD, SMTP_SERVER, SMTP_PORT, imei,
                          url, event_id, event_desc, client_id, client_name,
                          latitude, longitude):

    mail = imaplib.IMAP4_SSL(SMTP_SERVER, SMTP_PORT)
    mail.login(FROM_EMAIL, FROM_PWD)
    mail.select('inbox')

    #
    # ("EMAIL:{} password:{}".format(FROM_EMAIL,FROM_PWD))
    #mail.select(readonly=1)

    typ, data = mail.uid('SEARCH', None, '(UNSEEN)')

    for num in data[0].split():
        typ, data = mail.uid('fetch', num, '(RFC822)')
        for response in data:
            if isinstance(response, tuple):
                original = email.message_from_string(
                    response[1].decode("utf-8"))
                # print(original.keys())
                [
                    'Delivered-To', 'Received', 'X-Received', 'ARC-Seal',
                    'ARC-Message-Signature', 'ARC-Authentication-Results',
                    'Return-Path', 'Received', 'Received-SPF',
                    'Authentication-Results', 'DKIM-Signature',
                    'X-Google-DKIM-Signature', 'X-Gm-Message-State',
                    'X-Google-Smtp-Source', 'MIME-Version', 'X-Received',
                    'Date', 'List-Unsubscribe', 'X-Google-Id', 'X-Feedback-Id',
                    'X-No-Auto-Attachment', 'Message-ID', 'Subject', 'From',
                    'To', 'Content-Type'
                ]
                #print("original:{}",format(original))
                # print("From:{}".format(original['From']))
                # print("Subject:{}".format(original['Subject']))
                # print("Content:{}".format(original['Content-Type']))
                # print("ID:{}".format(original['Message-ID']))
                imageHtml = ''
                htmlBody = "<p>"
                if original.is_multipart():
                    #print("Multipart!")
                    for part in original.walk():
                        if part.get_content_maintype() == 'multipart':
                            continue
                        if part.get('Content-Disposition') is None:
                            continue
                        filename = part.get_filename()
                        #print("File Name:{}".format(filename))

                        if filename is not None and (
                                filename.find('.jpeg') > 0
                                or filename.find('.png') > 0
                                or filename.find('.jpg') > 0):
                            image = part.get_payload(decode=True)
                            bencodedString = base64.b64encode(image)
                            encodedString = bencodedString.decode("utf-8")
                            #print("IMAGE:{}".format(encodedString))
                            fp = '<img src="data:image/png;base64, '
                            sp = '" alt="Image" />'
                            imageHtml = imageHtml + fp + encodedString + sp
                    for part in original.get_payload():

                        if part.get_content_maintype() == 'text':
                            body = part.get_payload(decode=True)
                            #print("Body:{}".format(repr(body)))
                            #print("Type:{}".format(type (body)))
                            text = body.decode('utf-8', 'ignore')
                            #print("TEXT:{}".format(text))
                            #if text.find("[<email.message.Message object")<0:
                            for lines in text.split('\r\n'):
                                htmlBody = htmlBody + lines + '<br>'
                            htmlBody = htmlBody + "</p>"
                    utc = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
                    msg = htmlBody + imageHtml
                    query = DBSession.query(EmailData).filter_by(
                        email_id=original['Message-ID']).first()
                    if query is None:
                        newitem = EmailData()
                        newitem.imei = imei
                        newitem.email_id = original['Message-ID']
                        newitem.time_stamp = utc
                        newitem.data = msg
                        DBSession.add(newitem)
                        DBSession.flush()
                        transaction.commit()
                    #url=url+event_desc
                    data = {
                        'client_id': client_id,
                        'vehicle': client_name,
                        'event_id': event_id,
                        'event_desc': event_desc,
                        'rdatetime': utc,
                        'imei': imei,
                        'latitude': str(latitude),
                        'longitude': str(longitude)
                    }
                    #print("URL:{}".format(url+event_desc))
                    #print("Event Desc:{}".format(event_desc))
                    resp = requests.get(url + event_desc, params=data)
                    #print(resp.text)
                else:
                    body = original.get_payload()
                    text = str(body)

                    for lines in text.split('\r\n'):
                        htmlBody = htmlBody + lines + '<br>'
                    htmlBody = htmlBody + "</p>"
                    query = DBSession.query(EmailData).filter_by(
                        email_id=original['Message-ID']).first()
                    if query is None:
                        newitem = EmailData()
                        newitem.imei = imei
                        newitem.email_id = original['Message-ID']
                        newitem.data = htmlBody
                        DBSession.add(newitem)
                        DBSession.flush()
                        transaction.commit()
        mail.store(num, '+FLAGS', '\Seen')
        mail.uid("STORE", num, '+FLAGS', '\Seen')
    mail.close()
    mail.logout()
Esempio n. 17
0
    def dispatch(self, **kw):
        error = {"Error": "none"}
        jobID = kw['jobid']
        jobDate = kw['jobdate']
        jobDesc = kw['jobdesc']
        state = kw['state']
        name = kw['name']
        latitude = kw['latitude']
        longitude = kw['longitude']
        print("ID:{}".format(jobID))
        print("date:{}".format(jobDate))
        print("Description:{}".format(jobDesc))
        print("name:{}".format(name))
        print("state:{}".format(state))
        print("latitude:{}".format(latitude))
        print("longitude:{}".format(longitude))
        if state != "Assigned":
            dday = jobDate[8:10]
            ntime = jobDate[16:24]
            dyear = jobDate[11:15]
            dmonth = a2m(jobDate[4:7])
            newdate = dyear + "/" + dmonth + "/" + dday
            print("time:{}".format(jobDate[16:24]))
            sjobdate = newdate + " " + jobDate[16:24]
            print("S Date:{}".format(sjobdate))
            jobdate = datetime.strptime(sjobdate, '%Y/%m/%d %H:%M:%S')
            # store data in Job Table
            query = DBSession.query(Jobs).filter_by(gate_user=name,
                                                    job_id=jobID).first()
            if query is None:
                newitem = Jobs()
                newitem.job_id = jobID
                newitem.job_date = jobdate
                newitem.job_description = jobDesc
                newitem.job_state = state
                newitem.latitude = float(latitude)
                newitem.longitude = float(longitude)
                newitem.last_update = datetime.now()
                newitem.gate_user = name
                DBSession.add(newitem)
                DBSession.flush()
            else:
                query.job_date = jobdate
                query.job_description = jobDesc
                query.job_state = state
                query.latitude = float(latitude)
                query.longitude = float(longitude)
                query.last_update = datetime.now()
                DBSession.flush()

            print("Date:{}".format(newdate))
            query = DBSession.query(Smartphones).filter_by(
                gate_user=name).first()
            if query is not None:
                # Send Message
                data_message = {
                    "command": "message",
                    "title": newdate,
                    "body": jobDesc
                }
                # apikey=os.environ.get('FCM_KEY') or "AIzaSyAw5EFGDer7-PEuXXMzYNPwla9RP2SVqz4"
                apikey = "AIzaSyCxiYxZsSqKGaJ4NM7vM4yP9d0BYlQcNmo"
                push_service = FCMNotification(api_key=apikey)
                resp = push_service.notify_single_device(
                    registration_id=query.token, data_message=data_message)
                # Update Data
                print("Send newjob")
                data_message = {
                    "command": "newjob",
                    "jobnumber": jobID,
                    "jobdate": newdate,
                    "jobtime": ntime,
                    "jobdesc": jobDesc,
                    "joblat": latitude,
                    "joblon": longitude,
                    "jobstate": state
                }
                push_service = FCMNotification(api_key=apikey)
                resp = push_service.notify_single_device(
                    registration_id=query.token, data_message=data_message)
            Message.post("Smartphonesfrom", 'RELOAD' + "|")
        return error
Esempio n. 18
0
 def addLog(cls, **kw):
     newLog = cls(**kw)
     DBSession.add(newLog)
     DBSession.flush()