Exemplo n.º 1
0
    def weather(self):
        dummy, routes = get_route(tripuser(), request.params['tripname'])

        ret = []
        alts = request.params.get('alts', '')
        if alts == None:
            altvec = []
        else:
            altvec = alts.split(",")
        for route, altitude in zip(routes, altvec):
            #print("Looking for waypoint: %s"%(way.pos,))
            try:
                mapper.parse_elev(altitude)
            except mapper.NotAnAltitude, cause:
                ret.append(['', ''])
                continue  #skip this alt
            #N+1 selects....
            merc1 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14)
            merc2 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14)
            center = (0.5 * (merc1[0] + merc2[0]), 0.5 * (merc1[1] + merc2[1]))
            lat, lon = mapper.merc2latlon(center, 14)
            #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude)
            when = route.depart_dt + (route.arrive_dt - route.depart_dt) / 2
            dummy1, dummy2, we = gfs_weather.get_prognosis(when)
            if we == None:
                return ""
                #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey.
            else:
                try:
                    wi = we.get_wind(lat, lon, mapper.parse_elev(altitude))
                except:
                    print traceback.format_exc()
                    return ""
                #print "Got winds:",wi
                ret.append([wi['direction'], wi['knots']])
Exemplo n.º 2
0
 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')
Exemplo n.º 3
0
    def weather(self):
        dummy,routes=get_route(tripuser(),request.params['tripname'])

        ret=[]
        alts=request.params.get('alts','')
        if alts==None:
            altvec=[]
        else:
            altvec=alts.split(",")
        for route,altitude in zip(routes,altvec):
             #print("Looking for waypoint: %s"%(way.pos,))
             try:
                mapper.parse_elev(altitude)
             except mapper.NotAnAltitude,cause:
                 ret.append(['',''])                 
                 continue #skip this alt
             #N+1 selects....
             merc1=mapper.latlon2merc(mapper.from_str(route.a.pos),14)
             merc2=mapper.latlon2merc(mapper.from_str(route.a.pos),14)
             center=(0.5*(merc1[0]+merc2[0]),0.5*(merc1[1]+merc2[1]))
             lat,lon=mapper.merc2latlon(center,14)
             #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude)
             when=route.depart_dt+(route.arrive_dt-route.depart_dt)/2
             dummy1,dummy2,we=gfs_weather.get_prognosis(when)
             if we==None:
                 return ""; #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey.
             else:
                 try:
                     wi=we.get_wind(lat,lon,mapper.parse_elev(altitude))
                 except:
                     print traceback.format_exc()
                     return ""
                 #print "Got winds:",wi
                 ret.append([wi['direction'],wi['knots']])
Exemplo n.º 4
0
    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')
Exemplo n.º 5
0
    def get_airspace(self):
        utcnow = datetime.utcnow()
        try:
            zoomlevel = int(request.params['zoom'])
        except Exception:
            zoomlevel = session.get('zoom', 5)
        lat = float(request.params.get('lat'))
        lon = float(request.params.get('lon'))
        clickmerc = mapper.latlon2merc((lat, lon), zoomlevel)
        user = session.get('user', None)
        out = []
        spaces = chain(get_airspaces(lat, lon),
                       userdata.get_airspaces(lat, lon, user))
        print "Spaces:", spaces

        def anydate(s):
            if not 'date' in s: return ""
            d = s['date']
            age = utcnow - d
            if age > timedelta(367):
                return "<span style=\"font-size:10px\">[%d]</span>" % (
                    d.year, )
            if age > timedelta(2):
                return "<span style=\"font-size:10px\">[%d%02d%02d]</span>" % (
                    d.year, d.month, d.day)
            return ""

        spacelist = spaces
        spaces = u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>" %
                          (space['name'], anydate(space), space['floor'],
                           space['ceiling'], format_freqs(space['freqs']))
                          for space in sorted(spacelist, key=sort_airspace_key)
                          if space['type'] != 'sector')

        #sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
        #        space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
        #            spacelist,key=sort_airspace_key) if space['type']=='sectoasdfr')

        try:
            sectors = u"".join(
                u"<li><b>%s</b>%s: %s - %s%s</li>" %
                (space['name'], anydate(space), space['floor'],
                 space['ceiling'], format_freqs(space['freqs']))
                for space in sorted(spacelist, key=sort_airspace_key)
                if space['type'] == 'sector')
            if sectors != "":
                sectors = "<b>Sectors:</b><ul>" + sectors + "</ul>"
        except:
            print traceback.format_exc()
            sectors = ""

        if spaces == "":
            spaces = "No airspace found"

        mapviewurl = h.url_for(controller="mapview", action="index")

        notamlist = chain(get_notam_areas(lat, lon),
                          get_notampoints(lat, lon, zoomlevel))
        notams = dict([(n['notam'].strip(), (n['notam_ordinal'],
                                             n['notam_line']))
                       for n in notamlist])

        notamareas = "".join(
            "<li>%s <b><u><a href=\"javascript:navigate_to('%s#notam')\">Link</a></u></b></li>"
            % (text,
               h.url_for(controller="notam",
                         action="show_ctx",
                         backlink=mapviewurl,
                         notam=notam,
                         line=line)) for text, (notam, line) in notams.items())
        if notamareas != "":
            notamareas = "<b>Area Notams:</b><ul>" + notamareas + "</ul>"

        aip_sup_strs = "".join([
            "<li>%s <a href=\"%s\">link</a></li>" %
            (x['name'], x['url'].replace(" ", "%20"))
            for x in get_aip_sup_areas(lat, lon)
        ])
        if aip_sup_strs:
            aip_sup_strs = "<b>AIP SUP:</b><ul>" + aip_sup_strs + "</ul>"

        obstbytype = dict()
        for obst in chain(get_obstacles(lat, lon, zoomlevel),
                          userdata.get_obstacles(lat, lon, zoomlevel, user)):
            obstbytype.setdefault(obst['kind'], []).append(obst)
            print "processing", obst
        obstacles = []
        if len(obstbytype):
            for kind, obsts in sorted(obstbytype.items()):
                obstacles.append("<b>" + kind + ":</b>")
                obstacles.append(u"<ul>")
                for obst in obsts:
                    obstacles.append(u"<li><b>%s</b>: %s ft</li>" %
                                     (obst['name'], obst['elev']))
                obstacles.append(u"</ul>")

        tracks = []
        if session.get('showtrack', None) != None:
            track = session.get('showtrack')
            #print "%d points"%(len(track.points))
            mindiff = 1e30
            found = dict()
            hdg = 0
            speed = 0
            clickvec = Vertex(int(clickmerc[0]), int(clickmerc[1]))
            if len(track.points) > 0 and len(track.points[0]) == 2:
                pass  #Old style track, not supported anymore
            else:
                for a, b in izip(track.points, track.points[1:]):
                    merc = mapper.latlon2merc(a[0], zoomlevel)
                    nextmerc = mapper.latlon2merc(b[0], zoomlevel)
                    l = Line(Vertex(int(merc[0]), int(merc[1])),
                             Vertex(int(nextmerc[0]), int(nextmerc[1])))
                    diff = l.approx_dist(clickvec)

                    if diff < mindiff:
                        mindiff = diff
                        found = (a, b)

                if mindiff < 10:
                    tracks.append(
                        u"<b>GPS track:</b><ul><li>%(when)s - %(altitude)d ft hdg:%(heading)03d spd: %(speed)d kt</li></ul>"
                        % (get_stats(*found)))

        airports = []
        fields = list(
            chain(get_airfields(lat, lon, zoomlevel),
                  userdata.get_airfields(lat, lon, zoomlevel, user)))
        if len(fields):
            airports.append("<b>Airfield:</b><ul>")
            for airp in fields:
                #print "clicked on ",airp
                linksstr = ""
                links = []
                if 'flygkartan_id' in airp:
                    links.append(('http://www.flygkartan.se/0%s' %
                                  (airp['flygkartan_id'].strip(), ),
                                  'www.flygkartan.se'))
                if 'aiptexturl' in airp:
                    links.append((airp['aiptexturl'], 'AIP Text'))
                if 'aipvacurl' in airp:
                    links.append(
                        (airp['aipvacurl'], 'AIP Visual Approach Chart'))

                if False and 'aipsup' in airp:
                    #Using AIP SUP for opening hours has stopped.
                    links.append((extracted_cache.get_se_aip_sup_hours_url(),
                                  "AIP SUP Opening Hours"))
                weather = ""
                if airp.get('icao', 'ZZZZ').upper() != 'ZZZZ':
                    icao = airp['icao'].upper()
                    metar = metartaf.get_metar(icao)
                    taf = metartaf.get_taf(icao)
                    weather = "<table>"

                    def colorize(item, colfac=1):
                        if item == None:
                            col = "ffffff"
                            agestr = ""
                        else:
                            age = metartaf.get_data_age(item)
                            if age == None:
                                col = "ffffff"
                                agestr = ""
                            elif age < timedelta(0, 60 * 35 * colfac):
                                col = "c5c5c5"
                                agestr = "%d minutes" % (int(age.seconds / 60))
                            elif age < timedelta(0, 60 * 60 * colfac):
                                col = "ffff30"
                                agestr = "%d minutes" % (int(age.seconds / 60))
                            else:
                                col = "ff3030"
                                if age < timedelta(2):
                                    if age < timedelta(0, 3600 * 1.5):
                                        agestr = "%d minutes" % int(
                                            age.seconds / 60)
                                    else:
                                        agestr = "%d hours" % int(
                                            0.5 + (age.seconds) / 3600.0)
                                else:
                                    agestr = "%d days" % (int(age.days))

                        return "style=\"background:#" + col + "\" title=\"" + agestr + " old.\""

                    if taf and taf.text:
                        weather += "<tr valign=\"top\"><td>TAF:</td><td " + colorize(
                            taf, 5) + ">" + taf.text + "</td></tr>"
                    if metar and metar.text:
                        weather += "<tr valign=\"top\"><td>METAR:</td><td " + colorize(
                            metar) + ">" + metar.text + "</td></tr>"

                    ack_cnt = meta.Session.query(
                        NotamAck.appearnotam, NotamAck.appearline,
                        sa.func.count('*').label('acks')).filter(
                            NotamAck.user == session.get(
                                'user', None)).group_by(
                                    NotamAck.appearnotam,
                                    NotamAck.appearline).subquery()
                    notams = meta.Session.query(
                        NotamUpdate, ack_cnt.c.acks, Notam.downloaded
                    ).outerjoin(
                        (ack_cnt,
                         sa.and_(
                             NotamUpdate.appearnotam == ack_cnt.c.appearnotam,
                             NotamUpdate.appearline == ack_cnt.c.appearline))
                    ).outerjoin(
                        (Notam,
                         Notam.ordinal == NotamUpdate.appearnotam)).order_by(
                             sa.desc(Notam.downloaded)).filter(
                                 sa.and_(
                                     NotamUpdate.disappearnotam == sa.null(),
                                     NotamUpdate.category.like(icao.upper() +
                                                               "/%"))).all()
                    print "notams:", repr(notams)
                    if notams:
                        nots = []
                        for notam, ack, downloaded in notams:
                            nots.append(
                                "<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;\">%s</div>"
                                % (cgi.escape(notam.text)))

                        weather += "<tr valign=\"top\"><td colspan=\"2\">NOTAM:</td></tr><tr><td colspan=\"2\">%s</td></tr>" % (
                            "".join(nots))

                    weather += "</table>"
                    meta.Session.flush()
                    meta.Session.commit()

                if len(links) > 0 and 'icao' in airp:
                    linksstr = helpers.foldable_links(airp['icao'] + "links",
                                                      links)

                rwys = []
                if 'runways' in airp:
                    for rwy in airp['runways']:
                        ends = []
                        for end in rwy['ends']:
                            ends.append(end['thr'])
                        surf = ""
                        if 'surface' in rwy:
                            surf = "(" + rwy['surface'] + ")"
                        rwys.append("/".join(ends) + surf)

                if len(rwys):
                    rwys = ["<b> Runways</b>: "] + [", ".join(rwys)]
                remark = ""
                if airp.get('remark'):
                    remark = "<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;background-color:#ffffe0\"><b>Remark:</b> " + cgi.escape(
                        airp['remark']) + "</div>"

                airports.append(u"<li><b>%s</b> - %s%s%s%s%s</li>" %
                                (airp.get('icao', 'ZZZZ'), airp['name'],
                                 linksstr, remark, " ".join(rwys), weather))
            airports.append("</ul>")

        sigpoints = []
        sigps = list(
            chain(get_sigpoints(lat, lon, zoomlevel),
                  userdata.get_sigpoints(lat, lon, zoomlevel, user)))
        if len(sigps):
            sigpoints.append("<b>Sig. points</b><ul>")
            for sigp in sigps:
                sigpoints.append(
                    u"<li><b>%s</b>(%s)</li>" %
                    (sigp['name'], sigp.get('kind', 'unknown point')))
            sigpoints.append("</ul>")

        firs = []
        for fir in list(get_firs(
            (lat, lon))) + list(userdata.get_firs(lat, lon, user)):
            if 'icao' in fir:
                firs.append("%s (%s)" % (fir['name'], fir['icao']))
        if not firs:
            firs.append("Unknown")

        variation = '?'
        terrelev = get_terrain_elev((lat, lon), zoomlevel)
        try:
            varf = geomag.calc_declination((lat, lon), utcnow,
                                           (terrelev + 1000))
            variation = u"%+.1f°" % (varf, )
        except Exception:
            pass

        weather = ""
        try:
            when, valid, fct = gfs_weather.get_prognosis(datetime.utcnow())
            qnh = fct.get_qnh(lat, lon)
            out = [
                "<b>Weather</b><br/>Forecast: %sZ, valid: %sZ<br />" %
                (when.strftime("%Y-%m-%d %H:%M"), valid.strftime("%H:%M"))
            ]
            try:
                out.append("Surface wind: %.0f deg, %.1f knots<br />" %
                           fct.get_surfacewind(lat, lon))
                out.append("Surface RH: %.0f%%<br />" %
                           (fct.get_surfacerh(lat, lon), ))
            except:
                print traceback.format_exc()
            out.append("<ul>")
            for fl, dir, st, temp in fct.get_winds(lat, lon):
                out.append("<li>FL%02d: %03d deg, %.1fkt, %.1f &#176;C" %
                           (int(fl), int(dir), float(st), temp))
            out.append("</ul>QNH: %d<br/><br/>" % (qnh, ))
            weather = "".join(out)
        except Exception:
            print traceback.format_exc()

        return "<b>Airspace:</b><ul><li><b>FIR:</b> %s</li>%s</ul>%s%s%s%s%s%s%s<br/>%s<b>Terrain: %s ft, Var: %s</b>" % (
            ", ".join(firs), spaces, sectors, aip_sup_strs, "".join(obstacles),
            "".join(airports), "".join(tracks), "".join(sigpoints), notamareas,
            weather, terrelev, variation)
Exemplo n.º 6
0
    def get_airspace(self):
        utcnow=datetime.utcnow()
        try:
            zoomlevel=int(request.params['zoom'])
        except Exception:
            zoomlevel=session.get('zoom',5)
        lat=float(request.params.get('lat'))
        lon=float(request.params.get('lon'))
        clickmerc=mapper.latlon2merc((lat,lon),zoomlevel)
        user=session.get('user',None)
        out=[]
        spaces=chain(get_airspaces(lat,lon),userdata.get_airspaces(lat,lon,user))
        print "Spaces:",spaces
        def anydate(s):
            if not 'date' in s: return ""
            d=s['date']
            age=utcnow-d            
            if age>timedelta(367):
                return "<span style=\"font-size:10px\">[%d]</span>"%(d.year,)
            if age>timedelta(2):                
                return "<span style=\"font-size:10px\">[%d%02d%02d]</span>"%(
                        d.year,d.month,d.day)
            return ""
        spacelist=spaces
        spaces=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
                space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
                    spacelist,key=sort_airspace_key) if space['type']!='sector')


        #sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
        #        space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
        #            spacelist,key=sort_airspace_key) if space['type']=='sectoasdfr')

        try:
            sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
                   space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
                  spacelist,key=sort_airspace_key) if space['type']=='sector')
            if sectors!="":
                sectors="<b>Sectors:</b><ul>"+sectors+"</ul>"
        except:
            print traceback.format_exc()
            sectors=""

        if spaces=="":
            spaces="No airspace found"

            
        mapviewurl=h.url_for(controller="mapview",action="index")

        
        notamlist=chain(get_notam_areas(lat,lon),get_notampoints(lat,lon,zoomlevel))
        notams=dict([(n['notam'].strip(),(n['notam_ordinal'],n['notam_line']) ) for n in notamlist])

        
        notamareas="".join("<li>%s <b><u><a href=\"javascript:navigate_to('%s#notam')\">Link</a></u></b></li>"%(
            text,h.url_for(controller="notam",action="show_ctx",backlink=mapviewurl,notam=notam,line=line)) for text,(notam,line) in notams.items())
        if notamareas!="":
            notamareas="<b>Area Notams:</b><ul>"+notamareas+"</ul>"

        aip_sup_strs="".join(["<li>%s <a href=\"%s\">link</a></li>"%(x['name'],x['url'].replace(" ","%20")) for x in get_aip_sup_areas(lat,lon)])
        if aip_sup_strs:
            aip_sup_strs="<b>AIP SUP:</b><ul>"+aip_sup_strs+"</ul>"
         
        obstbytype=dict()
        for obst in chain(get_obstacles(lat,lon,zoomlevel),userdata.get_obstacles(lat,lon,zoomlevel,user)):
            obstbytype.setdefault(obst['kind'],[]).append(obst)
            print "processing",obst
        obstacles=[]
        if len(obstbytype):
            for kind,obsts in sorted(obstbytype.items()):
                obstacles.append("<b>"+kind+":</b>")
                obstacles.append(u"<ul>")
                for obst in obsts:
                    obstacles.append(u"<li><b>%s</b>: %s ft</li>"%(obst['name'],obst['elev'])) 
                obstacles.append(u"</ul>")

        tracks=[]
        if session.get('showtrack',None)!=None:                
            track=session.get('showtrack')
            #print "%d points"%(len(track.points))
            mindiff=1e30
            found=dict()
            hdg=0
            speed=0
            clickvec=Vertex(int(clickmerc[0]),int(clickmerc[1]))
            if len(track.points)>0 and len(track.points[0])==2:                
                pass #Old style track, not supported anymore
            else:
                for a,b in izip(track.points,track.points[1:]): 
                    merc=mapper.latlon2merc(a[0],zoomlevel)
                    nextmerc=mapper.latlon2merc(b[0],zoomlevel)
                    l=Line(Vertex(int(merc[0]),int(merc[1])),Vertex(int(nextmerc[0]),int(nextmerc[1])))
                    diff=l.approx_dist(clickvec)                

                    if diff<mindiff:
                        mindiff=diff
                        found=(a,b)

                if mindiff<10:
                    tracks.append(u"<b>GPS track:</b><ul><li>%(when)s - %(altitude)d ft hdg:%(heading)03d spd: %(speed)d kt</li></ul>"%(get_stats(*found)))
                                                  

        airports=[]
        fields=list(chain(get_airfields(lat,lon,zoomlevel),userdata.get_airfields(lat,lon,zoomlevel,user)))
        if len(fields):
            airports.append("<b>Airfield:</b><ul>")
            for airp in fields:
                #print "clicked on ",airp
                linksstr=""
                links=[]
                if 'flygkartan_id' in airp:
                    links.append(('http://www.flygkartan.se/0%s'%(airp['flygkartan_id'].strip(),),
                      'www.flygkartan.se'))
                if 'aiptexturl' in airp:
                    links.append((airp['aiptexturl'],
                      'AIP Text'))
                if 'aipvacurl' in airp:
                    links.append((airp['aipvacurl'],
                      'AIP Visual Approach Chart'))
                    
                if False and 'aipsup' in airp:
                    #Using AIP SUP for opening hours has stopped.
                    links.append((
                        extracted_cache.get_se_aip_sup_hours_url(),
                        "AIP SUP Opening Hours"))
                weather=""
                if airp.get('icao','ZZZZ').upper()!='ZZZZ':
                    icao=airp['icao'].upper()
                    metar=metartaf.get_metar(icao)
                    taf=metartaf.get_taf(icao)
                    weather="<table>"
                    
                    def colorize(item,colfac=1):
                        if item==None:
                            col="ffffff"
                            agestr=""
                        else:
                            age=metartaf.get_data_age(item)
                            if age==None:
                                col="ffffff"
                                agestr=""                                
                            elif age<timedelta(0,60*35*colfac):
                                col="c5c5c5"
                                agestr="%d minutes"%(int(age.seconds/60))
                            elif age<timedelta(0,60*60*colfac):
                                col="ffff30"
                                agestr="%d minutes"%(int(age.seconds/60))
                            else:
                                col="ff3030"
                                if age<timedelta(2):
                                    if age<timedelta(0,3600*1.5):
                                        agestr="%d minutes"%int(age.seconds/60)
                                    else:
                                        agestr="%d hours"%int(0.5+(age.seconds)/3600.0)
                                else:
                                    agestr="%d days"%(int(age.days))
                            
                        return "style=\"background:#"+col+"\" title=\""+agestr+" old.\""
                
                    if taf and taf.text:
                        weather+="<tr valign=\"top\"><td>TAF:</td><td "+colorize(taf,5)+">"+taf.text+"</td></tr>"
                    if metar and metar.text:
                        weather+="<tr valign=\"top\"><td>METAR:</td><td "+colorize(metar)+">"+metar.text+"</td></tr>"
                        
                        
                    ack_cnt = meta.Session.query(NotamAck.appearnotam,NotamAck.appearline,sa.func.count('*').label('acks')).filter(NotamAck.user==session.get('user',None)).group_by(NotamAck.appearnotam,NotamAck.appearline).subquery()
                    notams=meta.Session.query(NotamUpdate,ack_cnt.c.acks,Notam.downloaded).outerjoin(
                        (ack_cnt,sa.and_(
                            NotamUpdate.appearnotam==ack_cnt.c.appearnotam,
                            NotamUpdate.appearline==ack_cnt.c.appearline))).outerjoin(
                        (Notam,Notam.ordinal==NotamUpdate.appearnotam)
                         ).order_by(sa.desc(Notam.downloaded)).filter(
                                sa.and_(NotamUpdate.disappearnotam==sa.null(),
                                        NotamUpdate.category.like(icao.upper()+"/%")
                                        )).all()
                    print "notams:",repr(notams)
                    if notams:
                        nots=[]
                        for notam,ack,downloaded in notams:
                            nots.append("<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;\">%s</div>"%(cgi.escape(notam.text)))
                        
                        weather+="<tr valign=\"top\"><td colspan=\"2\">NOTAM:</td></tr><tr><td colspan=\"2\">%s</td></tr>"%("".join(nots))
                    
                    weather+="</table>"
                    meta.Session.flush()
                    meta.Session.commit()
                    
                if len(links)>0 and 'icao' in airp:                    
                    linksstr=helpers.foldable_links(airp['icao']+"links",links)

                rwys=[]
                if 'runways' in airp:
                    for rwy in airp['runways']:
                        ends=[]                        
                        for end in rwy['ends']:
                            ends.append(end['thr'])
                        surf=""
                        if 'surface' in rwy:
                            surf="("+rwy['surface']+")"
                        rwys.append("/".join(ends)+surf)
                            
                if len(rwys):                    
                    rwys=["<b> Runways</b>: "]+[", ".join(rwys)]
                remark=""
                if airp.get('remark'):
                    remark="<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;background-color:#ffffe0\"><b>Remark:</b> "+cgi.escape(airp['remark'])+"</div>"
                
                
                
                airports.append(u"<li><b>%s</b> - %s%s%s%s%s</li>"%(airp.get('icao','ZZZZ'),airp['name'],linksstr,remark," ".join(rwys),weather))
            airports.append("</ul>")
        
        sigpoints=[]
        sigps=list(chain(get_sigpoints(lat,lon,zoomlevel),userdata.get_sigpoints(lat,lon,zoomlevel,user)))
        if len(sigps):
            sigpoints.append("<b>Sig. points</b><ul>")
            for sigp in sigps:
                sigpoints.append(u"<li><b>%s</b>(%s)</li>"%(sigp['name'],sigp.get('kind','unknown point')))
            sigpoints.append("</ul>")
       

        firs=[]        
        for fir in list(get_firs((lat,lon)))+list(userdata.get_firs(lat,lon,user)):
            if 'icao' in fir:
                firs.append("%s (%s)"%(fir['name'],fir['icao']))        
        if not firs:
            firs.append("Unknown")
            
        variation='?'
        terrelev=get_terrain_elev((lat,lon),zoomlevel)
        try:
            varf=geomag.calc_declination((lat,lon),utcnow,(terrelev+1000))
            variation=u"%+.1f°"%(varf,)
        except Exception:
            pass
        
        weather=""
        try:
            when,valid,fct=gfs_weather.get_prognosis(datetime.utcnow())
            qnh=fct.get_qnh(lat,lon)
            out=["<b>Weather</b><br/>Forecast: %sZ, valid: %sZ<br />"%(when.strftime("%Y-%m-%d %H:%M"),valid.strftime("%H:%M"))]
            try:                
                out.append("Surface wind: %.0f deg, %.1f knots<br />"%fct.get_surfacewind(lat,lon))
                out.append("Surface RH: %.0f%%<br />"%(fct.get_surfacerh(lat,lon),))
            except:
                print traceback.format_exc()
            out.append("<ul>")
            for fl,dir,st,temp in fct.get_winds(lat,lon):
                out.append("<li>FL%02d: %03d deg, %.1fkt, %.1f &#176;C"%(int(fl),int(dir),float(st),temp))            
            out.append("</ul>QNH: %d<br/><br/>"%(qnh,))
            weather="".join(out)
        except Exception:
            print traceback.format_exc()
        
        return "<b>Airspace:</b><ul><li><b>FIR:</b> %s</li>%s</ul>%s%s%s%s%s%s%s<br/>%s<b>Terrain: %s ft, Var: %s</b>"%(", ".join(firs),spaces,sectors,aip_sup_strs,"".join(obstacles),"".join(airports),"".join(tracks),"".join(sigpoints),notamareas,weather,terrelev,variation)