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 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)
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 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 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)
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')
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")
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="")
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 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 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 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 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])
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 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 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 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 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 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 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 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 location(self, **kw): error = {"Error": "none"} print("Updating location") if not ('imei' in kw and 'account' in kw and 'latitude' in kw and 'longitude' in kw and 'speed' in kw and 'battery' in kw and 'accuracy' in kw and 'azimuth' in kw and 'valid' in kw): error = {"Error": "Parametros faltantes"} else: query = DBSession.query(Smartphones).filter_by( account=kw['account'], imei=kw['imei']).first() if query is not None: query.lastupdate = datetime.utcnow() query.latitude = float(kw['latitude']) query.longitude = float(kw['longitude']) query.speed = kw['speed'] query.accuracy = float(kw['accuracy']) query.battery = kw['battery'] DBSession.flush() else: error = {"Error": "Parametros faltantes"} print(error) return error
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 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 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 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