def evalCity(fieldname, **params): if fieldname in FezAlarmFaxChecker().fields: _str = FezAlarmFaxChecker().fields[fieldname][0] else: # city not found -> use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) raise alarmtype = params.get('alarmtype', None) if _str.strip() == '': FezAlarmFaxChecker().fields[fieldname] = ('', 0) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(_str.split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(_str, city.subcities + [city.name], 1) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return for s in _str.split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: FezAlarmFaxChecker().fields[fieldname] = (repl[0], c.id) return if alarmtype.translation(u'_default_city_') in _str.lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: FezAlarmFaxChecker().fields[fieldname] = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) return if _str.startswith('in'): # remove 'in' and plz _str = re.sub(r'in*|[0-9]*', '', _str[2:].strip()) FezAlarmFaxChecker().fields[fieldname] = ( _str, 0) # return original if no match return
def evalCity(fieldname, **params): if fieldname in FezAlarmFaxChecker().fields: _str = FezAlarmFaxChecker().fields[fieldname][0] else: # city not found -> use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) raise alarmtype = None if 'alarmtype' in params: alarmtype = params['alarmtype'] if _str.strip() == '': FezAlarmFaxChecker().fields[fieldname] = ('', 0) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(_str.split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(_str, city.subcities + [city.name], 1) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return for s in _str.split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: FezAlarmFaxChecker().fields[fieldname] = (repl[0], c.id) return if alarmtype.translation(u'_default_city_') in _str.lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: FezAlarmFaxChecker().fields[fieldname] = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) return if _str.startswith('in'): # remove 'in' and plz _str = re.sub(r'in*|[0-9]*', '', _str[2:].strip()) FezAlarmFaxChecker().fields[fieldname] = (_str, 0) # return original if no match return
def get_city(self): # deliver city object if self.get('id.city', '0') != '0': # city found return City.getCities(id=self.get('id.city')) elif self.get('id.city', '0') == '0': # not in list return City(self.get('city', ''), 1, 'osmap', 0, '', '', 0, '') else: return City.getDefaultCity()
def evalCity(field, **params): alarmtype = params.get('alarmtype', None) field.value = (field.value[0], -1) if field.value[0].strip() == '': field.value = ('', -1) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(field.value[0].split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: field.value = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(field.value[0], city.subcities + [city.name], 1) if len(repl) > 0: field.value = (repl[0], city.id) return for s in field.value[0].split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: field.value = (repl[0], c.id) return if alarmtype.translation( u'_default_city_').lower() in field.value[0].lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: field.value = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() field.value = (city.name, city.id) return if field.value[0].startswith('in'): # remove 'in' and plz field.value = (re.sub(r'in*|[0-9]*', '', field.value[0][2:].strip()), field.value[1])
def evalCity(field, **params): alarmtype = params.get('alarmtype', None) field.value = (field.value[0], -1) if field.value[0].strip() == '': field.value = ('', -1) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(field.value[0].split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: field.value = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(field.value[0], city.subcities + [city.name], 1) if len(repl) > 0: field.value = (repl[0], city.id) return for s in field.value[0].split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: field.value = (repl[0], c.id) return if alarmtype.translation(u'_default_city_').lower() in field.value[0].lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: field.value = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() field.value = (city.name, city.id) return if field.value[0].startswith('in'): # remove 'in' and plz field.value = (re.sub(r'in*|[0-9]*', '', field.value[0][2:].strip()), field.value[1])
def getAdminContent(self, **params): """ Deliver admin content of module streets :param params: use given parameters of request :return: rendered template as string """ module = request.view_args['module'].split('/') if len(module) < 2: if City.getDefaultCity(): module.append(u'{}'.format(City.getDefaultCity().id)) else: module.append(u'1') if len(module) == 2: # cities if module[1] == '0': # city list if request.method == 'POST': if request.form.get('action').startswith('detailcity_'): # edit city params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()}) return render_template('admin.streets.city_edit.html', **params) elif request.form.get('action') == 'updatecity': # update existing city if request.form.get('city_id') != 'None': # update city city = City.getCities(id=request.form.get('city_id')) city.name = request.form.get('cityname') city.subcity = request.form.get('subcity') city._dept = request.form.get('department') city.mapname = request.form.get('citymap') city.color = request.form.get('colorname') city.default = request.form.get('citydefault') city.osmid = request.form.get('osmid') city.osmname = request.form.get('osmname') else: # add city city = City(request.form.get('cityname'), request.form.get('department'), request.form.get('citymap'), request.form.get('citydefault'), request.form.get('subcity'), request.form.get('colorname'), request.form.get('osmid'), request.form.get('osmname')) db.session.add(city) db.session.commit() cache.clear() elif request.form.get('action') == 'createcity': # add city params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()}) return render_template('admin.streets.city_edit.html', **params) elif request.form.get('action').startswith('deletecity_'): # delete city db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1])) db.session.commit() self.updateAdminSubNavigation() cache.clear() params.update({'cities': City.getCities()}) return render_template('admin.streets.city_list.html', **params) else: # show city details if request.method == 'POST': if request.form.get('action').startswith('detailstreet_'): # edit street tileserver = {'lat': Settings.get('defaultLat'), 'lng': Settings.get('defaultLng'), 'zoom': Settings.get('defaultZoom'), 'map': Map.getDefaultMap()} params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver}) return render_template('admin.streets_edit.html', **params) elif request.form.get('action') == 'createstreet': # add street tileserver = {'lat': Settings.get('defaultLat'), 'lng': Settings.get('defaultLng'), 'zoom': Settings.get('defaultZoom'), 'map': Map.getDefaultMap()} params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver}) return render_template('admin.streets_edit.html', **params) elif request.form.get('action').startswith('deletestreets_'): # delete street db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1])) db.session.commit() cache.clear() elif request.form.get('action') == 'savestreet': # save street if request.form.get('street_id') != 'None': # update existing street street = Street.getStreets(id=request.form.get('street_id')) street.name = request.form.get('edit_name') street.navigation = request.form.get('edit_navigation') c = request.form.get('edit_cityid').split('_') if len(c) < 2: c.append('') street.cityid = c[0] street.subcity = c[1] street.lat = request.form.get('edit_lat') street.lng = request.form.get('edit_lng') street.zoom = request.form.get('edit_zoom') street.active = request.form.get('edit_active') db.session.commit() #cache.delete_memoized(City.streets) else: # add street c = request.form.get('edit_cityid').split('_') if len(c) < 2: c.append('') # subcity city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0] city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), '')) db.session.commit() cache.clear() try: streets = Street.getStreets(cityid=module[-1]) except AttributeError: streets = [] chars = {} for s in streets: chars[s.name[0].upper()] = 0 params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])}) return render_template('admin.streets.html', **params) return "streets"
def handleEvent(eventname, **kwargs): """ Eventhandler for alarm class :param eventname: name of event :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time :return: all kwargs """ try: from emonitor import app global LASTALARM alarm_fields = dict() stime = time.time() alarmtype = None for t in AlarmType.getAlarmTypes(): if re.search(t.keywords.replace('\r\n', '|'), kwargs.get('text', '')): alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs.get('text', '')) if alarm_fields.get('error'): kwargs['error'] = alarm_fields['error'] del alarm_fields['error'] alarmtype = t break alarm = Alarm(datetime.datetime.now(), '', 1, 0) etime = time.time() _missing = 0 for p in ['time', 'city', 'address', 'key']: if p not in alarm_fields: # test required fields _missing += 1 kwargs['error'] = kwargs.get('error', 'Missing parameter:') + "<br/>- '{}'".format(p) try: t = datetime.datetime.strptime(alarm_fields.get('time')[0], '%d.%m.%Y - %H:%M:%S') except ValueError: t = datetime.datetime.now() alarm.timestamp = t kwargs['fields'] = '' # set evaluated fields from fax for k in alarm_fields: kwargs['fields'] = u'{}\n-{}:\n {}'.format(kwargs.get('fields'), k, alarm_fields[k]) if _missing == 0: # all required parameters found if kwargs.get('mode') != 'test': if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))): os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))) try: shutil.copy2('{incomepath}{filename}'.format(**kwargs), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs.get('filename'))[1])) except: pass try: # remove file os.remove('{incomepath}{filename}'.format(**kwargs)) except: pass kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1]) logger.debug('alarm_fields: {}'.format(alarm_fields)) if len(alarm_fields) == 0: # no alarmfields found kwargs['id'] = 0 logger.error('no alarm fields found.') return kwargs if not alarmtype: # alarmtype not found kwargs['id'] = 0 kwargs['error'] = kwargs.get('error', '') + 'alarmtype not found' logger.error('alarmtype not found.') return kwargs # position if alarm_fields.get('lat'): _position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0]) else: _position = dict(lat=u'0.0', lng=u'0.0') if USE_NOMINATIM == 1: try: url = 'http://nominatim.openstreetmap.org/search' params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0]) if 'streetno' in alarm_fields: params += ' {}'.format(alarm_fields['streetno'][0].split()[0]) # only first value r = requests.get('{}?{}'.format(url, params)) _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon']) except: pass # create alarm object if alarm_fields.get('key', [u'', 0])[0] == u'': if alarmtype.translation(u'_bma_main_') in alarm_fields.get('remark', [u'', 0])[0] or alarmtype.translation(u'_bma_main_') in alarm_fields.get('person', [u'', 0])[0]: alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all() if len(alarmkey) > 0: alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id)) else: alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0') if alarm_fields.get('time', [u'', 0])[1] == 1: # found correct time t = datetime.datetime.strptime(alarm_fields.get('time', [u'', 0])[0], '%d.%m.%Y - %H:%M:%S') else: t = datetime.datetime.now() alarm.timestamp = t alarm.set('id.key', alarm_fields['key'][1]) alarm._key = alarm_fields['key'][0] alarm.material = dict(cars1='', cars2='', material='') # set required attributes alarm.set('marker', '0') alarm.set('filename', kwargs['filename']) alarm.set('priority', '1') # set normal priority alarm.set('alarmtype', alarmtype.name) # set checker name alarm.position = _position alarm.state = 1 # city if alarm_fields.get('city', ['', 0])[1] > 0: alarm.city = City.getCities(id=alarm_fields.get('city')[1]) if alarm_fields.get('address'): alarm.street = Street.getStreets(id=alarm_fields.get('address')[1]) else: # city not found -> build from fax url = 'http://nominatim.openstreetmap.org/search' params = u'format=json&city={}&street={}'.format(alarm_fields.get('city', [u'', 0])[0].split()[0], alarm_fields.get('address', [u'', 0])[0]) if alarm_fields.get('streetno'): try: params += u' {}'.format(alarm_fields.get('streetno')[0].split()[0]) # only first value except: pass alarm.set('streetno', alarm_fields.get('streetno')[0]) try: r = requests.get(u'{}?{}'.format(url, params)) logger.debug(u'load address data from nomination with parameters: city={} street={}'.format(alarm_fields.get('city')[0].split()[0], alarm_fields.get('address', ['', 0])[0])) _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon']) alarm.position = _position except: pass alarm.set('city', alarm_fields.get('city')[0].split()[0]) alarm.set('id.city', alarm_fields.get('city')[1]) alarm.set('address', alarm_fields.get('address', ['', 0])[0]) if alarm_fields.get('address', [u'', 0])[1] != 0: alarm.street = Street.getStreets(id=alarm_fields.get('address')[1]) if alarm_fields.get('cars'): # add cars found in material for _c in alarm_fields.get('cars')[1].split(';'): alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c) # street / street2 if alarm_fields.get('address', [u'', 0]) != '': # check correct city -> change if street has different city if len(str(alarm_fields.get('address')[1]).split(';')) > 0 and alarm_fields.get('address')[1] != 0: _c = [] for s in str(alarm_fields.get('address')[1]).split(';'): _s = Street.getStreets(id=s) if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields.get('city', [u'', 0])[1]: _c.append(_s.cityid) alarm.street = _s if alarm_fields.get('object', [u'', 0])[1] == 0: if not alarm_fields.get('lat') and not alarm_fields.get('lng'): alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom) if _position['lat'] != u'0.0' and _position['lng'] != u'0.0': # set marker if nominatim delivers result alarm.position = _position alarm.set('marker', '1') else: # add unknown street alarm.set('id.address', 0) alarm.set('address', alarm_fields['address'][0]) # houseno if alarm_fields.get('streetno'): alarm.set('streetno', alarm_fields.get('streetno')[0]) if alarm_fields.get('id.streetno') and alarm_fields.get('lat') and alarm_fields.get('lng'): alarm.position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0]) alarm.set('id.streetno', alarm_fields.get('id.streetno')[1]) else: # new hn = alarm.street.getHouseNumber(name=alarm_fields.get('streetno')[0]) if hn: alarm.position = hn.getPosition(0) if alarm_fields.get('zoom'): alarm.set('zoom', alarm_fields.get('zoom')[0]) # crossing if alarm_fields.get('crossing', [u'', 0])[0] != '': if alarm_fields.get('crossing', [u'', 0])[1] != alarm_fields.get('address',[u'', 0])[1]: alarm.set('id.address2', alarm_fields.get('crossing')[1]) alarm.set('address2', alarm_fields.get('crossing')[0]) else: alarm.set('id.address2', '0') alarm.set('address2', alarm_fields.get('crossing')[0]) # addresspart if alarm_fields.get('addresspart', [u'', 0])[0] != u'' and alarm_fields.get('addresspart', [u'', 0])[0] != alarm_fields.get('address', [u'', 0])[0]: if alarm_fields.get('addresspart')[1] > 0: if len(str(alarm_fields.get('addresspart')[1]).split(';')) > 0: _c = [] for s in str(alarm_fields.get('addresspart')[1]).split(';'): try: _s = Street.getStreets(id=s) if _s.cityid not in _c and _s.cityid == alarm_fields.get('city')[1]: _c.append(_s.cityid) alarm.set('id.address2', _s.id) except: pass else: alarm.set('id.address2', alarm_fields.get('addresspart')[1]) else: alarm.set('id.address2', '0') alarm.set('address2', alarm_fields.get('addresspart')[0]) # person if alarm_fields.get('person', [u'', 0])[0] != u'': alarm.set('person', alarm_fields.get('person')[0]) # alarmplan if alarm_fields.get('alarmplan', [u'', 0])[0] != u'': alarm.set('alarmplan', alarm_fields.get('alarmplan')[0]) # alarmobject _ao = None if alarm_fields.get('object', [u'', 0])[0] != u'' and alarm_fields.get('city', [u'', 0])[1] > 0: alarm.set('object', alarm_fields.get('object')[0]) alarm.set('id.object', alarm_fields.get('object')[1]) # alarmplan from object if alarm_fields.get('object')[1] != 0: _ao = AlarmObject.getAlarmObjects(id=alarm_fields.get('object')[1]) if _ao: if _ao.alarmplan != 0: alarm.set('alarmplan', _ao.alarmplan) elif alarm_fields.get('alarmplan'): alarm.set('alarmplan', alarm_fields.get('alarmplan')[0]) if _ao.street.id != alarm_fields.get('address', [u'', 0])[1]: # street config from alarmobject alarm.street = Street.getStreets(id=_ao.street.id) if _ao.streetno == "": alarm.set('streetno', alarm_fields.get('streetno')[0]) else: alarm.set('streetno', _ao.streetno) alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom) # remark if alarm_fields.get('remark', [u'', 0])[0] != u'': alarm.set('remark', alarm_fields.get('remark')[0]) if alarmtype.translation(u'_bma_main_') in alarm_fields.get('remark', [u'', 0])[0] or alarmtype.translation(u'_bma_main_') in alarm_fields.get('person', [u'', 0])[0]: alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first() if alarmkey: alarm.set('id.key', alarmkey.id) alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key) else: alarm.set('id.key', '0') alarm._key = alarmtype.translation(u'_bma_key_') # additional remarks if alarm_fields.get('remark2', [u'', 0])[0] != u'': alarm.set('remark', u'{}\n{}'.format(alarm.get('remark'), alarm_fields.get('remark2')[0])) # material if alarm.get('id.key') != 0 and alarm_fields.get('city'): # found key with aao if alarm_fields.get('city')[1] not in [0, -1]: # default city if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields.get('city')[1]: # default city for dep if alarm_fields.get('material'): if str(alarm_fields.get('material')[1])[0] == '0': # default cars for aao try: alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)])) except AttributeError: alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)])) for _c in u'{}'.format(alarm_fields.get('material')[1]).split(','): # add additional cars if _c != '0' and _c not in alarm.get('k.cars1').split(','): alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c)) else: # only alarmed material alarm.material = dict(cars1=alarm_fields.get('material', [u'', ''])[1]) else: # else city if alarm_fields.get('material', [u'', u''])[1] == u'0': # default cars for aao alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)])) else: alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields.get('material', ['', '-1'])[1]).split(',')))))) else: # default aao of current department (without aao) if alarm_fields.get('city', [u'', 0])[1] != 0: # found city -> use default aao if City.getCities(id=alarm_fields.get('city')[1]): c = City.getCities(id=alarm_fields.get('city')[1]).dept else: c = City.getDefaultCity().dept akc = Alarmkey.getDefault(c) if len(akc.cars1) + len(akc.cars2) + len(akc.materials) == 0: # no default aao defined # use cars of fax alarm.material = {'cars1': re.sub(r'^0,', '', alarm_fields.get('material')[1]), 'cars2': '', 'material': ''} else: # use cars of default aao alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials])) l = (u'{},{},{}'.format(alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',') if len(set(str(alarm_fields.get('material', ([], '-1'))[1]).split(',')).intersection(set(l))) == 0: _dep = Department.getDefaultDepartment() for c in str(alarm_fields.get('material', ([], '-1'))[1]).split(','): if c == u'0': # default of home department needed alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)])) break if u'0' not in str(alarm_fields.get('material', ([], '-1'))[1]): # only single car needed alarm.set('k.cars1', u'{},{}'.format(alarm_fields.get('material', ([], '-1'))[1], alarm.get('k.cars1'))) if _ao and _ao.hasOwnAAO(): # use aao of current object alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()])) if not kwargs.get('time'): kwargs['time'] = [] kwargs['time'].append('alarm creation done in {} sec.'.format(etime - stime)) if kwargs.get('mode') != 'test': db.session.add(alarm) db.session.commit() signal.send('alarm', 'added', alarmid=alarm.id) Alarm.changeState(alarm.id, 1) # activate alarm logger.info('alarm created with id {} ({})'.format(alarm.id, (etime - stime))) else: kwargs['fields'] = kwargs.get('fields', 'xxx') + '\n\n-------------- ALARM-Object --------------\n' _cdict = Car.getCarsDict() for a in alarm.attributes: try: if a in ['k.cars1', 'k.cars2', 'k.material']: kwargs['fields'] += '\n-%s:\n %s -> %s' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c not in ['', '0']])) elif a in 'id.key': if alarm.get(a) > 0: _k = Alarmkey.getAlarmkeys(id=alarm.get(a)) kwargs['fields'] += '\n-%s:\n %s -> %s: %s' % (a, alarm.get(a), _k.category, _k.key) else: kwargs['fields'] += '\n-%s:\n %s' % (a, alarm.get(a)) kwargs['fields'] += '\n-key:\n %s' % alarm._key elif a == 'id.address': kwargs['fields'] += '\n-%s:\n %s -> %s' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name) elif a == 'id.object': kwargs['id.object'] = '\n-%s:\n %s' % (a, alarm.get(a)) kwargs['object'] = '\n-object:\n %s' % alarm.get('object') else: kwargs['fields'] += '\n-%s:\n %s' % (a, alarm.get(a)) except (AttributeError, KeyError): kwargs['fields'] += '\n-%s:\n %s (error)' % (a, alarm.get(a)) kwargs['id'] = '-0' # add dummy id db.session.rollback() logger.info('alarm created in TESTMODE (%s)' % (etime - stime)) except: signal.send('alarm', 'error', message='alarms.errorincreation', text=kwargs.get('text', '')) return kwargs
def handleEvent(eventname, **kwargs): """ Eventhandler for alarm class :param eventname: name of event :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time :return: all kwargs """ try: from emonitor import app global LASTALARM alarm_fields = dict() stime = time.time() alarmtype = None for t in AlarmType.getAlarmTypes(): if re.search(t.keywords.replace('\r\n', '|'), kwargs.get('text', '')): alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs.get('text', '')) if alarm_fields.get('error'): kwargs['error'] = alarm_fields['error'] del alarm_fields['error'] alarmtype = t break alarm = Alarm(datetime.datetime.now(), '', 1, 0) etime = time.time() _missing = 0 for p in ['time', 'city', 'address', 'key']: if p not in alarm_fields: # test required fields _missing += 1 kwargs['error'] = kwargs.get('error', 'Missing parameter:') + "<br/>- '{}'".format(p) try: t = datetime.datetime.strptime(alarm_fields.get('time')[0], '%d.%m.%Y - %H:%M:%S') except ValueError: t = datetime.datetime.now() alarm.timestamp = t kwargs['id'] = u'<ul><li>-test-</li></ul>' # add dummy id kwargs['fields'] = u'<ul>' # set evaluated fields from fax for k in sorted(alarm_fields): # add field values as unicode string if len(alarm_fields[k]) > 1: kwargs['fields'] = u'{}<li><b>{}:</b>\n <small style="color:silver">value:</small> "{}" → <small style="color:silver">id:</small> {}</li>'.format(kwargs.get('fields'), k, alarm_fields[k][0], alarm_fields[k][1]) else: kwargs['fields'] = u'{}<li><b>{}:</b>\n <small style="color:silver">value:</small> "{}"</li>'.format(kwargs.get('fields'), k, alarm_fields[k]) kwargs['fields'] = kwargs.get('fields', ' ') + '</ul></pre>\n\n<h5> ALARM-Object</h5>\n<pre><ul>' if _missing == 0: # all required parameters found if kwargs.get('mode') != 'test': if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))): os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))) try: shutil.copy2('{incomepath}{filename}'.format(**kwargs), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs.get('filename'))[1])) except: pass try: # remove file os.remove('{incomepath}{filename}'.format(**kwargs)) except: pass kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1]) logger.debug('alarm_fields: {}'.format(alarm_fields)) if len(alarm_fields) == 0: # no alarmfields found kwargs['id'] = 0 logger.error('no alarm fields found.') return kwargs if not alarmtype: # alarmtype not found kwargs['id'] = 0 kwargs['error'] = kwargs.get('error', '') + 'alarmtype not found' logger.error('alarmtype not found.') return kwargs # position if alarm_fields.get('lat'): _position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0]) else: _position = dict(lat=u'0.0', lng=u'0.0') if USE_NOMINATIM == 1: try: url = 'http://nominatim.openstreetmap.org/search' params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0]) if 'streetno' in alarm_fields: params += ' {}'.format(alarm_fields['streetno'][0].split()[0]) # only first value r = requests.get('{}?{}'.format(url, params)) _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon']) except: pass # create alarm object if alarm_fields.get('key', [u'', 0])[0] == u'': if alarmtype.translation(u'_bma_main_') in alarm_fields.get('remark', [u'', 0])[0] or alarmtype.translation(u'_bma_main_') in alarm_fields.get('person', [u'', 0])[0]: alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all() if len(alarmkey) > 0: alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id)) else: alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0') if alarm_fields.get('time', [u'', 0])[1] == 1: # found correct time t = datetime.datetime.strptime(alarm_fields.get('time', [u'', 0])[0], '%d.%m.%Y - %H:%M:%S') else: t = datetime.datetime.now() alarm.timestamp = t alarm.set('id.key', alarm_fields['key'][1]) alarm._key = alarm_fields['key'][0] alarm.material = dict(cars1='', cars2='', material='') # set required attributes alarm.set('marker', '0') alarm.set('filename', kwargs['filename']) alarm.set('priority', '1') # set normal priority alarm.set('alarmtype', alarmtype.name) # set checker name alarm.position = _position alarm.state = 1 # city if alarm_fields.get('city', ['', 0])[1] > 0: alarm.city = City.getCities(id=alarm_fields.get('city')[1]) if alarm_fields.get('address'): alarm.street = Street.getStreets(id=alarm_fields.get('address')[1]) else: # city not found -> build from fax url = 'http://nominatim.openstreetmap.org/search' if len(alarm_fields.get('city', [u'', 0])[0].split()) > 0: params = u'format=json&city={}&street={}'.format(alarm_fields.get('city', [u'', 0])[0].split()[0], alarm_fields.get('address', [u'', 0])[0]) if alarm_fields.get('streetno'): try: params += u' {}'.format(alarm_fields.get('streetno')[0].split()[0]) # only first value except: pass alarm.set('streetno', alarm_fields.get('streetno')[0]) try: r = requests.get(u'{}?{}'.format(url, params)) logger.debug(u'load address data from nomination with parameters: city={} street={}'.format(alarm_fields.get('city')[0].split()[0], alarm_fields.get('address', ['', 0])[0])) _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon']) alarm.position = _position except: pass if len(alarm_fields.get('city', ['', 0])[0].split()) > 0: alarm.set('city', alarm_fields.get('city', ['', 0])[0].split()[0]) alarm.set('id.city', alarm_fields.get('city')[1]) alarm.set('address', alarm_fields.get('address', ['', 0])[0]) if alarm_fields.get('address', [u'', 0])[1] != 0: alarm.street = Street.getStreets(id=alarm_fields.get('address')[1]) if alarm_fields.get('cars'): # add cars found in material for _c in alarm_fields.get('cars')[1].split(';'): alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c) # street / street2 if alarm_fields.get('address', [u'', 0]) != '': # check correct city -> change if street has different city if len(str(alarm_fields.get('address')[1]).split(';')) > 0 and alarm_fields.get('address')[1] != 0: _c = [] for s in str(alarm_fields.get('address')[1]).split(';'): _s = Street.getStreets(id=s) if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields.get('city', [u'', 0])[1]: _c.append(_s.cityid) alarm.street = _s if alarm_fields.get('object', [u'', 0])[1] == 0: if not alarm_fields.get('lat') and not alarm_fields.get('lng'): alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom) if _position['lat'] != u'0.0' and _position['lng'] != u'0.0': # set marker if nominatim delivers result alarm.position = _position alarm.set('marker', '1') else: # add unknown street alarm.set('id.address', 0) alarm.set('address', alarm_fields['address'][0]) # houseno if alarm_fields.get('streetno'): alarm.set('streetno', alarm_fields.get('streetno')[0]) if alarm_fields.get('id.streetno') and alarm_fields.get('lat') and alarm_fields.get('lng'): alarm.position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0]) alarm.set('id.streetno', alarm_fields.get('id.streetno')[1]) else: # new hn = alarm.street.getHouseNumber(name=alarm_fields.get('streetno')[0]) if hn: alarm.position = hn.getPosition(0) if alarm_fields.get('zoom'): alarm.set('zoom', alarm_fields.get('zoom')[0]) # crossing if alarm_fields.get('crossing', [u'', 0])[0] != '': if alarm_fields.get('crossing', [u'', 0])[1] != alarm_fields.get('address',[u'', 0])[1]: alarm.set('id.address2', alarm_fields.get('crossing')[1]) alarm.set('address2', alarm_fields.get('crossing')[0]) else: alarm.set('id.address2', '0') alarm.set('address2', alarm_fields.get('crossing')[0]) # addresspart if alarm_fields.get('addresspart', [u'', 0])[0] != u'' and alarm_fields.get('addresspart', [u'', 0])[0] != alarm_fields.get('address', [u'', 0])[0]: if alarm_fields.get('addresspart')[1] > 0: if len(str(alarm_fields.get('addresspart')[1]).split(';')) > 0: _c = [] for s in str(alarm_fields.get('addresspart')[1]).split(';'): try: _s = Street.getStreets(id=s) if _s.cityid not in _c and _s.cityid == alarm_fields.get('city')[1]: _c.append(_s.cityid) alarm.set('id.address2', _s.id) except: pass else: alarm.set('id.address2', alarm_fields.get('addresspart')[1]) else: alarm.set('id.address2', '0') alarm.set('address2', alarm_fields.get('addresspart')[0]) # person if alarm_fields.get('person', [u'', 0])[0] != u'': alarm.set('person', alarm_fields.get('person')[0]) # alarmplan if alarm_fields.get('alarmplan', [u'', 0])[0] != u'': alarm.set('alarmplan', alarm_fields.get('alarmplan')[0]) # alarmobject _ao = None if alarm_fields.get('object', [u'', 0])[0] != u'' and alarm_fields.get('city', [u'', 0])[1] > 0: alarm.set('object', alarm_fields.get('object')[0]) alarm.set('id.object', alarm_fields.get('object')[1]) # alarmplan from object if alarm_fields.get('object')[1] != 0: _ao = AlarmObject.getAlarmObjects(id=alarm_fields.get('object')[1]) if _ao: if _ao.alarmplan != 0: alarm.set('alarmplan', _ao.alarmplan) elif alarm_fields.get('alarmplan'): alarm.set('alarmplan', alarm_fields.get('alarmplan')[0]) if _ao.street.id != alarm_fields.get('address', [u'', 0])[1]: # street config from alarmobject alarm.street = Street.getStreets(id=_ao.street.id) if _ao.streetno == "": alarm.set('streetno', alarm_fields.get('streetno')[0]) else: alarm.set('streetno', _ao.streetno) alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom) # remark if alarm_fields.get('remark', [u'', 0])[0] != u'': alarm.set('remark', alarm_fields.get('remark')[0]) _bma = 0 for v in alarmtype.translation(u'_bma_main_').split(): if v in alarm_fields.get('remark', [u'', 0])[0] or v in alarm_fields.get('person', [u'', 0])[0]: _bma = 1 break if _bma == 1: alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first() if alarmkey: alarm.set('id.key', alarmkey.id) alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key) else: alarm.set('id.key', '0') alarm._key = alarmtype.translation(u'_bma_key_') # additional remarks if alarm_fields.get('remark2', [u'', 0])[0] != u'': alarm.set('remark', u'{}\n{}'.format(alarm.get('remark'), alarm_fields.get('remark2')[0])) # material if alarm.get('id.key') != 0 and alarm_fields.get('city'): # found key with aao if alarm_fields.get('city')[1] not in [0, -1]: # default city if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields.get('city')[1]: # default city for dep if alarm_fields.get('material'): if str(alarm_fields.get('material')[1])[0] == '0': # default cars for aao try: alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)])) except AttributeError: alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)])) for _c in u'{}'.format(alarm_fields.get('material')[1]).split(','): # add additional cars if _c != '0' and _c not in alarm.get('k.cars1').split(','): alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c)) else: # only alarmed material alarm.material = dict(cars1=alarm_fields.get('material', [u'', ''])[1]) else: # else city if alarm_fields.get('material', [u'', u''])[1] == u'0': # default cars for aao alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)])) else: alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields.get('material', ['', '-1'])[1]).split(',')))))) else: # default aao of current department (without aao) if alarm_fields.get('city', [u'', 0])[1] != 0: # found city -> use default aao if City.getCities(id=alarm_fields.get('city')[1]): c = City.getCities(id=alarm_fields.get('city')[1]).dept else: c = City.getDefaultCity().dept akc = Alarmkey.getDefault(c) if len(akc.cars1) + len(akc.cars2) + len(akc.materials) == 0: # no default aao defined # use cars of fax alarm.material = {'cars1': re.sub(r'^0,', '', alarm_fields.get('material')[1]), 'cars2': '', 'material': ''} else: # use cars of default aao alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials])) l = (u'{},{},{}'.format(alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',') if len(set(str(alarm_fields.get('material', ([], '-1'))[1]).split(',')).intersection(set(l))) == 0: _dep = Department.getDefaultDepartment() for c in str(alarm_fields.get('material', ([], '-1'))[1]).split(','): if c == u'0': # default of home department needed alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)])) break if u'0' not in str(alarm_fields.get('material', ([], '-1'))[1]): # only single car needed alarm.set('k.cars1', u'{},{}'.format(alarm_fields.get('material', ([], '-1'))[1], alarm.get('k.cars1'))) if _ao and _ao.hasOwnAAO(): # use aao of current object alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()])) if not kwargs.get('time'): kwargs['time'] = [] kwargs['time'].append('alarm creation done in {} sec.'.format(etime - stime)) if kwargs.get('mode') != 'test': db.session.add(alarm) db.session.commit() signal.send('alarm', 'added', alarmid=alarm.id) Alarm.changeState(alarm.id, 1) # activate alarm logger.info('alarm created with id {} ({})'.format(alarm.id, (etime - stime))) else: _cdict = Car.getCarsDict() for a in sorted(alarm.attributes): try: if a in ['k.cars1', 'k.cars2', 'k.material']: kwargs['fields'] += '<li><b>%s:</b>\n <small style="color:silver">id:</small> "%s" → "%s"</li>' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c not in ['', '0']])) elif a in 'id.key': if alarm.get(a) > 0: _k = Alarmkey.getAlarmkeys(id=alarm.get(a)) kwargs['fields'] += '<li><b>%s:</b>\n <small style="color:silver">id:</small> "%s" → "%s: %s"</li>' % (a, alarm.get(a), _k.category, _k.key) else: kwargs['fields'] += '<li><b>%s:</b>\n <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a)) kwargs['fields'] += '<li><b>key:</b>\n <small style="color:silver">value:</small> "%s"</li>' % alarm._key elif a == 'id.address': kwargs['fields'] += '<li><b>%s:</b>\n <small style="color:silver">id:</small> "%s" → "%s"</li>' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name) elif a == 'id.object': kwargs['id.object'] = '<li><b>%s:</b>\n <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a)) kwargs['object'] = '<li><b>object:</b>\n <small style="color:silver">value:</small> "%s"</li>' % alarm.get('object') else: kwargs['fields'] += '<li><b>%s:</b>\n <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a)) except (AttributeError, KeyError): kwargs['fields'] += '<li style="color:red"><b>%s:</b>\n <small style="color:silver">value:</small> "%s" (error)</li>' % (a, alarm.get(a)) kwargs['fields'] += "</ul>" db.session.rollback() logger.info('alarm created in TESTMODE (%s)' % (etime - stime)) except: signal.send('alarm', 'error', message='alarms.errorincreation', text=kwargs.get('text', '')) return kwargs
def loadStreetsFromOsm(city=None, format="html"): """ Load all Streets from OpenStreetMap :param optional city: :py:class:`emonitor.modules.streets.city.City` :param optional format: return format, *html*=rendered template, streets as OrderedDict :return: rendered template or dict """ global URL if not city: city = City.getDefaultCity() map_details = Map.getDefaultMap().getMapBox(tilepath=current_app.config.get("PATH_TILES")) SEARCHSTRING = 'area[name~"%s"];way(%s,%s,%s,%s)(area)[highway][name];(._;>;);out;' % ( city.name, map_details["min_latdeg"], map_details["min_lngdeg"], map_details["max_latdeg"], map_details["max_lngdeg"], ) # search all streets for given city r = requests.post(URL, data={"data": SEARCHSTRING}) xmldoc = minidom.parseString(r.content) nodes = xmldoc.getElementsByTagName("node") ways = xmldoc.getElementsByTagName("way") dbosmids = [int(s.osmid or 0) for s in city.getCities()] streets = OrderedDict() n = {} for node in nodes: n[int(node.attributes["id"].value)] = (float(node.attributes["lat"].value), float(node.attributes["lon"].value)) for way in ways: nds = [] osmids = [] name = "" for tag in way.childNodes: if tag.nodeName == "tag" and tag.attributes["k"].value == "name": name = tag.attributes["v"].value osmids.append(int(way.attributes["id"].value)) if tag.nodeName == "nd": _nid = int(tag.attributes["ref"].value) if _nid in n.keys(): nds.append(n[_nid]) if name not in streets.keys(): streets[name] = {"osmids": osmids, "nodes": nds, "indb": False} else: streets[name]["osmids"].extend(osmids) streets[name]["nodes"].extend(nds) if len(set(osmids).intersection(set(dbosmids))) > 0: streets[name]["indb"] = True streets = OrderedDict(sorted(streets.items(), key=lambda t: t[0])) if format == "html": # html output return render_template("admin.streets_osm.html", streets=streets, city=city) else: # data output for name in streets: points = streets[name]["nodes"] if len(points) > 2: cent = centroid_of_polygon(points) streets[name]["center"] = cent elif len(points) == 2: streets[name]["center"] = (((points[0][0] + points[1][0]) / 2), ((points[0][1] + points[1][1]) / 2)) else: streets[name]["center"] = (0.0, 0.0) return streets
def getAdminContent(self, **params): """ Deliver admin content of module streets :param params: use given parameters of request :return: rendered template as string """ module = request.view_args['module'].split('/') if len(module) < 2: if City.getDefaultCity(): module.append(u'{}'.format(City.getDefaultCity().id)) else: module.append(u'1') if len(module) == 2: # cities if module[1] == '0': # city list if request.method == 'POST': if request.form.get('action').startswith('detailcity_'): # edit city params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()}) return render_template('admin.streets.city_edit.html', **params) elif request.form.get('action') == 'updatecity': # update existing city if request.form.get('city_id') != 'None': # update city city = City.getCities(id=request.form.get('city_id')) city.name = request.form.get('cityname') city.subcity = request.form.get('subcity') city.dept = request.form.get('department') city.mapname = request.form.get('citymap') city.color = request.form.get('colorname') city.default = request.form.get('citydefault') city.osmid = request.form.get('osmid') city.osmname = request.form.get('osmname') else: # add city city = City(request.form.get('cityname'), request.form.get('department'), request.form.get('citymap'), request.form.get('citydefault'), request.form.get('subcity'), request.form.get('colorname'), request.form.get('osmid'), request.form.get('osmname')) db.session.add(city) db.session.commit() cache.clear() elif request.form.get('action') == 'createcity': # add city params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()}) return render_template('admin.streets.city_edit.html', **params) elif request.form.get('action').startswith('deletecity_'): # delete city db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1])) db.session.commit() self.updateAdminSubNavigation() cache.clear() params.update({'cities': City.getCities()}) return render_template('admin.streets.city_list.html', **params) else: # show city details if request.method == 'POST': if request.form.get('action').startswith('detailstreet_'): # edit street tileserver = {'lat': Settings.get('defaultLat'), 'lng': Settings.get('defaultLng'), 'zoom': Settings.get('defaultZoom'), 'map': Map.getDefaultMap()} params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver}) return render_template('admin.streets_edit.html', **params) elif request.form.get('action') == 'createstreet': # add street tileserver = {'lat': Settings.get('defaultLat'), 'lng': Settings.get('defaultLng'), 'zoom': Settings.get('defaultZoom'), 'map': Map.getDefaultMap()} params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver}) return render_template('admin.streets_edit.html', **params) elif request.form.get('action').startswith('deletestreets_'): # delete street db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1])) db.session.commit() cache.clear() elif request.form.get('action', '').startswith('deleteallsteets_'): print "delete all streets of", request.form.get('action').split('_')[-1] for s in Street.getStreets(cityid=request.form.get('action').split('_')[-1]): db.session.delete(s) db.session.commit() cache.clear() elif request.form.get('action') == 'savestreet': # save street if request.form.get('street_id') != 'None': # update existing street street = Street.getStreets(id=request.form.get('street_id')) street.name = request.form.get('edit_name') street.navigation = request.form.get('edit_navigation') c = request.form.get('edit_cityid').split('_') if len(c) < 2: c.append('') street.cityid = c[0] street.subcity = c[1] street.lat = request.form.get('edit_lat') street.lng = request.form.get('edit_lng') street.zoom = request.form.get('edit_zoom') street.active = request.form.get('edit_active') db.session.commit() #cache.delete_memoized(City.streets) else: # add street c = request.form.get('edit_cityid').split('_') if len(c) < 2: c.append('') # subcity city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0] city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), 0)) db.session.commit() cache.clear() try: streets = Street.getStreets(cityid=module[-1]) except AttributeError: streets = [] chars = {} for s in streets: chars[s.name[0].upper()] = 0 params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])}) return render_template('admin.streets.html', **params) return "streets"