2015-09-01 03:31:25 +00:00
|
|
|
__author__ = 'tyrel'
|
|
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
from django.contrib.auth.models import User
|
2015-09-01 03:56:40 +00:00
|
|
|
from tracking.models import Track, Segment, Point
|
2015-09-08 16:55:41 +00:00
|
|
|
from django.contrib.gis import geos
|
2015-09-01 04:47:56 +00:00
|
|
|
import xmltodict
|
|
|
|
|
2015-09-01 03:31:25 +00:00
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
help = 'Import a gpx file'
|
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
|
|
|
parser.add_argument('username', help="Username to import to.")
|
|
|
|
parser.add_argument('filepath', help="File or directory to import a gpx file.")
|
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
2015-09-01 04:47:56 +00:00
|
|
|
self.username = options['username']
|
2015-09-01 03:31:25 +00:00
|
|
|
filepath = options['filepath']
|
2015-09-01 04:47:56 +00:00
|
|
|
|
2015-09-01 03:31:25 +00:00
|
|
|
try:
|
2015-09-01 04:47:56 +00:00
|
|
|
self.user = User.objects.get(username=self.username)
|
2015-09-01 03:31:25 +00:00
|
|
|
except User.DoesNotExist:
|
2015-09-01 04:47:56 +00:00
|
|
|
raise CommandError("User {0} does not exist".format(self.username))
|
2015-09-01 03:31:25 +00:00
|
|
|
|
2015-09-08 16:55:41 +00:00
|
|
|
if os.path.isfile(filepath):
|
2015-09-01 04:47:56 +00:00
|
|
|
self.import_file(filepath)
|
2015-09-01 03:31:25 +00:00
|
|
|
else:
|
|
|
|
raise CommandError("{0} is neither an existing file, nor a path.".format(filepath))
|
|
|
|
|
2015-09-01 04:47:56 +00:00
|
|
|
def import_file(self, filename):
|
|
|
|
with open(filename) as fd:
|
|
|
|
obj = dict(xmltodict.parse(fd.read()))['gpx']
|
2015-09-08 16:55:41 +00:00
|
|
|
user = self.user
|
2015-09-01 04:47:56 +00:00
|
|
|
|
2015-09-08 16:55:41 +00:00
|
|
|
create_points_segments_tracks(obj, user)
|
2015-09-01 03:56:40 +00:00
|
|
|
|
|
|
|
|
2015-09-08 16:55:41 +00:00
|
|
|
def create_points_segments_tracks(obj, user):
|
|
|
|
# Get some Meta data from the gpx file.
|
|
|
|
metadata = obj['metadata']
|
|
|
|
start_time = metadata['time']
|
|
|
|
# Get the the track and segments from the gpx file.
|
|
|
|
tracks = obj['trk']
|
|
|
|
name = tracks['name']
|
|
|
|
segments = tracks['trkseg']
|
|
|
|
# Check unimplemented features
|
|
|
|
if isinstance(segments, list):
|
|
|
|
raise NotImplemented(
|
|
|
|
"Haven't run across one that has multiple segments. "
|
|
|
|
"Contribute a patch if you have.")
|
|
|
|
elif isinstance(segments, dict):
|
|
|
|
track = Track.objects.create(user=user,
|
|
|
|
start=start_time,
|
|
|
|
name=name)
|
|
|
|
points = segments['trkpt']
|
|
|
|
segment = Segment(track=track, time=points[0]['time'])
|
|
|
|
segment.save()
|
|
|
|
for pt in points:
|
|
|
|
lat, lon = float(pt['@lat']), float(pt['@lon'])
|
|
|
|
poly_pt = geos.Point(lon, lat)
|
|
|
|
Point.objects.create(segment=segment,
|
|
|
|
time=pt['time'],
|
|
|
|
elevation=pt['ele'],
|
|
|
|
point=poly_pt)
|