def badge(): if request.identity is None: counter = 0 else: identity = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=identity).first() counter = DBSession.query(Notification).filter_by(user_id=user.user_id, attended_state="N").count() return '' if counter == 0 else str(counter)
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))
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
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')
def updateBadge(self, **kw): record = kw['record'] user = DBSession.query(User).filter_by( user_name=request.identity['repoze.who.userid']).first() notification = DBSession.query(Notification).filter_by( id=record).first() if notification is not None: notification.attended_state = "Y" notification.attended_time = datetime.datetime.utcnow() DBSession.flush() counter = DBSession.query(Notification).filter_by( user_id=user.user_id, attended_state='N').count() return dict(badge='' if counter == 0 else str(counter))
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="")
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)
def get_query(self): ''' Returns query with all the objects :return: ''' if not self.query: if self.sord == "asc": self.query = DBSession.query(self.model_class).order_by( asc(self.sidx)) else: self.query = DBSession.query(self.model_class).order_by( desc(self.sidx)) #self.query = self.session.query(self.model_class) return self.query
def monitor(self): # 1 --> Look Traffic Detail # 2 --> Put Pending # 3 --> Create Ticket # 4 --> Finalize Traffic # 5 --> C5 Alarm # 6 --> Add Image # 7 --> Telefonica Location imageArray=[] for operation in range(1,8): operation_name=app_globals.trafficOperation[operation] line_chart = pygal.HorizontalBar() line_chart.title = operation_name print("Operation:{}".format(operation_name)) qry = DBSession.query(OperatorLog).filter(and_(OperatorLog.time_stamp <= '2018-08-30', OperatorLog.time_stamp >= '2018-08-01', OperatorLog.operation == operation)).order_by(asc(OperatorLog.time_stamp)).all() index= {} for item in qry: if item.user_name in index: index[item.user_name]+=1 else: index[item.user_name]=1 sort_dic = [(k, index[k]) for k in sorted(index, key=index.get, reverse=True)] for key,value in sort_dic: print("{}:{}".format(key,value)) line_chart.add(key, value) imageArray.append(line_chart.render_data_uri()) return dict(graph_data=imageArray)
def get_all(self): pets = [] allrecords = DBSession.query(Pets).all() for item in allrecords: pets.append(dict(id=item.id, name=item.name, breed=item.breed)) print(item.name) return dict(pets=pets)
def post_delete(self, record): print("DELETE Id: {} ".format(record)) query = DBSession.query(Pets).filter_by(id=int(record)).first() if query is not None: DBSession.delete(query) DBSession.flush() return dict(id=record)
def updateTrafficStatus(self, **kw): traffic_id = kw['traffic_id'] state = kw['state'] comment = kw['comment'] if kw['false_alarm'] == "true": false_alarm = 1 else: false_alarm = 0 alert = DBSession.query(Traffic).filter_by(id=traffic_id).first() if alert is not None: alert.attended_state = state alert.comment = comment alert.false_alarm = false_alarm if state == "A": alert.attended_time = datetime.datetime.utcnow() if state == "P": OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.putPending, traffic_id=traffic_id) alert.pending_time = datetime.datetime.utcnow() if state == "C": OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.finalizedTraffic, traffic_id=traffic_id) alert.closed_time = datetime.datetime.utcnow() DBSession.flush() else: print("NOT FOUND!!!") if not "group" in kw: abort(status_code=500, detail="Traffic error, parameter (group) not found") else: gaugeParameters = Statistics() currentGauge=gaugeParameters.byUser(kw["group"]) Message.post("trafficlistener_" + kw["group"], 'REPAINT' + "|") return currentGauge
def images(self, **kw): list = [] myimages = DBSession.query(Assets).all() for every_picture in myimages: list.append(every_picture.data) print("len:{}".format(len(every_picture.data))) return dict(list=list)
def index(self, **kw): if not "user" in kw: abort(status_code=500, detail="Traffic error, parameter (user) not found") else: gaugeParameters = Statistics() currentGauge=gaugeParameters.byUser(kw["groups"]) currentComments = [] all = DBSession.query(helpComment).all() for item in all: currentComments.append(dict(id=item.id, hcomment=item.comment)) currentGauge["group"]=kw["groups"] currentGauge["user"] = kw["user"] currentGauge["list"]=currentComments if 'application_id' in kw: r=requests.get('https://sun.dudewhereismy.com.mx/services/utc_zone?application_id='+kw["application_id"]) parameters = {} parameters["application_id"] = kw["application_id"] newSession = requests.session() mkw = {'params': parameters,'verify': False, 'timeout': 10} response = newSession.get('https://sun.dudewhereismy.com.mx/services/utc_zone', **mkw) values = response.json() if "error" in values: if values['error']=='ok': currentGauge["tz"] =values["utc_zone"] #print("TZ:{}".format(currentGauge["tz"])) else: currentGauge["tz"] = "America/Mexico_City" else: currentGauge["tz"] = "America/Mexico_City" #for k,v in kw.items(): # print("{} {}".format(k,v)) #print("**************> GROUPS:{}".format(kw['groups'])) return currentGauge
def updatedispatch(self, **kw): error = {"Error": "none"} #### ## ggs = "testggs.dwim.mx" ### GPS GATE SERVER DEFINITION ## #### imei = kw['imei'] type = kw['type'] jobNumber = kw['jobnumber'] if 'jobcomment' in kw: jobComment = kw['jobcomment'] else: jobComment = "" latitude = kw['latitude'] longitude = kw['longitude'] print("######### Update Dispatch ##########") print(imei) print(type) print("JOb:{}".format(jobNumber)) print(jobComment) print(latitude) print(longitude) query = DBSession.query(Jobs).filter_by(job_id=jobNumber).first() if query is not None: query.comment = jobComment DBSession.flush() query = DBSession.query(Smartphones).filter_by(imei=imei).first() if query is not None: print(query.gate_user) print(query.gate_password) print(query.gate_app) if type == "D": updateJob2Dispatched(ggs, query.gate_user, query.gate_password, query.gate_app, jobNumber, float(latitude), float(longitude)) if type == "A": updateJob2Active(ggs, query.gate_user, query.gate_password, query.gate_app, jobNumber, float(latitude), float(longitude)) if type == "F": updateJob2Finished(ggs, query.gate_user, query.gate_password, query.gate_app, jobNumber, float(latitude), float(longitude), jobComment) return error
def put(self, name, breed, id): query = DBSession.query(Pets).filter_by(id=int(id)).first() if query is not None: query.name = name query.breed = breed DBSession.flush() print("PUT Name: {} Breed: {} id:".format(name, breed, id)) return dict(name=name, breed=breed, id=id)
def perm(name): identity = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=identity).first() perm = Permission.exist(u''+name+'',user.groups) if perm == "si": return True else: return False
def getDynamicTemplate(self, **kw): list=[] #listener=kw['listener'] currentevent = DBSession.query(Events).all() for element in currentevent: list.append({"FIELD1": element.event_id, "FIELD2": element.event_desc}) eventtemplate = render_template({"list": list}, "mako", 'pythondispatchms.templates.traffic.eventstemplate') return dict(eventtemplate=eventtemplate)
def display(self, **kw): if 'job' in kw: all = DBSession.query(ReservedImages).filter_by( job_id=kw["job"]).all() st = "" for item in all: st = st + str(item.id) + "," if len(st) > 0: st = st[:-1] print(st) query = DBSession.query(ReservedImages).filter_by( job_id=kw["job"]).first() if query is not None: encoded_string = str(b64encode(query.image), 'utf-8') return dict(jobimage=encoded_string, elements=st, currentjob=kw["job"]) return dict(jobimage="", elements="", currentjob="")
def getimage(self, **kw): print("getimage") if 'id' in kw and 'job' in kw: query = DBSession.query(ReservedImages).filter_by( job_id=kw["job"], id=kw['id']).first() if query is not None: print("found") encoded_string = str(b64encode(query.image), 'utf-8') return dict(image=encoded_string) return dict(image="")
def csv(self): list = [] allrecords = DBSession.query(User).all() for item in allrecords: list.append( str(item.user_id) + "," + item.user_name + "," + item.email_address + "," + item.display_name + '\n') file_name = ExportCVS.create(list, "users", "/test/csv") print("file_name:{}".format(file_name)) return dict(file_name=file_name)
def taskEmail(i): #print("thread {} start".format(i)) emailServices = DBSession.query(EmailService).all() for everyitem in emailServices: # SMTP_SERVER = "imap.gmail.com" # SMTP_PORT = 993 url = host_prefix + host + "/listener/" read_email_from_gmail(everyitem.email, everyitem.password, everyitem.smpt_server, everyitem.port, everyitem.imei, url, everyitem.event_id, everyitem.event_desc, everyitem.client_id, everyitem.client_name, everyitem.latitude, everyitem.longitude)
def checkTraffic(self, **kw): #print("user:{}".format(kw['user'])) # 0 - open # 1 - dedicated ok # 2 - dedicated nok status=2 query = DBSession.query(Traffic).filter_by(id=kw['traffic_id']).first() if query is not None: if query.dedicated_id!=0: ded=DBSession.query(Dedicated).filter_by(id=query.dedicated_id).first() if ded is not None: rol=ded.role ded = DBSession.query(Roles).filter_by(name=rol).first() if ded is not None: for item in ded.users: #print(item.user_name) if item.user_name==kw['user']: #print("bingo!") status=1 else: status=0 return dict(status=status)
def release_license(self, **kw): error = {"Error": "none"} print("Release License") if not ('imei' in kw and 'account' in kw): error = {"Error": "Parametros faltantes"} else: item = DBSession.query(Smartphones).filter_by( account=kw['account'], imei=kw['imei']).first() if item is not None: DBSession.delete(item) DBSession.flush() Message.post("Smartphonesfrom", 'RELOAD' + "|") print(error) return error
def getOperatorLog(self, **kw): localtz = kw['tz'] operatorlog = [] operlog = DBSession.query(OperatorLog).filter_by(traffic_id=kw['traffic_id']).order_by(asc(OperatorLog.time_stamp)).all() for operitem in operlog: oper_utc = arrow.get(operitem.time_stamp) oper_localtime = oper_utc.to(localtz) cabus="" if len(operitem.ticket)>1: cabus=":" +operitem.ticket operatorlog.append(str(oper_localtime) + ":" + operitem.user_name + ":" + operitem.group_name + ":" + app_globals.trafficOperation[operitem.operation]+cabus) return dict(operatorlog=operatorlog)
def getPlataformPosition(self, **kw): OperatorLog.addLog(user_name=kw["user"], group_name=kw["group"], operation=app_globals.telefonicaLocation, traffic_id=kw['traffic_id']) traffic_id=kw['traffic_id'] error = "No puedo conectar con plataforma" position = DBSession.query(Traffic).filter_by(id=traffic_id).first() if position is not None: print("IMEI:{}".format(position.imei)) pluto = Rest() parameters = {} parameters['imei'] = position.imei imei=position.imei imeiData = pluto.get(app_globals.domainpluto + "/services/imeiInfo", parameters) latitude='0' if 'server' in imeiData: if imeiData['server'] == 1: r = requests.get("http://server1.gpscontrol.com.mx/webservice/api/location/getbyimei?imei=" + imei, auth=('lusa', '1234')) json_object = r.json() if len(json_object) > 0: latitude = json_object[0]['latitude'] longitude = json_object[0]['longitude'] heading = json_object[0]['heading'] error='ok' elif imeiData['server'] == 2: r = requests.get( "http://server2.gpscontrol.com.mx/webservice/api/location/getbyimei?imei=" + imei, auth=('lusa', '1234')) json_object = r.json() if len(json_object) > 0: latitude = json_object[0]['latitude'] longitude = json_object[0]['longitude'] heading = json_object[0]['heading'] error = 'ok' elif imeiData['server'] == 3: r = requests.get("http://plataforma3.gpscontrol.com.mx/ms03/location/" + imei, auth=('ms03', 'qazwsxedc')) json_object = r.json() if len(json_object) > 0: latitude = json_object[0]['latitude'] longitude = json_object[0]['longitude'] speed = json_object[0]['speed'] heading = json_object[0]['azimut'] error = 'ok' return dict(error=error, latitude=latitude, longitude=longitude)
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")
def loadDetail(self): 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) window = query.all() records = [] fields = [] for rw in window: for column in rw.__table__.columns: #print(column.name) fields.append(getattr(rw, column.name)) records.append({ self.indexkey: str(getattr(rw, self.indexkey)), 'cell': fields }) fields = [] #print(records) return dict(rows=records)
def sendMsg(self, **kw): error = {"Error": "none"} print("") print(kw["title"]) print(kw["subtitle"]) query = DBSession.query(Smartphones).filter_by(imei=kw['imei']).first() if query is not None: data_message = { "command": "message", "title": kw["title"], "body": kw["subtitle"] } apikey = "AIzaSyCxiYxZsSqKGaJ4NM7vM4yP9d0BYlQcNmo" push_service = FCMNotification(api_key=apikey) resp = push_service.notify_single_device( registration_id=query.token, data_message=data_message) error = {"Error": str(resp)} else: error = {"Error": "Smartphone not found in table"} return error
def getMonitorGraphs(self, **kw): imageArray=[] for operation in range(1,8): operation_name=app_globals.trafficOperation[operation] line_chart = pygal.HorizontalBar() line_chart.title = operation_name print("Operation:{}".format(operation_name)) qry = DBSession.query(OperatorLog).filter(and_(OperatorLog.time_stamp <= kw['end'], OperatorLog.time_stamp >= kw['start'], OperatorLog.operation == operation)).order_by(asc(OperatorLog.time_stamp)).all() index= {} for item in qry: if item.user_name in index: index[item.user_name]+=1 else: index[item.user_name]=1 sort_dic = [(k, index[k]) for k in sorted(index, key=index.get, reverse=True)] for key,value in sort_dic: print("{}:{}".format(key,value)) line_chart.add(key, value) imageArray.append(line_chart.render_data_uri()) print(imageArray[0]) return dict(graph_data=imageArray)