Example #1
0
def upload_( request ):
    if request.method == "POST":
        if request.is_ajax( ):
            # the file is stored raw in the request
            upload = request
            is_raw = True
            # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
            try:
                filename = request.GET[ 'qqfile' ]
            except KeyError: 
                return HttpResponseBadRequest( "AJAX request not valid" )
            # not an ajax upload, so it was the "basic" iframe version with submission via form
        else:
            is_raw = False
            if len( request.FILES ) == 1:
                # FILES is a dictionary in Django but Ajax Upload gives the uploaded file an
                # ID based on a random number, so it cannot be guessed here in the code.
                # Rather than editing Ajax Upload to pass the ID in the querystring,
                # observer that each upload is a separate request,
                # so FILES should only have one entry.
                # Thus, we can just grab the first (and only) value in the dict.
                upload = request.FILES.values( )[ 0 ]
            else:
                raise Http404( "Bad Upload" )
            filename = upload.name

        (tmp_id, tmp_up) = tempfile.mkstemp(suffix='-' + filename, dir="uploads")
        dfilename = tmp_up
        os.close(tmp_id)
    
        # save the file
        success = save_upload( upload, dfilename, is_raw )

        track = IGC(open(dfilename)).track()
        
        kmz = flights2kmz([Flight(track)],
                          roots=[],
                          tz_offset=0,
                          task=None)
        (tmp_id, tmp_up2) = tempfile.mkstemp(suffix='-' + filename + '.kmz', dir="uploads")
        os.close(tmp_id)
        kmz.write(tmp_up2, '2.2')
        os.unlink(tmp_up)

        ret_json = { 'success': success,
                     'track': tmp_up2.replace(os.path.join(os.getcwd(), 'uploads'),'/static/') }
        r = json.dumps( ret_json )

        return HttpResponse(r, mimetype='application/json' )
    def getResult(self):
        kwargs = {}
        kwargs['filename'] = "FAKE NAME"

        t = track.Track(self.coords, **kwargs)
 
        f = Flight(t)
        
        try:
            kmz = flights2kmz([f], roots=[], tz_offset=0, task=None)
            sio = StringIO.StringIO()

            kmz.write("TEMP-TEST", '2.2')
        except Exception,e:
            traceback.print_exc()
    def getResult(self):
        kwargs = {}
        kwargs['filename'] = "FAKE NAME"

        t = track.Track(self.coords, **kwargs)

        f = Flight(t)

        try:
            kmz = flights2kmz([f], roots=[], tz_offset=0, task=None)
            sio = StringIO.StringIO()

            kmz.write("TEMP-TEST", '2.2')
        except Exception, e:
            traceback.print_exc()
Example #4
0
def main(argv):
    parser = optparse.OptionParser(
            usage='Usage: %prog [options] flightID',
            description='IGC to Google Earth converter (Leonardo integration)')
    parser.add_option('-o', '--output', metavar='FILENAME',
                      help='set output filename')
    parser.add_option('-n', '--name', metavar='STRING')
    parser.add_option('-i', '--icon', metavar='URL')
    parser.add_option('-u', '--url', metavar='URL', help='set URL')
    parser.add_option('-d', '--directory', metavar='PATH', help='set directory')
    parser.add_option('-e', '--engine', metavar='URL', help='set engine')
    parser.add_option('-z', '--tz-offset', metavar='HOURS', type='int',
                      help='set timezone offset')
    parser.add_option('-t', '--table-prefix', metavar='STRING',
                      help='set table prefix')
    parser.add_option('-x', '--igc-suffix', metavar='STRING',
                      help='set IGC file suffix')
    parser.add_option('-I', '--igc-path', metavar='STRING',
                      help='set IGC path')
    parser.add_option('-P', '--photos-path', metavar='STRING',
                      help='set photos path')
    parser.add_option('-U', '--photos-url', metavar='STRING',
                      help='set photos URL')
    parser.set_defaults(output='igc2kmz.kmz')
    parser.set_defaults(name=DEFAULT_NAME)
    parser.set_defaults(icon=DEFAULT_ICON)
    parser.set_defaults(url=DEFAULT_URL)
    parser.set_defaults(directory=DEFAULT_DIRECTORY)
    parser.set_defaults(tz_offset=0)
    parser.set_defaults(table_prefix=DEFAULT_TABLE_PREFIX)
    parser.set_defaults(igc_path=DEFAULT_IGC_PATH)
    parser.set_defaults(photos_path=DEFAULT_PHOTOS_PATH)
    parser.set_defaults(photos_url=DEFAULT_PHOTOS_URL)
    parser.set_defaults(igc_suffix='.saned.full.igc')
    options, args = parser.parse_args(argv)
    #
    flights_dir = os.path.join(options.directory,
                               'modules', 'leonardo', 'flights')
    #
    roots = []
    roots.append(make_banner(options))
    #
    metadata = MetaData(options.engine)
    pilots_table = Table(options.table_prefix + '_pilots', metadata,
                         autoload=True)
    flights_table = Table(options.table_prefix + '_flights', metadata,
                          autoload=True)
    flights_score_table = Table(options.table_prefix + '_flights_score',
                                metadata, autoload=True)
    photos_table = Table(options.table_prefix + '_photos', metadata,
                         autoload=True)
    waypoints_table = Table(options.table_prefix + '_waypoints', metadata,
                            autoload=True)
    #
    flights = []
    for flightID in args[1:]:
        select = flights_table.select(flights_table.c.ID == int(flightID))
        flight_row = select.execute().fetchone()
        if flight_row is None:
            raise KeyError, id
        if flight_row.userServerID:
            pilot_id = '%(userServerID)d_%(userID)d' % flight_row
        else:
            pilot_id = flight_row.userID
        substitutions = {
                'PILOTID': str(pilot_id),
                'YEAR': str(flight_row.DATE.year),
                }
        igc_path = os.path.join(options.directory,
                                substitute(options.igc_path, substitutions),
                                flight_row.filename + options.igc_suffix)
        track = IGC(open(igc_path), date=flight_row.DATE).track()
        flight = Flight(track)
        flight.glider_type = flight_row.glider
        flight.url = options.url + SHOW_FLIGHT_URL % flight_row
        #
        select = pilots_table.select((pilots_table.c.pilotID
                                     == flight_row.userID) &
                                     (pilots_table.c.serverID
                                     == flight_row.userServerID))
        pilot_row = select.execute().fetchone()
        if pilot_row is None:
            raise KeyError, '(%(userID)s, %(userServerID)s)' % flight_row
        flight.pilot_name = '%(FirstName)s %(LastName)s' % pilot_row
        #
        routes = []
        select = flights_score_table.select(flights_score_table.c.flightID
                                            == flight_row.ID)
        for flight_score_row in select.execute().fetchall():
            route_name = ROUTE_NAME[flight_score_row.type]
            league = LEAGUE[flight_score_row.method]
            distance = flight_score_row.distance
            score = flight_score_row.score
            multiplier = round(score / distance, 2)
            circuit = CIRCUIT[flight_score_row.type]
            tps = []
            for i in xrange(1, 8):
                m = B_RECORD_RE.match(flight_score_row['turnpoint%d' % i])
                if not m:
                    continue
                time = datetime.time(*map(int, m.group(1, 2, 3)))
                dt = datetime.datetime.combine(flight_row.DATE, time)
                lat = int(m.group(4)) + int(m.group(5)) / 60000.0
                if m.group(6) == 'S':
                    lat = -lat
                lon = int(m.group(7)) + int(m.group(8)) / 60000.0
                if m.group(9) == 'W':
                    lon = -lon
                coord = Coord.deg(lat, lon, 0, dt)
                name = 'Start' if i == 1 else 'TP%d' % (i - 1)
                tp = Turnpoint(name, coord)
                tps.append(tp)
            tps[-1].name = 'Finish'
            route = Route(route_name, league, distance, multiplier, score,
                          circuit, tps)
            routes.append(route)
        flight.xc = XC(routes)
        #
        if flight_row.hasPhotos:
            select = photos_table.select(photos_table.c.flightID
                                         == flight_row.ID)
            for photo_row in select.execute().fetchall():
                photo_url = options.url \
                        + substitute(options.photos_url, substitutions) \
                        + '/' + photo_row.name
                photo_path = os.path.join(options.directory,
                                          substitute(options.photos_path, substitutions),
                                          photo_row.name)
                photo = Photo(photo_url, path=photo_path)
                if photo_row.description:
                    photo.description = photo_row.description
                flight.photos.append(photo)
        #
        flights.append(flight)
        #
        select = waypoints_table.select(waypoints_table.c.ID
                                        == flight_row.takeoffID)
        takeoff_row = select.execute().fetchone()
        if takeoff_row:
            roots.append(make_takeoff_placemark(takeoff_row))
    #
    kmz = flights2kmz(flights, roots=roots, tz_offset=options.tz_offset)
    kmz.write(options.output, '2.2')
Example #5
0
def main(argv):
    parser = optparse.OptionParser(
            usage='Usage: %prog [options]',
            description="IGC to Google Earth converter")
    parser.add_option('-o', '--output', metavar='FILENAME',
            help='set output filename')
    parser.add_option('-z', '--tz-offset', metavar='HOURS', type='int',
            help='set timezone offset')
    parser.add_option('-r', '--root', metavar='FILENAME',
            action='append', dest='roots',
            help='add root element')
    parser.add_option('-t', '--task', metavar='FILENAME',
            help='set task')
    group = optparse.OptionGroup(parser, 'Per-flight options')
    group.add_option('-i', '--igc', metavar='FILENAME', type='string',
            action='callback', callback=add_flight,
            help='set flight IGC file')
    group.add_option('-n', '--pilot-name', metavar='STRING', type='string',
            action='callback', callback=set_flight_option,
            help='set pilot name')
    group.add_option('-g', '--glider-type', metavar='STRING', type='string',
            action='callback', callback=set_flight_option,
            help='set glider type')
    group.add_option('-c', '--color', metavar='COLOR', type='string',
            action='callback', callback=set_flight_option,
            help='set track line color')
    group.add_option('-w', '--width', metavar='INTEGER', type='int',
            action='callback', callback=set_flight_option,
            help='set track line width')
    group.add_option('-u', '--url', metavar='URL', type='string',
            action='callback', callback=set_flight_option,
            help='set flight URL')
    group.add_option('-x', '--xc', metavar='FILENAME', type='string',
            action='callback', callback=set_flight_xc,
            help='set flight XC')
    parser.add_option_group(group)
    group = optparse.OptionGroup(parser, 'Per-photo options')
    group.add_option('-p', '--photo', metavar='URL', type='string',
            action='callback', callback=add_photo,
            help='add photo')
    group.add_option('-d', '--description', metavar='STRING', type='string',
            action='callback', callback=set_photo_option,
            help='set photo comment')
    parser.add_option_group(group)
    #
    parser.set_defaults(flights=[])
    parser.set_defaults(output='igc2kmz.kmz')
    parser.set_defaults(roots=[])
    parser.set_defaults(tz_offset=0)
    #
    options, args = parser.parse_args(argv)
    if len(options.flights) == 0:
        parser.error('no flights specified')
    if len(args) != 1:
        parser.error('extra arguments on command line: %s' % repr(args[1:]))
    #
    roots = [Verbatim(open(root).read()) for root in options.roots]
    task = Task.from_file(open(options.task)) if options.task else None
    kmz = flights2kmz(options.flights,
                      roots=roots,
                      tz_offset=options.tz_offset,
                      task=task)
    kmz.write(options.output, '2.2')
Example #6
0
def main(argv):
    parser = optparse.OptionParser(
        usage='Usage: %prog [options] flightID',
        description='IGC to Google Earth converter (Leonardo integration)')
    parser.add_option('-o',
                      '--output',
                      metavar='FILENAME',
                      help='set output filename')
    parser.add_option('-n', '--name', metavar='STRING')
    parser.add_option('-i', '--icon', metavar='URL')
    parser.add_option('-u', '--url', metavar='URL', help='set URL')
    parser.add_option('-d',
                      '--directory',
                      metavar='PATH',
                      help='set directory')
    parser.add_option('-e', '--engine', metavar='URL', help='set engine')
    parser.add_option('-z',
                      '--tz-offset',
                      metavar='HOURS',
                      type='int',
                      help='set timezone offset')
    parser.add_option('-t',
                      '--table-prefix',
                      metavar='STRING',
                      help='set table prefix')
    parser.add_option('-x',
                      '--igc-suffix',
                      metavar='STRING',
                      help='set IGC file suffix')
    parser.add_option('-I',
                      '--igc-path',
                      metavar='STRING',
                      help='set IGC path')
    parser.add_option('-P',
                      '--photos-path',
                      metavar='STRING',
                      help='set photos path')
    parser.add_option('-U',
                      '--photos-url',
                      metavar='STRING',
                      help='set photos URL')
    parser.set_defaults(output='igc2kmz.kmz')
    parser.set_defaults(name=DEFAULT_NAME)
    parser.set_defaults(icon=DEFAULT_ICON)
    parser.set_defaults(url=DEFAULT_URL)
    parser.set_defaults(directory=DEFAULT_DIRECTORY)
    parser.set_defaults(tz_offset=0)
    parser.set_defaults(table_prefix=DEFAULT_TABLE_PREFIX)
    parser.set_defaults(igc_path=DEFAULT_IGC_PATH)
    parser.set_defaults(photos_path=DEFAULT_PHOTOS_PATH)
    parser.set_defaults(photos_url=DEFAULT_PHOTOS_URL)
    parser.set_defaults(igc_suffix='.saned.full.igc')
    options, args = parser.parse_args(argv)
    #
    flights_dir = os.path.join(options.directory, 'modules', 'leonardo',
                               'flights')
    #
    roots = []
    roots.append(make_banner(options))
    #
    metadata = MetaData(options.engine)
    pilots_table = Table(options.table_prefix + '_pilots',
                         metadata,
                         autoload=True)
    flights_table = Table(options.table_prefix + '_flights',
                          metadata,
                          autoload=True)
    flights_score_table = Table(options.table_prefix + '_flights_score',
                                metadata,
                                autoload=True)
    photos_table = Table(options.table_prefix + '_photos',
                         metadata,
                         autoload=True)
    waypoints_table = Table(options.table_prefix + '_waypoints',
                            metadata,
                            autoload=True)
    #
    flights = []
    for flightID in args[1:]:
        select = flights_table.select(flights_table.c.ID == int(flightID))
        flight_row = select.execute().fetchone()
        if flight_row is None:
            raise KeyError, id
        if flight_row.userServerID:
            pilot_id = '%(userServerID)d_%(userID)d' % flight_row
        else:
            pilot_id = flight_row.userID
        substitutions = {
            'PILOTID': str(pilot_id),
            'YEAR': str(flight_row.DATE.year),
        }
        igc_path = os.path.join(options.directory,
                                substitute(options.igc_path, substitutions),
                                flight_row.filename + options.igc_suffix)
        track = IGC(open(igc_path), date=flight_row.DATE).track()
        flight = Flight(track)
        flight.glider_type = flight_row.glider
        flight.url = options.url + SHOW_FLIGHT_URL % flight_row
        #
        select = pilots_table.select(
            (pilots_table.c.pilotID == flight_row.userID)
            & (pilots_table.c.serverID == flight_row.userServerID))
        pilot_row = select.execute().fetchone()
        if pilot_row is None:
            raise KeyError, '(%(userID)s, %(userServerID)s)' % flight_row
        flight.pilot_name = '%(FirstName)s %(LastName)s' % pilot_row
        #
        routes = []
        select = flights_score_table.select(
            flights_score_table.c.flightID == flight_row.ID)
        for flight_score_row in select.execute().fetchall():
            route_name = ROUTE_NAME[flight_score_row.type]
            league = LEAGUE[flight_score_row.method]
            distance = flight_score_row.distance
            score = flight_score_row.score
            multiplier = round(score / distance, 2)
            circuit = CIRCUIT[flight_score_row.type]
            tps = []
            for i in xrange(1, 8):
                m = B_RECORD_RE.match(flight_score_row['turnpoint%d' % i])
                if not m:
                    continue
                time = datetime.time(*map(int, m.group(1, 2, 3)))
                dt = datetime.datetime.combine(flight_row.DATE, time)
                lat = int(m.group(4)) + int(m.group(5)) / 60000.0
                if m.group(6) == 'S':
                    lat = -lat
                lon = int(m.group(7)) + int(m.group(8)) / 60000.0
                if m.group(9) == 'W':
                    lon = -lon
                coord = Coord.deg(lat, lon, 0, dt)
                name = 'Start' if i == 1 else 'TP%d' % (i - 1)
                tp = Turnpoint(name, coord)
                tps.append(tp)
            tps[-1].name = 'Finish'
            route = Route(route_name, league, distance, multiplier, score,
                          circuit, tps)
            routes.append(route)
        flight.xc = XC(routes)
        #
        if flight_row.hasPhotos:
            select = photos_table.select(
                photos_table.c.flightID == flight_row.ID)
            for photo_row in select.execute().fetchall():
                photo_url = options.url \
                        + substitute(options.photos_url, substitutions) \
                        + '/' + photo_row.name
                photo_path = os.path.join(
                    options.directory,
                    substitute(options.photos_path, substitutions),
                    photo_row.name)
                photo = Photo(photo_url, path=photo_path)
                if photo_row.description:
                    photo.description = photo_row.description
                flight.photos.append(photo)
        #
        flights.append(flight)
        #
        select = waypoints_table.select(
            waypoints_table.c.ID == flight_row.takeoffID)
        takeoff_row = select.execute().fetchone()
        if takeoff_row:
            roots.append(make_takeoff_placemark(takeoff_row))
    #
    kmz = flights2kmz(flights, roots=roots, tz_offset=options.tz_offset)
    kmz.write(options.output, '2.2')
Example #7
0
def main(argv):
    parser = optparse.OptionParser(usage='Usage: %prog [options]',
                                   description="IGC to Google Earth converter")
    parser.add_option('-o',
                      '--output',
                      metavar='FILENAME',
                      help='set output filename')
    parser.add_option('-z',
                      '--tz-offset',
                      metavar='HOURS',
                      type='int',
                      help='set timezone offset')
    parser.add_option('-r',
                      '--root',
                      metavar='FILENAME',
                      action='append',
                      dest='roots',
                      help='add root element')
    parser.add_option('-t', '--task', metavar='FILENAME', help='set task')
    group = optparse.OptionGroup(parser, 'Per-flight options')
    group.add_option('-i',
                     '--igc',
                     metavar='FILENAME',
                     type='string',
                     action='callback',
                     callback=add_flight,
                     help='set flight IGC file')
    group.add_option('-n',
                     '--pilot-name',
                     metavar='STRING',
                     type='string',
                     action='callback',
                     callback=set_flight_option,
                     help='set pilot name')
    group.add_option('-g',
                     '--glider-type',
                     metavar='STRING',
                     type='string',
                     action='callback',
                     callback=set_flight_option,
                     help='set glider type')
    group.add_option('-c',
                     '--color',
                     metavar='COLOR',
                     type='string',
                     action='callback',
                     callback=set_flight_option,
                     help='set track line color')
    group.add_option('-w',
                     '--width',
                     metavar='INTEGER',
                     type='int',
                     action='callback',
                     callback=set_flight_option,
                     help='set track line width')
    group.add_option('-u',
                     '--url',
                     metavar='URL',
                     type='string',
                     action='callback',
                     callback=set_flight_option,
                     help='set flight URL')
    group.add_option('-x',
                     '--xc',
                     metavar='FILENAME',
                     type='string',
                     action='callback',
                     callback=set_flight_xc,
                     help='set flight XC')
    parser.add_option_group(group)
    group = optparse.OptionGroup(parser, 'Per-photo options')
    group.add_option('-p',
                     '--photo',
                     metavar='URL',
                     type='string',
                     action='callback',
                     callback=add_photo,
                     help='add photo')
    group.add_option('-d',
                     '--description',
                     metavar='STRING',
                     type='string',
                     action='callback',
                     callback=set_photo_option,
                     help='set photo comment')
    parser.add_option_group(group)
    #
    parser.set_defaults(flights=[])
    parser.set_defaults(roots=[])
    parser.set_defaults(tz_offset=0)
    #
    options, args = parser.parse_args(argv)
    if len(options.flights) == 0:
        parser.error('no flights specified')
    if len(args) != 1:
        parser.error('extra arguments on command line: %s' % repr(args[1:]))
    #
    roots = [Verbatim(open(root).read()) for root in options.roots]
    task = Task.from_file(open(options.task)) if options.task else None
    kmz = flights2kmz(options.flights,
                      roots=roots,
                      tz_offset=options.tz_offset,
                      task=task)
    output = options.output or default_output
    kmz.write(output, '2.2')