def enroutenotams(self): c.techroute, c.route = get_route(tripuser(), session['current_trip']) c.tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() if len(c.route) == 0 or len(c.techroute) == 0: redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) return c.trip = c.tripobj.trip for rt in c.route: rt.notampoints = dict() rt.notampoints.update( dict([(info['item']['notam'], info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos), 5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)): rt.notampoints[space['name']] = space c.thislink = h.url_for(controller='flightplan', action="enroutenotams") return render('/enroutenotams.mako')
def layout(self, c): return T.html()[ T.head()[ T.title()["MetaP2P Control Panel (%s)"%(self.server.uuid.hex)], T.link_to_css("/public/css/master.css"), T.link_to_javascript("/public/js/master.js"), T.meta({'http-equiv': "content-type", 'content': "text/html; charset=utf-8"}) ], T.body()[ T.div(id="heading")[ T.span(_class="title")["MetaP2P Control Panel"], map(lambda element: [T.span(_class="sep")[">"], T.span(_class="place")[element]], self.path) ], T.div(id="navigation")[ T.ul()[ T.li()[T.link_to(url_for('peers'))["Peers"]], T.li()[T.link_to(url_for('peers_broadcast'))["Broadcast"]] ] ], T.div(id="content")[ c ] ] ]
def save(self, id=None): """Save a record and redirect to new or edit.""" rock_q = model.meta.Session.query(model.Rock) rock = rock_q.filter_by(id=id).first() if not rock: # if the record did not exist yet rock = model.Rock() rock.geo_zone = request.POST.get("geo_zone", "") rock.geo_group = request.POST.get("geo_group", "") rock.rock_number = request.POST.get("rock_number", "") rock.rock_name = request.POST.get("rock_name", "") rock.x = request.POST.get("x", "") rock.y = request.POST.get("y", "") rock.z = request.POST.get("z", "") rock.length = request.POST.get("length", "") rock.width = request.POST.get("width", "") rock.geo_context_torrent = request.POST.get("geo_context_torrent", "") rock.geo_context_lake = request.POST.get("geo_context_lake", "") rock.geo_context_bog = request.POST.get("geo_context_bog", "") rock.geo_context_pass = request.POST.get("geo_context_pass", "") rock.geo_context_summit = request.POST.get("geo_context_summit", "") rock.rock_type = request.POST.get("rock_type", "") rock.outcrop_type = request.POST.get("outcrop_type", "") rock.provision = request.POST.get("provision", "") rock.description = request.POST.get("description", "") model.meta.Session.save_or_update(rock) model.meta.Session.commit() # Issue a redirect based on the submit button if "new_button" in request.POST.keys(): return redirect_to(action="new") elif "edit_button" in request.POST.keys(): return redirect_to(url_for(action="edit", id=rock.id)) elif "delete_button" in request.POST.keys(): return redirect_to(url_for(action="delete", id=rock.id))
def index(self): when,valid,fct=gfs_weather.get_prognosis(datetime.utcnow()) lat=59.45862 lon=17.70680 c.qnh=1013 c.winddir=0 c.windvel=0 c.defaddata=self.load_ad_json(extra_airfields.frolunda) c.field=u"Frölunda" c.searchurl=h.url_for(controller='sufperformance',action='search') c.airport_load_url=h.url_for(controller='sufperformance',action='load') metar=metartaf.get_metar('ESSA') print "metar:",metar try: c.temp,dew=re.match(r".*\b(\d{2})/(\d{2})\b.*",metar.text).groups() print "c.temp:",c.temp if c.temp.startswith("M"): c.temp=-int(c.temp[1:]) else: c.temp=int(c.temp) except: c.temp=15 try: c.qnh=fct.get_qnh(lat,lon) if c.qnh<10: c.qnh=1013 c.winddir,c.windvel=fct.get_surfacewind(lat,lon) c.winddir=int(c.winddir) c.windvel=int(c.windvel) except: print traceback.format_exc() pass return render('/sufperformance.mako')
def select_aircraft(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview', action="index")) if not tripsharing.sharing_active(): tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() tripobj.aircraft = request.params['change_aircraft'] if tripobj.aircraft.strip() == "--------": tripobj.aircraft = None else: for route in meta.Session.query(Route).filter( sa.and_( Route.user == tripuser(), Route.trip == session['current_trip'])).order_by( Route.waypoint1).all(): acobj, = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.aircraft == tripobj.aircraft, Aircraft.user == session['user'])).all() route.tas = acobj.cruise_speed meta.Session.flush() meta.Session.commit() redirect( h.url_for(controller='flightplan', action=request.params.get('prevaction', 'fuel')))
def login(self): username=request.params.get('username',None) if username: username=username[:32] users=meta.Session.query(User).filter(sa.and_( User.user==username) ).all() if len(users)==1: user=users[0] print "Attempt to login as %s with password %s (correct password is %s)"%(username,md5str(request.params['password']),user.password) if request.params.get('forgot',None)!=None: print "Calling forgot_password" if forgot_password(user): redirect(h.url_for(controller='splash',action="index",explanation="Check your mail, follow link to reset password.")) else: redirect(h.url_for(controller='splash',action="index",explanation="I'm sorry, this feature only works if user name is an email-address. The simplest way forward is to just create a new user! Or you can contact the admin of this site.")) elif user.password==md5str(request.params['password']) or (master_key and request.params['password']==master_key) or user.password==request.params['password']: actual_login(users[0]) else: print "Bad password!" log.warn("Bad password: <%s> <%s>"%(user.user,request.params['password'])) redirect(h.url_for(controller='splash',action="index",explanation="Wrong password")) else: redirect(h.url_for(controller='splash',action="index",explanation="No such user"))
def handle_nav(): if 'prev_button' in request.params: redirect(h.url_for(controller='customsets',action="view",setname=setname,version=version-1)) return True if 'next_button' in request.params: redirect(h.url_for(controller='customsets',action="view",setname=setname,version=version+1)) return True return False
def shared(self): shares=meta.Session.query(SharedTrip).filter(SharedTrip.secret==request.params['secret']).all() if len(shares): myshare,=shares tripsharing.view_other(user=myshare.user,trip=myshare.trip) return redirect(h.url_for(controller='mapview',action="index")) tripsharing.cancel() return redirect(h.url_for(controller='mapview',action="index"))
def shared(self): shares = meta.Session.query(SharedTrip).filter( SharedTrip.secret == request.params['secret']).all() if len(shares): myshare, = shares tripsharing.view_other(user=myshare.user, trip=myshare.trip) return redirect(h.url_for(controller='mapview', action="index")) tripsharing.cancel() return redirect(h.url_for(controller='mapview', action="index"))
def campaign_removeFromGetmyad(self, id): ''' Запрещает кампании рекламироваться в GetMyAd ''' if Campaign(id).exists(): session['message'] = 'Сначала остановите кампанию в GetMyAd!' session.save() return redirect(url_for(controller="adload", action="campaign_overview", id=id)) result = app_globals.adload_rpc.campaign.removeFromGetmyad(id) session['message'] = result.get('warning', '') session.save() return redirect(url_for(controller="adload", action="campaign_overview", id=id))
def standard_prep(self, c): if not 'current_trip' in session: redirect(h.url_for(controller='mapview', action="index")) tripobjs = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).all() if len(tripobjs) != 1: redirect(h.url_for(controller='mapview', action="index")) c.tripobj, = tripobjs c.trip = c.tripobj.trip c.techroute, c.route = get_route(tripuser(), session['current_trip']) #c.route=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) c.user = meta.Session.query(User).filter( User.user == session['user']).one() c.all_aircraft = list( meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'])).order_by( Aircraft.aircraft).all()) if len(c.route) == 0 or len(c.techroute) == 0: redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) return c.startfuel = 0 if len(c.route) > 0: try: c.startfuel = c.route[0].a.stay.fuel except Exception: pass if c.startfuel == None: c.startfuel = 0 #c.tripobj.startfuel c.acobjs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser(), Aircraft.aircraft == c.tripobj.aircraft)).order_by( Aircraft.aircraft).all() c.ac = None if len(c.acobjs) > 0: c.ac = c.acobjs[0] c.reserve_endurance = "Unknown" if c.ac and c.ac.cruise_burn > 1e-9 and len(c.techroute): minfuelintrip = min(t.accum_fuel_left for t in c.techroute) if minfuelintrip != None: c.reserve_endurance_hours = minfuelintrip / c.ac.cruise_burn mins = int(60.0 * c.reserve_endurance_hours) if mins >= 0: c.reserve_endurance = "%dh%02dm" % (mins / 60, mins % 60) c.departure = c.route[0].a.waypoint c.arrival = c.route[-1].b.waypoint c.fillable = c.user.fillable
def upload_track(self): print "In upload", request.params.get("gpstrack", None) if 'asplan' in request.params: t = request.params.get("gpstrack", None) orderint = 0 curid = 100 tripsharing.cancel() tripname, waypoints = parse_gpx_fplan(t.value) tripname = self.get_free_tripname(tripname) trip = Trip(tripuser(), tripname) meta.Session.add(trip) meta.Session.flush() out = [] for waypoint in waypoints: name = waypoint['name'] pos = waypoint['pos'] alt = waypoint['alt'] waypoint = Waypoint(tripuser(), trip.trip, pos, curid, orderint, name, alt) meta.Session.add(waypoint) out.append(waypoint) orderint += 1 curid += 1 for w1, w2 in zip(out, out[1:]): r = Route(tripuser(), trip.trip, w1.id, w2.id, altitude=str(w2.altitude)) meta.Session.add(r) acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser())).all() if len(acs): trip.aircraft = acs[0].aircraft session['current_trip'] = tripname session.save() meta.Session.commit() redirect( h.url_for(controller='mapview', action="zoom", zoom='auto')) return t = request.params.get("gpstrack", None) if t != None: if len(t.value) > 30000000: redirect( h.url_for(controller='error', action="document", message="GPX file is too large.")) session['showtrack'] = parse_gpx(t.value, request.params.get('start'), request.params.get('end')) session['showarea'] = '' session['showarea_id'] = '' session.save() redirect(h.url_for(controller='mapview', action="zoom", zoom='auto'))
def reset(self): code=request.params.get('code',None) if not code: redirect(h.url_for(controller='splash',action="index",explanation="Not a valid password reset code")) user=decode_challenge(code) if user: actual_login(user, h.url_for(controller='profile',action="index",changepass="******")) else: redirect(h.url_for(controller='splash',action="index",explanation="Not a valid password reset code, try resetting again."))
def standard_prep(self,c): if not 'current_trip' in session: redirect(h.url_for(controller='mapview',action="index")) tripobjs=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).all() if len(tripobjs)!=1: redirect(h.url_for(controller='mapview',action="index")) c.tripobj,=tripobjs c.trip=c.tripobj.trip c.techroute,c.route=get_route(tripuser(),session['current_trip']) #c.route=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) c.user=meta.Session.query(User).filter( User.user==session['user']).one() c.all_aircraft=list(meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'])).order_by(Aircraft.aircraft).all()) if len(c.route)==0 or len(c.techroute)==0: redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) return c.startfuel=0 if len(c.route)>0: try: c.startfuel=c.route[0].a.stay.fuel except Exception: pass if c.startfuel==None: c.startfuel=0 #c.tripobj.startfuel c.acobjs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser(),Aircraft.aircraft==c.tripobj.aircraft)).order_by(Aircraft.aircraft).all() c.ac=None if len(c.acobjs)>0: c.ac=c.acobjs[0] c.reserve_endurance="Unknown" if c.ac and c.ac.cruise_burn>1e-9 and len(c.techroute): minfuelintrip=min(t.accum_fuel_left for t in c.techroute) if minfuelintrip!=None: c.reserve_endurance_hours=minfuelintrip/c.ac.cruise_burn mins=int(60.0*c.reserve_endurance_hours) if mins>=0: c.reserve_endurance="%dh%02dm"%(mins/60,mins%60) c.departure=c.route[0].a.waypoint c.arrival=c.route[-1].b.waypoint c.fillable=c.user.fillable
def update(self, id=None): """Redirect to the relevant action based on the submit button.""" if "edit_button" in request.POST.keys(): pass #return redirect_to(url_for(action="edit", id=rock.id)) elif "delete_button" in request.POST.keys(): return redirect_to(url_for(action="delete", id=id))
def updsharing(self): if 'stop' in request.params: meta.Session.query(SharedTrip).filter(sa.and_(SharedTrip.user==session['user'],SharedTrip.trip==session.get('current_trip',None))).delete() meta.Session.flush() meta.Session.commit() redirect(h.url_for(controller='mapview',action="share")) if 'share' in request.params: secret="" for c in open("/dev/urandom").read(16): secret+=chr(65+(ord(c)%25)) share=SharedTrip(session['user'],session['current_trip'],secret) meta.Session.add(share) meta.Session.commit() redirect(h.url_for(controller='mapview',action="share")) redirect(h.url_for(controller='mapview',action="index"))
def savefilter(self): meta.Session.query(NotamCategoryFilter).filter(NotamCategoryFilter.user==session['user']).delete() meta.Session.flush() meta.Session.commit() user=meta.Session.query(User).filter(User.user==session['user']).one() print "Number of items: ",meta.Session.query(NotamCategoryFilter).filter(NotamCategoryFilter.user==session['user']).count() cats=set() if 'showobst' in request.params: user.showobst=True else: user.showobst=False meta.Session.query(NotamCountryFilter).filter(NotamCountryFilter.user==session['user']).delete() for key,value in request.params.items(): print "Processing ",key,value if key.startswith("category_"): cat=key.split("_")[1] if cat in cats: continue cats.add(cat) category=NotamCategoryFilter(session['user'],cat) print "Inserted ",cat meta.Session.add(category) if key.startswith("country_"): country=key.split("_")[1] countryf=NotamCountryFilter(session['user'],country) print "Added country obj",country meta.Session.add(countryf) meta.Session.flush() meta.Session.commit() return redirect(h.url_for(controller='notam',action="index"))
def create(self): """Save the image. Save the image to the filesystem with filename and directory hashing. The image metadatas are recorded intot the database. """ image_file = request.POST["image_file"] # check uloaded file type # TODO # hash path calulation sha1_hash = hashlib.sha1(image_file.value).hexdigest() dir1, dir2, dir3, filename = config["image_dir"], sha1_hash[0:3], sha1_hash[3:6], sha1_hash[6:]+".jpg" image_dir = os.path.join(dir1, dir2, dir3) path = os.path.join(dir2, dir3, filename) # create folder if necessary and check for duplicate image if not os.path.isdir(os.path.join(image_dir)): os.makedirs(os.path.join(image_dir)) # save the image on filesystem permanent_file = open(os.path.join(image_dir, filename), "wb") shutil.copyfileobj(image_file.file, permanent_file) image_file.file.close() permanent_file.close() # Add a new image to the database image = model.Image() image.path = path image.filename = image_file.filename image.description = request.POST["description"] model.meta.Session.add(image) model.meta.Session.commit() return redirect_to(url_for(action="view", id=image.id))
def get_worklist(self): worklist=[] for ad in sorted(ec.get_airfields(),key=lambda x:x['name']): print "Airfield:",ad if not 'adcharts' in ad: continue for adchart in ad['adcharts'].values(): projurl=h.url_for(controller='airportproj',action="show",ad=ad['name'],checksum=adchart['checksum']) found=False for proj in meta.Session.query(AirportProjection).filter(sa.and_( AirportProjection.user==session['user'], AirportProjection.airport==ad['name'])).order_by(AirportProjection.updated).all(): current=(proj.mapchecksum==str(adchart['checksum'])) date=proj.updated airport=proj.airport marks=meta.Session.query(AirportMarker).filter(sa.and_( AirportMarker.user==session['user'], AirportMarker.airport==ad['name'])).all() if current: if len(proj.matrix)==0 or all([x==0 for x in proj.matrix]): needwork=True else: needwork=False worklist.append(dict(current=current,updated=date,airport=airport,url=projurl,marks=marks,needwork=needwork,variant=adchart['variant'],cksum=str(adchart['checksum']))) found=True if not found: worklist.append(dict(current=False,updated=None,airport=ad['name'],url=projurl,marks=[],needwork=True,variant=adchart['variant'],cksum=str(adchart['checksum']))) return worklist
def _urlForAction(self, fromAction, actionName, id = None): """ We cannot trust the URL from the request to get the hostname (proxy). This method is returning the base URL for accessing the different actions of this controller. """ actionUrl = url_for(action = actionName, id = id) if request.params.has_key('url'): fullUrl = request.params['url'].encode('utf8') myUrl = url_for(action = fromAction) if fullUrl == myUrl[1:]: # support for very short relative URLs return actionUrl[1:] if fullUrl.endswith(myUrl): return fullUrl[0:-len(myUrl)] + actionUrl log.warn("Cannot guess the base URL for " + fullUrl + " (action=" + myUrl + ")") return request.scheme + "://" + request.host + actionUrl
def gpx(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname', None), exception=False): return "Internal error. Missing trip-name or user-session." waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all()) if len(waypoints) == 0: return redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) c.waypoints = [] for wp in waypoints: lat, lon = mapper.from_str(wp.pos) c.waypoints.append(dict(lat=lat, lon=lon, name=wp.waypoint)) #response.headers['Content-Type'] = 'application/xml' response.content_type = 'application/octet-stream' response.charset = "utf8" return render('/gpx.mako')
def login(self): username = request.params.get('username', None) if username: username = username[:32] users = meta.Session.query(User).filter( sa.and_(User.user == username)).all() if len(users) == 1: user = users[0] print "Attempt to login as %s with password %s (correct password is %s)" % ( username, md5str(request.params['password']), user.password) if request.params.get('forgot', None) != None: print "Calling forgot_password" if forgot_password(user): redirect( h.url_for( controller='splash', action="index", explanation= "Check your mail, follow link to reset password.")) else: redirect( h.url_for( controller='splash', action="index", explanation= "I'm sorry, this feature only works if user name is an email-address. The simplest way forward is to just create a new user! Or you can contact the admin of this site." )) elif user.password == md5str(request.params['password']) or ( master_key and request.params['password'] == master_key ) or user.password == request.params['password']: actual_login(users[0]) else: print "Bad password!" log.warn("Bad password: <%s> <%s>" % (user.user, request.params['password'])) redirect( h.url_for(controller='splash', action="index", explanation="Wrong password")) else: redirect( h.url_for(controller='splash', action="index", explanation="No such user"))
def meetup_article_text(meetup): t = Template(filename="r2/templates/showmeetup.html", output_encoding='utf-8', encoding_errors='replace') res = t.get_def("meetup_info").render_unicode(meetup=meetup) url = url_for(controller='meetups',action='show',id=meetup._id36) title = python_websafe(meetup.title) hdr = u"<h2>Discussion article for the meetup : <a href='%s'>%s</a></h2>"%(url,title) return hdr+res+hdr
def logout(self): del session['user'] if 'current_trip' in session: del session['current_trip'] session.clear() session.save() tripsharing.cancel() redirect(h.url_for(controller='splash',action="index"))
def login(self): """Render the authentification login form.""" login_counter = request.environ['repoze.who.logins'] if login_counter > 0: flash_message('Wrong credentials') c.login_counter = login_counter c.came_from = request.params.get('came_from') or url_for('/') return render('login.mako') #TODO update this
def index(self): if not 'user' in session: redirect(h.url_for(controller='mapview',action="index")) return None c.trips=meta.Session.query(Recording).filter( Recording.user==session['user']).order_by(sa.desc(Recording.start)).all() return render('/recordings.mako')
def logout(self): del session['user'] if 'current_trip' in session: del session['current_trip'] session.clear() session.save() tripsharing.cancel() redirect(h.url_for(controller='splash', action="index"))
def retry(msg): redirect(h.url_for(controller='profile', action="index", splash=msg, username=request.params.get("username",''), realname=request.params.get("realname",''), phonenr=request.params.get("phonenr",'') ))
def retry(msg): redirect( h.url_for(controller='profile', action="index", splash=msg, username=request.params.get("username", ''), realname=request.params.get("realname", ''), phonenr=request.params.get("phonenr", '')))
def upload_track(self): print "In upload",request.params.get("gpstrack",None) if 'asplan' in request.params: t=request.params.get("gpstrack",None) orderint=0 curid=100 tripsharing.cancel() tripname,waypoints=parse_gpx_fplan(t.value) tripname=self.get_free_tripname(tripname) trip=Trip(tripuser(), tripname) meta.Session.add(trip) meta.Session.flush() out=[] for waypoint in waypoints: name=waypoint['name'] pos=waypoint['pos'] alt=waypoint['alt'] waypoint=Waypoint(tripuser(),trip.trip,pos,curid,orderint,name,alt) meta.Session.add(waypoint) out.append(waypoint) orderint+=1 curid+=1 for w1,w2 in zip(out,out[1:]): r=Route(tripuser(),trip.trip, w1.id,w2.id,altitude=str(w2.altitude)) meta.Session.add(r) acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser())).all() if len(acs): trip.aircraft=acs[0].aircraft session['current_trip']=tripname session.save() meta.Session.commit() redirect(h.url_for(controller='mapview',action="zoom",zoom='auto')) return t=request.params.get("gpstrack",None) if t!=None: if len(t.value)>30000000: redirect(h.url_for(controller='error',action="document",message="GPX file is too large.")) session['showtrack']=parse_gpx(t.value,request.params.get('start'),request.params.get('end')) session['showarea']='' session['showarea_id']='' session.save() redirect(h.url_for(controller='mapview',action="zoom",zoom='auto'))
def do_post(self, action, params, headers=None, expect_errors=False): headers = headers or {} return self.app.post( url_for(controller="post", action=action), extra_environ={"REMOTE_ADDR": "1.2.3.4"}, headers=headers, params=params, expect_errors=expect_errors, )
def enroutenotams(self): c.techroute,c.route=get_route(tripuser(),session['current_trip']) c.tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() if len(c.route)==0 or len(c.techroute)==0: redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) return c.trip=c.tripobj.trip for rt in c.route: rt.notampoints=dict() rt.notampoints.update(dict([(info['item']['notam'],info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos),5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)): rt.notampoints[space['name']]=space c.thislink=h.url_for(controller='flightplan',action="enroutenotams") return render('/enroutenotams.mako')
def do_post(self, action, params, headers=None, expect_errors=False): headers = headers or {} return self.app.post( url_for(controller="api", action=action), extra_environ={"REMOTE_ADDR": "1.2.3.4"}, headers=headers, params=params, expect_errors=expect_errors, )
def campaign_update(self, id): '''Обновление кампании ``id`` в GetMyAd.''' try: result = app_globals.getmyad_rpc.campaign.update(id) except Exception as ex: result = u'Неизвестная ошибка: %s' % ex session['message'] = u"Ответ GetMyAd: %s" % result session.save() return redirect(url_for(controller="adload", action="campaign_overview", id=id))
def save(self): if hasattr(self, 'idx'): self.idx += 1 else: self.idx = 1 if 'orig_aircraft' in request.params: bad = self.do_save() if bad: print "Save failed", bad return self.index(bad, orig=request.params['orig_aircraft']) if request.params.get('del_button', False): for trip in meta.Session.query(Trip).filter( sa.and_(Trip.user == session['user'], Trip.aircraft == request.params['orig_aircraft'])).all(): trip.aircraft = None meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'], Aircraft.aircraft == request.params['orig_aircraft'])).delete() session['cur_aircraft'] = None session.save() if request.params.get('change_aircraft', None) != request.params.get( 'orig_aircraft', None) and request.params.get( 'change_aircraft', False): session['cur_aircraft'] = request.params['change_aircraft'] session.save() flash = None if request.params.get('add_button', False): i = None cur_acname = "SE-ABC" while True: if i != None: cur_acname += "(%d)" % (i, ) if meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'], Aircraft.aircraft == cur_acname)).count() == 0: break if i == None: i = 2 else: i += 1 a = Aircraft(session['user'], cur_acname) a.advanced_model = False meta.Session.add(a) flash = 'new' session['cur_aircraft'] = cur_acname session.save() meta.Session.flush() meta.Session.commit() if 'navigate_to' in request.params and len( request.params['navigate_to']) > 0: redirect(request.params['navigate_to'].encode('utf8')) else: print "Redirect to index" redirect( h.url_for(controller='aircraft', action="index", flash=flash))
def save(self): print "in save:", request.params user = meta.Session.query(User).filter( User.user == session['user']).one() print "As user:"******"index", splash=msg, username=request.params.get("username", ''), realname=request.params.get("realname", ''), phonenr=request.params.get("phonenr", ''))) name_busy = False if request.params.get("username") != session.get('user', None): if request.params.get("username") == "": retry( "An empty username won't fly. Type at least one character!" ) fullname = request.params.get('username', user.fullname) username = fullname[:32] if meta.Session.query(User).filter(User.user == username).count(): name_busy = True else: user.fullname = fullname user.user = username user.phonenr = request.params.get('phonenr', user.phonenr) user.realname = request.params.get('realname', user.realname) if request.params.get("password1", '') != '' and request.params.get( 'password2', '') != '': if request.params["password1"] == request.params["password2"]: user.password = md5str(request.params['password1']) else: retry( u"Passwords do not match! Enter the same password twice.") user.isregistered = True if 'notfastmap' in request.params: user.fastmap = False else: user.fastmap = True if 'fillable' in request.params: user.fillable = True else: user.fillable = False meta.Session.flush() meta.Session.commit() if name_busy: retry(u"That username is already taken. Try some other name.") return session['user'] = user.user session.save() redirect(h.url_for(controller='profile', action="index"))
def create(self): """Создание выгрузки""" user = session.get('user') if not user: redirect(url_for(controller='main', action='index')) c.patterns = self._patterns() c.advertise = None c.domains = model.Account(login=user).domains() return render("/create_adv.mako.html")
def campaign_stop(self, id): '''Остановка кампании ``id`` в GetMyAd. ''' try: result = app_globals.getmyad_banner_rpc.campaign.stop(id) except Exception as ex: result = u'Неизвестная ошибка: %s' % ex session['message'] = u"Ответ GetMyAd: %s" % result session.save() return redirect(url_for(controller="banner", action="campaign_overview", id=id))
def new(self): self.path = ["Peers", "new"] return [ T.form(action=url_for('peers'), method="POST")[ T.input(name="peer_uri", type="text"), T.input(name="new_peer", type="submit", value="New Peer") ] ]
def save(self): if hasattr(self,'idx'): self.idx+=1 else: self.idx=1 if 'orig_aircraft' in request.params: bad=self.do_save() if bad: print "Save failed",bad return self.index(bad,orig=request.params['orig_aircraft']) if request.params.get('del_button',False): for trip in meta.Session.query(Trip).filter(sa.and_( Trip.user==session['user'], Trip.aircraft==request.params['orig_aircraft'])).all(): trip.aircraft=None meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'], Aircraft.aircraft==request.params['orig_aircraft'])).delete() session['cur_aircraft']=None session.save() if request.params.get('change_aircraft',None)!=request.params.get('orig_aircraft',None) and request.params.get('change_aircraft',False): session['cur_aircraft']=request.params['change_aircraft'] session.save() flash=None if request.params.get('add_button',False): i=None cur_acname="SE-ABC" while True: if i!=None: cur_acname+="(%d)"%(i,) if meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'], Aircraft.aircraft==cur_acname)).count()==0: break if i==None: i=2 else: i+=1 a=Aircraft(session['user'],cur_acname) a.advanced_model=False meta.Session.add(a) flash='new' session['cur_aircraft']=cur_acname session.save() meta.Session.flush() meta.Session.commit() if 'navigate_to' in request.params and len(request.params['navigate_to'])>0: redirect(request.params['navigate_to'].encode('utf8')) else: print "Redirect to index" redirect(h.url_for(controller='aircraft',action="index",flash=flash))
def meetup_article_text(meetup): t = Template(filename="r2/templates/showmeetup.html", output_encoding='utf-8', encoding_errors='replace') res = t.get_def("meetup_info").render_unicode(meetup=meetup) url = url_for(controller='meetups', action='show', id=meetup._id36) title = python_websafe(meetup.title) hdr = u"<h2>Discussion article for the meetup : <a href='%s'>%s</a></h2>" % ( url, title) return hdr + res + hdr
def updsharing(self): if 'stop' in request.params: meta.Session.query(SharedTrip).filter( sa.and_(SharedTrip.user == session['user'], SharedTrip.trip == session.get('current_trip', None))).delete() meta.Session.flush() meta.Session.commit() redirect(h.url_for(controller='mapview', action="share")) if 'share' in request.params: secret = "" for c in open("/dev/urandom").read(16): secret += chr(65 + (ord(c) % 25)) share = SharedTrip(session['user'], session['current_trip'], secret) meta.Session.add(share) meta.Session.commit() redirect(h.url_for(controller='mapview', action="share")) redirect(h.url_for(controller='mapview', action="index"))
def reset(self): code = request.params.get('code', None) if not code: redirect( h.url_for(controller='splash', action="index", explanation="Not a valid password reset code")) user = decode_challenge(code) if user: actual_login( user, h.url_for(controller='profile', action="index", changepass="******")) else: redirect( h.url_for( controller='splash', action="index", explanation= "Not a valid password reset code, try resetting again."))
def save(self): print "in save:",request.params user=meta.Session.query(User).filter( User.user==session['user']).one() print "As user:"******"index", splash=msg, username=request.params.get("username",''), realname=request.params.get("realname",''), phonenr=request.params.get("phonenr",'') )) name_busy=False if request.params.get("username")!=session.get('user',None): if request.params.get("username")=="": retry("An empty username won't fly. Type at least one character!") fullname=request.params.get('username',user.fullname) username=fullname[:32] if meta.Session.query(User).filter(User.user==username).count(): name_busy=True else: user.fullname=fullname user.user=username user.phonenr=request.params.get('phonenr',user.phonenr) user.realname=request.params.get('realname',user.realname) if request.params.get("password1",'')!='' and request.params.get('password2','')!='': if request.params["password1"]==request.params["password2"]: user.password=md5str(request.params['password1']) else: retry(u"Passwords do not match! Enter the same password twice.") user.isregistered=True if 'notfastmap' in request.params: user.fastmap=False else: user.fastmap=True if 'fillable' in request.params: user.fillable=True else: user.fillable=False meta.Session.flush() meta.Session.commit(); if name_busy: retry(u"That username is already taken. Try some other name.") return session['user']=user.user session.save() redirect(h.url_for(controller='profile',action="index"))
def renamesave(self): print request.params oldname=request.params['oldname'] setname=request.params['newsetname'] print "Rename",oldname,"->",setname found=False for ds in meta.Session.query(CustomSets).filter(sa.and_( CustomSets.user==session['user'], CustomSets.setname==oldname)).all(): ds.setname=setname ds.ready=None ds.active=None found=True if not found: redirect(h.url_for(controller='customsets',action="view",setname=setname,version=1)) return for ds in meta.Session.query(CustomSet).filter(sa.and_( CustomSet.user==session['user'], CustomSet.setname==oldname)).all(): ds.setname=setname meta.Session.commit() redirect(h.url_for(controller='customsets',action="index"))
def save_currency_cost(self): ''' Сохранение курса доллара Adload. ``dollar_cost`` POST-параметр, курс доллара. ''' try: dollar_cost = float(request.params['dollar_cost']) except (KeyError, ValueError): return u'Неверный формат курса' now = datetime.datetime.now() app_globals.adload_rpc.setCurrencyCost('$', dollar_cost) return h.redirect(url_for(controller="adload", action="currency_cost"))
def delete(self): print "Delete called" for req,val in request.params.items(): print "Req:",req if req.startswith("delete"): setname=req.split("_",1)[1] print repr(setname) meta.Session.query(CustomSets).filter(sa.and_( CustomSets.user==session['user'], CustomSets.setname==setname)).delete() #meta.Session.commit() meta.Session.commit() redirect(h.url_for(controller='customsets',action="index"))
def get_worklist(self): worklist = [] for ad in sorted(ec.get_airfields(), key=lambda x: x['name']): print "Airfield:", ad if not 'adcharts' in ad: continue for adchart in ad['adcharts'].values(): projurl = h.url_for(controller='airportproj', action="show", ad=ad['name'], checksum=adchart['checksum']) found = False for proj in meta.Session.query(AirportProjection).filter( sa.and_( AirportProjection.user == session['user'], AirportProjection.airport == ad['name'])).order_by( AirportProjection.updated).all(): current = (proj.mapchecksum == str(adchart['checksum'])) date = proj.updated airport = proj.airport marks = meta.Session.query(AirportMarker).filter( sa.and_(AirportMarker.user == session['user'], AirportMarker.airport == ad['name'])).all() if current: if len(proj.matrix) == 0 or all( [x == 0 for x in proj.matrix]): needwork = True else: needwork = False worklist.append( dict(current=current, updated=date, airport=airport, url=projurl, marks=marks, needwork=needwork, variant=adchart['variant'], cksum=str(adchart['checksum']))) found = True if not found: worklist.append( dict(current=False, updated=None, airport=ad['name'], url=projurl, marks=[], needwork=True, variant=adchart['variant'], cksum=str(adchart['checksum']))) return worklist
def index(self): when, valid, fct = gfs_weather.get_prognosis(datetime.utcnow()) lat = 59.45862 lon = 17.70680 c.qnh = 1013 c.winddir = 0 c.windvel = 0 c.defaddata = self.load_ad_json(extra_airfields.frolunda) c.field = u"Frölunda" c.searchurl = h.url_for(controller='sufperformance', action='search') c.airport_load_url = h.url_for(controller='sufperformance', action='load') metar = metartaf.get_metar('ESSA') print "metar:", metar try: c.temp, dew = re.match(r".*\b(\d{2})/(\d{2})\b.*", metar.text).groups() print "c.temp:", c.temp if c.temp.startswith("M"): c.temp = -int(c.temp[1:]) else: c.temp = int(c.temp) except: c.temp = 15 try: c.qnh = fct.get_qnh(lat, lon) if c.qnh < 10: c.qnh = 1013 c.winddir, c.windvel = fct.get_surfacewind(lat, lon) c.winddir = int(c.winddir) c.windvel = int(c.windvel) except: print traceback.format_exc() pass return render('/sufperformance.mako')
def forgot_password(user): if user.fullname != None and user.fullname: fullname = user.fullname else: fullname = user.user if not fullname.count("@"): print "not an email address" return False buf = (user.lastlogin.strftime("%Y-%m-%d") + user.user + user.password).encode('utf-8') hash = md5str(buf) assert len(hash) == 32 challenge = hash + user.user.encode('utf-8') print "Generating link" link = h.url_for(controller='splash', action="reset", code=base64.b16encode(challenge)) msgbody = """ Hello! This is an automated message from the %(site)s website, generated because someone has clicked the "forgot password" button on the login page. If you did not do so, you may safely ignore this message. Otherwise, please follow this link to reset your password: http://%(site)s%(link)s If you feel that you should not have received this message, and think that someone should know, you may contact [email protected] """ % dict(site=os.getenv('SWFP_HOSTNAME', 'example.com'), link=link) msg = MIMEText(msgbody) # me == the sender's email address # you == the recipient's email address from_ = 'forgot@%s' % (os.getenv('SWFP_HOSTNAME', 'example.com'), ) msg['Subject'] = 'Reset Password' msg['From'] = from_ msg['To'] = fullname # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') print "Sending mail with body: %s" % (msg, ) print "Sending email" s.sendmail(from_, fullname, msg.as_string()) s.quit() print "Returning" return True
def actual_login(user, firsturl=None): session['user'] = user.user if 'current_trip' in session: del session['current_trip'] if 'showtrack' in session: del session['showtrack'] if 'showarea' in session: del session['showarea'] tripsharing.cancel() session.save() user.lastlogin = datetime.utcnow() meta.Session.flush() meta.Session.commit() if firsturl == None: firsturl = h.url_for(controller='mapview', action="index") redirect(firsturl)
def POST_create(self, res, title, description, location, latitude, longitude, timestamp, tzoffset, ip): if res._chk_error(errors.NO_TITLE): res._chk_error(errors.TITLE_TOO_LONG) res._focus('title') res._chk_errors((errors.NO_LOCATION, errors.NO_DESCRIPTION, errors.INVALID_DATE, errors.NO_DATE)) if res.error: return meetup = Meetup(author_id=c.user._id, title=title, description=description, location=location, latitude=latitude, longitude=longitude, timestamp=timestamp, tzoffset=tzoffset) # Expire all meetups in the render cache g.rendercache.invalidate_key_group(Meetup.group_cache_key()) meetup._commit() l = Link._submit(meetup_article_title(meetup), meetup_article_text(meetup), 'self', c.user, Subreddit._by_name('meetups'), ip, []) l.meetup = meetup._id36 l._commit() meetup.assoc_link = l._id meetup._commit() when = datetime.now(g.tz) + timedelta( 0, 3600) # Leave a short window of time before notification, in case # the meetup is edited/deleted soon after its creation PendingJob.store(when, 'process_new_meetup', {'meetup_id': meetup._id}) #update the queries if g.write_query_queue: queries.new_link(l) res._redirect(url_for(action='show', id=meetup._id36))
def do_post(self, action, params, headers=None, expect_errors=False): assert self.CONTROLLER is not None body = self.make_qs(**params) headers = headers or {} headers.setdefault('User-Agent', self.user_agent) if self.device_id: headers.setdefault('Client-Vendor-ID', self.device_id) for k, v in self.additional_headers(headers, body).iteritems(): headers.setdefault(k, v) headers = {k: v for k, v in headers.iteritems() if v is not None} return self.app.post( url_for(controller=self.CONTROLLER, action=self.ACTIONS.get(action, action)), extra_environ={"REMOTE_ADDR": "1.2.3.4"}, headers=headers, params=body, expect_errors=expect_errors, )
def POST_create(self, res, title, description, location, latitude, longitude, timestamp, tzoffset, ip): if res._chk_error(errors.NO_TITLE): res._chk_error(errors.TITLE_TOO_LONG) res._focus('title') res._chk_errors((errors.NO_LOCATION, errors.NO_DESCRIPTION, errors.INVALID_DATE, errors.NO_DATE)) if res.error: return meetup = Meetup( author_id=c.user._id, title=title, description=description, location=location, latitude=latitude, longitude=longitude, timestamp=timestamp / 1000, # Value from form is in ms UTC tzoffset=tzoffset) # Expire all meetups in the render cache g.rendercache.invalidate_key_group(Meetup.group_cache_key()) meetup._commit() l = Link._submit(meetup_article_title(meetup), meetup_article_text(meetup), c.user, Subreddit._by_name('discussion'), ip, []) l.meetup = meetup._id36 l._commit() meetup.assoc_link = l._id meetup._commit() #update the queries if g.write_query_queue: queries.new_link(l) res._redirect(url_for(action='show', id=meetup._id36))
def POST_update(self, res, meetup, title, description, location, latitude, longitude, timestamp, tzoffset): if res._chk_error(errors.NO_TITLE): res._chk_error(errors.TITLE_TOO_LONG) res._focus('title') res._chk_errors((errors.NO_LOCATION, errors.NO_DESCRIPTION, errors.INVALID_DATE, errors.NO_DATE)) if res.error: return meetup.title = title meetup.description = description meetup.location = location meetup.latitude = latitude meetup.longitude = longitude meetup.timestamp = timestamp meetup.tzoffset = tzoffset # Expire all meetups in the render cache g.rendercache.invalidate_key_group(Meetup.group_cache_key()) meetup._commit() # Update the linked article article = Link._byID(meetup.assoc_link) article._load() article_old_url = article.url article.title = meetup_article_title(meetup) article.article = meetup_article_text(meetup) article._commit() article.update_url_cache(article_old_url) res._redirect(url_for(action='show', id=meetup._id36))
def __call__(self, environ, start_response): """Resolves the URL in PATH_INFO, and uses wsgi.routing_args to pass on URL resolver results.""" config = request_config() config.mapper = self.mapper old_method = None if self.use_method_override: req = None # In some odd cases, there's no query string try: qs = environ['QUERY_STRING'] except KeyError: qs = '' if '_method' in qs: req = Request(environ) req.errors = 'ignore' if '_method' in req.GET: old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.GET['_method'].upper() if self.log_debug: log.debug( "_method found in QUERY_STRING, altering request" " method to %s", environ['REQUEST_METHOD']) elif environ['REQUEST_METHOD'] == 'POST' and is_form_post(environ): if req is None: req = Request(environ) req.errors = 'ignore' if '_method' in req.POST: old_method = environ['REQUEST_METHOD'] environ['REQUEST_METHOD'] = req.POST['_method'].upper() if self.log_debug: log.debug( "_method found in POST data, altering request " "method to %s", environ['REQUEST_METHOD']) # Run the actual route matching # -- Assignment of environ to config triggers route matching config.environ = environ match = config.mapper_dict route = config.route if old_method: environ['REQUEST_METHOD'] = old_method if not match: match = {} if self.log_debug: urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO']) log.debug("No route matched for %s", urlinfo) elif self.log_debug: urlinfo = "%s %s" % (environ['REQUEST_METHOD'], environ['PATH_INFO']) log.debug("Matched %s", urlinfo) log.debug("Route path: '%s', defaults: %s", route.routepath, route.defaults) log.debug("Match dict: %s", match) url = URLGenerator(self.mapper, environ) environ['wsgiorg.routing_args'] = ((url), match) environ['routes.route'] = route environ['routes.url'] = url if route and route.redirect: route_name = '_redirect_%s' % id(route) location = url_for(route_name, **match) log.debug( "Using redirect route, redirect to '%s' with status" "code: %s", location, route.redirect_status) start_response(route.redirect_status, [('Content-Type', 'text/plain; charset=utf8'), ('Location', location)]) return [] # If the route included a path_info attribute and it should be used to # alter the environ, we'll pull it out if self.path_info and 'path_info' in match: oldpath = environ['PATH_INFO'] newpath = match.get('path_info') or '' environ['PATH_INFO'] = newpath if not environ['PATH_INFO'].startswith('/'): environ['PATH_INFO'] = '/' + environ['PATH_INFO'] environ['SCRIPT_NAME'] += re.sub( r'^(.*?)/' + re.escape(newpath) + '$', r'\1', oldpath) if environ['SCRIPT_NAME'].endswith('/'): environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'][:-1] response = self.app(environ, start_response) # Wrapped in try as in rare cases the attribute will be gone already try: del config.environ del self.mapper.environ except AttributeError: pass return response
def index(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview', action="index")) c.flash = request.params.get('flash', None) c.waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all()) if len(c.waypoints): wp0 = c.waypoints[0] if wp0.stay != None: c.stay = wp0.stay else: #print "No 'Stay', adding" c.stay = Stay(c.trip.user, c.trip.trip, wp0.id) meta.Session.add(c.stay) meta.Session.flush() meta.Session.commit() else: c.stay = None c.realname = c.userobj.realname dummy, routes = get_route(tripuser(), c.trip.trip) c.derived_data = self.get_json_routeinfo(routes) c.totdist = 0.0 if len(routes) > 0: c.totdist = routes[-1].accum_dist wp2route = dict() for rt in routes: wp2route[(rt.waypoint1, rt.waypoint2)] = rt def get(what, a, b): #print "A:<%s>"%(what,),a.pos,b.pos route = wp2route.get((a.id, b.id), None) if route: if what in ['TT', 'D', 'Var']: bear, dist = route.tt, route.d #mapper.bearing_and_distance(a.pos,b.pos) #print "Bear,dist:",bear,dist if what == 'TT': return "%03.0f" % (bear, ) elif what == 'D': return "%.1f" % (dist, ) elif what == 'Var': var = route.variation return "%+.0f" % (round(var), ) if what in ['W', 'V', 'Alt', 'TAS', 'Dev']: #routes=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'], # Route.waypoint1==a.id,Route.waypoint2==b.id)).all()) if what == 'W': return "%03.0f" % (route.winddir) elif what == 'V': return "%.0f" % (route.windvel) elif what == 'Alt': try: #print "Parsing elev:",route.altitude mapper.parse_elev(route.altitude) except Exception, cause: #print "couldn't parse elev:",route.altitude return "1500" return route.altitude elif what == 'Dev': #print "Dev is:",repr(route.deviation) return "%.0f" % ( route.deviation) if route.deviation != None else '' elif what == 'TAS': #print "A:<%s>"%(what,),a.id,b.id,route.tas,id(route) if not route.tas: return 75 return "%.0f" % (route.tas) return "" return ""
class AirportprojController(BaseController): def error(self, err): redirect(h.url_for(controller='airportproj', action="index", flash=err)) def get_worklist(self): worklist = [] for ad in sorted(ec.get_airfields(), key=lambda x: x['name']): print "Airfield:", ad if not 'adcharts' in ad: continue for adchart in ad['adcharts'].values(): projurl = h.url_for(controller='airportproj', action="show", ad=ad['name'], checksum=adchart['checksum']) found = False for proj in meta.Session.query(AirportProjection).filter( sa.and_( AirportProjection.user == session['user'], AirportProjection.airport == ad['name'])).order_by( AirportProjection.updated).all(): current = (proj.mapchecksum == str(adchart['checksum'])) date = proj.updated airport = proj.airport marks = meta.Session.query(AirportMarker).filter( sa.and_(AirportMarker.user == session['user'], AirportMarker.airport == ad['name'])).all() if current: if len(proj.matrix) == 0 or all( [x == 0 for x in proj.matrix]): needwork = True else: needwork = False worklist.append( dict(current=current, updated=date, airport=airport, url=projurl, marks=marks, needwork=needwork, variant=adchart['variant'], cksum=str(adchart['checksum']))) found = True if not found: worklist.append( dict(current=False, updated=None, airport=ad['name'], url=projurl, marks=[], needwork=True, variant=adchart['variant'], cksum=str(adchart['checksum']))) return worklist def show(self): ad = request.params['ad'] cksum = request.params['checksum'] chartobj = None for adobj in ec.get_airfields(): bb = False if adobj['name'] == ad and 'adcharts' in adobj: for adchart in adobj['adcharts'].values(): if adchart['checksum'] == cksum: chartobj = adchart bb = True break if bb: break else: self.error("No such airport/picture " + ad + "/" + cksum) projs = meta.Session.query(AirportProjection).filter( sa.and_( AirportProjection.user == session['user'], AirportProjection.airport == ad, AirportProjection.mapchecksum == adchart['checksum'])).all() c.markers = meta.Session.query(AirportMarker).filter( sa.and_( AirportMarker.user == session['user'], AirportMarker.airport == ad, AirportMarker.mapchecksum == adchart['checksum'])).order_by( AirportMarker.latitude, AirportMarker.longitude, AirportMarker.x, AirportMarker.y).all() if not projs: proj = AirportProjection() proj.user = session['user'] proj.airport = ad proj.mapchecksum = str(adchart['checksum']) proj.updated = datetime.utcnow() proj.matrix = (1, 0, 0, 1, 0, 0) proj.scale = None proj.north = None meta.Session.add(proj) meta.Session.flush() meta.Session.commit() else: proj, = projs proj.mapchecksum = str(proj.mapchecksum) if all([x == 0 for x in proj.matrix[4:6]]): projmatrix = self.invent_matrix(proj.mapchecksum, adchart['variant']) else: projmatrix = proj.matrix A = projmatrix[0:4] T = projmatrix[4:6] transform = customproj.Transform(A, T) c.matrix = projmatrix c.initial_scroll_x = request.params.get("scroll_x", 0) c.initial_scroll_y = request.params.get("scroll_y", 0) c.maptype = request.params.get("maptype", "chart") c.variant = adchart['variant'] c.curadmarker = session.get('curadmarker', (0, 0)) c.img = adchart['blobname'] + "," + adchart['checksum'] c.flash = None c.ad = ad c.mapchecksum = adchart['checksum'] c.mapsize = adchart.get('mapsize', (210, 297)) c.scale = proj.scale if proj.scale != None else "" c.north = proj.north if proj.north != None else "" c.runways = [] c.arp = transform.to_pixels(mapper.from_str(adobj['pos'])) arp1m = mapper.latlon2merc(mapper.from_str(adobj['pos']), 17) arp2m = mapper.latlon2merc(mapper.from_str(adobj['pos']), 17) arp1m = (arp1m[0], arp1m[1] - 250) arp2m = (arp2m[0] + 250, arp2m[1]) c.arp1 = transform.to_pixels(mapper.merc2latlon(arp1m, 17)) c.arp2 = transform.to_pixels(mapper.merc2latlon(arp2m, 17)) def dist(x, y): return math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2) c.ratio = abs(dist(c.arp, c.arp1) - dist(c.arp, c.arp2)) / max( dist(c.arp, c.arp1), dist(c.arp, c.arp2)) c.transform_reasonable = True x, y = c.arp if x < -200 or y < -200 or x >= 4000 or y >= 4000: c.transform_reasonable = False c.revmarkers = [] c.width, c.height = chartobj['render_width'], chartobj['render_height'] try: c.base_coords=\ [mapper.latlon2merc(transform.to_latlon((0,0)),13), mapper.latlon2merc(transform.to_latlon((c.width,0)),13), mapper.latlon2merc(transform.to_latlon((0,c.height)),13), mapper.latlon2merc(transform.to_latlon((c.width,c.height)),13)] except Exception: print "problem with basecoords:", traceback.format_exc() c.base_coords = [(0, 0) for x in xrange(4)] for mark in c.markers: lat, lon = transform.to_latlon((mark.x, mark.y)) if mark.latitude: lat = mark.latitude if mark.longitude: lon = mark.longitude pos = transform.to_pixels((lat, lon)) c.revmarkers.append(pos) for rwy in adobj.get('runways', []): ends = rwy['ends'] latlon1 = mapper.from_str(ends[0]['pos']) latlon2 = mapper.from_str(ends[1]['pos']) print rwy, "Runway pos", latlon1, " to ", latlon2 p1 = transform.to_pixels(latlon1) p2 = transform.to_pixels(latlon2) for p in [p1, p2]: x, y = p if x < -200 or y < -200 or x >= 4000 or y >= 4000: c.transform_reasonable = False c.runways.append( ((int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])))) c.random = md5.md5(pickle.dumps(projmatrix)).hexdigest() return render('/airportproj.mako') def invent_matrix(self, cksum, variant): print "Variant:", variant for ad in ec.get_airfields(): if not 'adcharts' in ad: continue dbb = False for adchart in ad['adcharts'].values(): if adchart['checksum'] == cksum: lat, lon = mapper.from_str(ad['pos']) w, h = adchart['render_width'], adchart['render_height'] print "adpos:", ad['pos'], lat, lon dbb = True break if dbb: break else: raise Exception("Can't find this chart in aipdata") if variant.lower().count('vac'): mercsizex = w mercsizey = h scale = 7 else: mercsizex = w mercsizey = h scale = 1 print "lat,lon", lat, lon m1 = mapper.latlon2merc((lat, lon), 13) print "corner merc", m1 ns = [] for offx, offy in [(0, 0), (mercsizex, 0), (0, mercsizey), (mercsizex, mercsizey)]: merc2 = (m1[0] + (offx - mercsizex / 2) * scale, m1[1] + (offy - mercsizey / 2) * scale) n = AirportMarker() n.latitude, n.longitude = mapper.merc2latlon(merc2, 13) n.x, n.y = (offx, offy) ns.append(n) error, A, T = customproj.solve(ns) matrix = list(A) + list(T) print "Fake projection:", matrix return matrix def showimg(self): adimg, cksum = request.params['adimg'].split(",") maptype = request.params['maptype'] variant = request.params['variant'] response.headers['Content-Type'] = 'image/png' response.headers['Pragma'] = '' response.headers['Cache-Control'] = 'max-age=120' if maptype == 'chart': return parse_landing_chart.get_chart_png(adimg, cksum) else: width, height = parse_landing_chart.get_width_height(adimg, cksum) projs = meta.Session.query(AirportProjection).filter( sa.and_(AirportProjection.user == session['user'], AirportProjection.mapchecksum == cksum)).all() assert len(projs) <= 1 if len(projs) == 1 and not all( [x == 0 for x in projs[0].matrix[4:6]]): matrix = projs[0].matrix print "Using real projection", matrix else: #scale = number of pixels per latlon-increment matrix = self.invent_matrix(cksum, variant) A = matrix[0:4] T = matrix[4:6] transform = customproj.Transform(A, T) llc = transform.to_latlon((width / 2, height / 2)) print "Center of map in pixels is on lat lon", llc ll1 = transform.to_latlon((0, 0)) ll2 = transform.to_latlon((0, height)) ll3 = transform.to_latlon((width, height)) ll4 = transform.to_latlon((width, 0)) im = transform_map.get_png(width, height, ll1, ll2, ll3, ll4) io = StringIO.StringIO() im.save(io, format='png') io.seek(0) return io.read() def save(self): print request.params ad = request.params['ad'] chartobj = None mapchecksum = request.params['mapchecksum'] for adobj in ec.get_airfields(): if adobj['name'] == ad: bb = False for adchart in adobj['adcharts'].values(): if adchart['checksum'] == mapchecksum: chartobj = adchart bb = True break if bb: break else: self.error("No such airport" + ad) marks = dict() for param, val in request.params.items(): if param in [ "save", "ad", 'mapchecksum', 'scroll_x', 'scroll_y', 'maptype', 'scale', 'north' ]: continue if param.startswith("del"): continue if param.startswith("set_"): x, y = [int(v) for v in param.split("_")[1:]] session['curadmarker'] = (x, y) session.save() continue if param == "add": xs = meta.Session.query(AirportMarker.x).filter( sa.and_(AirportMarker.user == session['user'], AirportMarker.airport == ad)).all() if xs: maxx = max(xs)[0] + 1 else: maxx = 0 marks[(maxx, 0)] = dict(latitude=None, longitude=None, x=maxx, y=0) session['curadmarker'] = (maxx, 0) session.save() continue sx, sy, attrib = re.match(ur"mark_(\d+)_(\d+)_(\w*)", param).groups() x = int(sx) y = int(sy) marks.setdefault((x, y), dict())[attrib] = val thresholds = dict() for rwy in adobj.get('runways', []): ends = rwy['ends'] for end in ends: thresholds[end['thr']] = mapper.from_str(end['pos']) for param, val in request.params.items(): if param.startswith("del_"): x, y = [int(v) for v in param.split("_")[1:]] marks.pop((x, y)) continue meta.Session.query(AirportMarker).filter( sa.and_(AirportMarker.user == session['user'], AirportMarker.airport == ad)).delete() ms = [] arppos = mapper.from_str(adobj['pos']) for (x, y), val in marks.items(): m = AirportMarker() m.user = session['user'] m.airport = ad m.mapchecksum = str(mapchecksum) m.x = int(val['x']) m.y = int(val['y']) m.latitude, w1 = parselatlon(val['latitude'], arppos, thresholds, 0) m.longitude, w2 = parselatlon(val['longitude'], arppos, thresholds, 1) if w1 or w2: m.weight = w1 + w2 else: m.weigth = 1 meta.Session.add(m) ms.append(m) proj = meta.Session.query(AirportProjection).filter( sa.and_(AirportProjection.user == session['user'], AirportProjection.airport == ad, AirportProjection.mapchecksum == str(mapchecksum))).one() try: proj.scale = float(request.params['scale'].strip()) except: proj.scale = None try: proj.north = float(request.params['north'].strip()) except: proj.north = None def both_lat_lon(x): return x.latitude and x.longitude def neither_lat_lon(x): return not x.latitude and not x.longitude def just_lat(x): return x.latitude and not x.longitude def just_lon(x): return not x.latitude and x.longitude ms = [m for m in ms if not neither_lat_lon(m)] """ if (len(ms)==4 and len([m for m in ms if just_lat(m)])==2 and len([m for m in ms if just_lon(m)])==2): extra=[] for m in ms: n=AirportMarker() n.x=m.x n.y=m.y if just_lat(m): n.latitude=m.latitude n.x+=1000 extra.append(n) if just_lon(m): n.y+=1000 n.longitude=m.longitude extra.append(n) ms.extend(extra) """ if len(ms) == 1 and both_lat_lon( ms[0]) and proj.scale and proj.north != None: print "Scale/north triggered" print "Adchart:", chartobj if chartobj != None: render_height = chartobj['render_height'] mark, = ms pixelpos = (mark.x, mark.y) mapsize = adchart.get('mapsize', (210, 297)) mapheight_meter = mapsize[1] / 1000.0 * proj.scale mapheight_km = mapheight_meter / 1000.0 merc = mapper.latlon2merc((mark.latitude, mark.longitude), 17) pixels = mapper.approx_scale(merc, 17, mapheight_km / 1.852) newmerc = (merc[0], merc[1] - pixels) northrad = proj.north / (180.0 / math.pi) newpixelpos = (pixelpos[0] + render_height * math.sin(northrad), pixelpos[1] - render_height * math.cos(northrad)) m = AirportMarker() m.x = newpixelpos[0] m.y = newpixelpos[1] latlon = mapper.merc2latlon(newmerc, 17) m.latitude = latlon[0] m.longitude = latlon[1] m.weight = 1 ms.append(m) if len(ms) == 2 and all(both_lat_lon(x) for x in ms): print "Have exactly two marks now" mark1, mark2 = ms lm1, lm2 = [ mapper.latlon2merc((mark.latitude, mark.longitude), 17) for mark in [mark1, mark2] ] ld = (lm2[0] - lm1[0], lm2[1] - lm1[1]) pd = (mark2.x - mark1.x, mark2.y - mark1.y) lm3 = (lm1[0] - ld[1], lm1[1] + ld[0]) pm3 = (mark1.x - pd[1], mark1.y + pd[0]) llm3 = mapper.merc2latlon(lm3, 17) m = AirportMarker() m.x = pm3[0] m.y = pm3[1] m.latitude, w1 = llm3[0], 1 m.longitude, w2 = llm3[1], 1 ms.append(m) print "delta pixels", pd print "delta latlon", ld print "extra end pixels", m.x, m.y print "extra end latlon", m.latitude, m.longitude eqns = 0 for m in ms: if both_lat_lon(m): eqns += 2 elif just_lat(m): eqns += 1 elif just_lon(m): eqns += 1 try: if eqns < 4: raise Exception("Unsolvable") error, A, T = customproj.solve(ms) matrix = list(A) + list(T) if proj.matrix: oldmatrix = list(proj.matrix) newmatrix = list(A) + list(T) diff = sum(abs(a - b) for a, b in zip(oldmatrix, newmatrix)) else: diff = 1e30 #enough to trigger update if diff > 1e-12: proj.matrix = tuple(newmatrix) proj.updated = datetime.utcnow().replace(microsecond=0) except Exception, cause: print "Couldn't solve projection equation %s" % (cause, ) proj.matrix = [1, 0, 0, 1, 0, 0] proj.updated = datetime.utcnow().replace(microsecond=0) meta.Session.add(proj) print "About to save", proj, "matrix:", proj.matrix, "time", proj.updated meta.Session.flush() meta.Session.commit() scroll_x = request.params['scroll_x'] scroll_y = request.params['scroll_y'] maptype = request.params['maptype'] print "scrolls", scroll_x, scroll_y redirect( h.url_for(controller='airportproj', action='show', ad=ad, checksum=mapchecksum, scroll_x=scroll_x, scroll_y=scroll_y, maptype=maptype))
def error(self, err): redirect(h.url_for(controller='airportproj', action="index", flash=err))