fix import bug, make points commify
[rails.git] / lib / daemons / gpx_import.rb
1 #!/usr/bin/env ruby
2
3 #You might want to change this
4 ENV["RAILS_ENV"] ||= "development"
5
6 require File.dirname(__FILE__) + "/../../config/environment"
7
8 $running = true;
9 Signal.trap("TERM") do 
10   $running = false
11 end
12
13 logger = ActiveRecord::Base.logger
14
15 while($running) do
16   
17   ActiveRecord::Base.logger.info("GPX Import daemon wake @ #{Time.now}.")
18
19   traces = Trace.find(:all, :conditions => ['inserted = ?', false])
20
21   if traces and traces.length > 0
22     traces.each do |trace|
23       begin
24
25         logger.info("GPX Import importing #{trace.name} from #{trace.user.email}")
26 \r
27         # TODO *nix specific, could do to work on windows... would be functionally inferior though - check for '.gz'
28         gzipped = `file -b /tmp/#{trace.id}.gpx`.chomp =~/^gzip/\r
29
30         if gzipped
31           logger.info("gzipped")
32         else
33           logger.info("not gzipped")
34         end
35         gpx = OSM::GPXImporter.new("/tmp/#{trace.id}.gpx")
36
37         f_lat = 0
38         l_lon = 0
39         first = true
40
41         gpx.points do |point|
42           if first
43             f_lat = point['latitude']
44             f_lon = point['longitude']
45           end
46
47           tp = Tracepoint.new
48           tp.latitude = point['latitude']
49           tp.longitude = point['longitude']
50           tp.altitude = point['altitude']
51           tp.user_id = trace.user.id
52           tp.gpx_id = trace.id
53           tp.trackid = point['segment']
54           tp.save!
55         end
56
57         if gpx.actual_points > 0
58           max_lat = Tracepoint.maximum('latitude', :conditions => ['gpx_id = ?', trace.id])
59           min_lat = Tracepoint.minimum('latitude', :conditions => ['gpx_id = ?', trace.id])
60           max_lon = Tracepoint.maximum('longitude', :conditions => ['gpx_id = ?', trace.id])
61           min_lon = Tracepoint.minimum('longitude', :conditions => ['gpx_id = ?', trace.id])
62
63           trace.latitude = f_lat
64           trace.longitude = f_lon
65           trace.large_picture = gpx.get_picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points)
66           trace.icon_picture = gpx.get_icon(min_lat, min_lon, max_lat, max_lon)
67           trace.size = gpx.actual_points
68           trace.inserted = true
69           trace.save
70           Notifier::deliver_gpx_success(trace, gpx.possible_points)
71         else
72           #trace.destroy
73           Notifier::deliver_gpx_failure(trace, '0 points parsed ok. Do they all have lat,lng,alt,timestamp?')
74         end
75
76       rescue Exception => ex
77         #trace.destroy
78         Notifier::deliver_gpx_failure(trace, ex.to_s + ex.backtrace.join("\n") )
79       end
80     end
81   end
82   sleep 15.minutes
83 end