]> git.openstreetmap.org Git - rails.git/blob - app/models/trace.rb
Remove support for legacy trace files
[rails.git] / app / models / trace.rb
1 # == Schema Information
2 #
3 # Table name: gpx_files
4 #
5 #  id          :bigint(8)        not null, primary key
6 #  user_id     :bigint(8)        not null
7 #  visible     :boolean          default(TRUE), not null
8 #  name        :string           default(""), not null
9 #  size        :bigint(8)
10 #  latitude    :float
11 #  longitude   :float
12 #  timestamp   :datetime         not null
13 #  description :string           default(""), not null
14 #  inserted    :boolean          not null
15 #  visibility  :enum             default("public"), not null
16 #
17 # Indexes
18 #
19 #  gpx_files_timestamp_idx           (timestamp)
20 #  gpx_files_user_id_idx             (user_id)
21 #  gpx_files_visible_visibility_idx  (visible,visibility)
22 #
23 # Foreign Keys
24 #
25 #  gpx_files_user_id_fkey  (user_id => users.id)
26 #
27
28 class Trace < ApplicationRecord
29   require "open3"
30
31   self.table_name = "gpx_files"
32
33   belongs_to :user, :counter_cache => true
34   has_many :tags, :class_name => "Tracetag", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
35   has_many :points, :class_name => "Tracepoint", :foreign_key => "gpx_id", :dependent => :delete_all, :inverse_of => :trace
36
37   scope :visible, -> { where(:visible => true) }
38   scope :visible_to, ->(u) { visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
39   scope :visible_to_all, -> { where(:visibility => %w[public identifiable]) }
40   scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
41
42   has_one_attached :file, :service => Settings.trace_file_storage
43   has_one_attached :image, :service => Settings.trace_image_storage
44   has_one_attached :icon, :service => Settings.trace_icon_storage
45
46   validates :user, :associated => true
47   validates :name, :presence => true, :length => 1..255, :characters => true
48   validates :description, :presence => { :on => :create }, :length => 1..255, :characters => true
49   validates :timestamp, :presence => true
50   validates :visibility, :inclusion => %w[private public trackable identifiable]
51
52   after_save :set_filename
53
54   def tagstring
55     tags.collect(&:tag).join(", ")
56   end
57
58   def tagstring=(s)
59     self.tags = if s.include? ","
60                   s.split(/\s*,\s*/).grep_v(/^\s*$/).collect do |tag|
61                     tt = Tracetag.new
62                     tt.tag = tag
63                     tt
64                   end
65                 else
66                   # do as before for backwards compatibility:
67                   s.split.collect do |tag|
68                     tt = Tracetag.new
69                     tt.tag = tag
70                     tt
71                   end
72                 end
73   end
74
75   def file=(attachable)
76     case attachable
77     when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
78       super(:io => attachable,
79             :filename => attachable.original_filename,
80             :content_type => content_type(attachable.path),
81             :identify => false)
82     else
83       super(attachable)
84     end
85   end
86
87   def public?
88     visibility == "public" || visibility == "identifiable"
89   end
90
91   def trackable?
92     visibility == "trackable" || visibility == "identifiable"
93   end
94
95   def identifiable?
96     visibility == "identifiable"
97   end
98
99   def large_picture
100     image.blob.download
101   end
102
103   def icon_picture
104     icon.blob.download
105   end
106
107   def mime_type
108     file.content_type
109   end
110
111   def extension_name
112     case mime_type
113     when "application/x-tar+gzip" then ".tar.gz"
114     when "application/x-tar+x-bzip2" then ".tar.bz2"
115     when "application/x-tar" then ".tar"
116     when "application/zip" then ".zip"
117     when "application/gzip" then ".gpx.gz"
118     when "application/x-bzip2" then ".gpx.bz2"
119     else ".gpx"
120     end
121   end
122
123   def update_from_xml(xml, create: false)
124     p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
125     doc = p.parse
126     pt = doc.find_first("//osm/gpx_file")
127
128     if pt
129       update_from_xml_node(pt, :create => create)
130     else
131       raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
132     end
133   rescue LibXML::XML::Error, ArgumentError => e
134     raise OSM::APIBadXMLError.new("trace", xml, e.message)
135   end
136
137   def update_from_xml_node(pt, create: false)
138     raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt["visibility"].nil?
139
140     self.visibility = pt["visibility"]
141
142     unless create
143       raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt["id"].nil?
144
145       id = pt["id"].to_i
146       # .to_i will return 0 if there is no number that can be parsed.
147       # We want to make sure that there is no id with zero anyway
148       raise OSM::APIBadUserInput, "ID of trace cannot be zero when updating." if id.zero?
149       raise OSM::APIBadUserInput, "The id in the url (#{self.id}) is not the same as provided in the xml (#{id})" unless self.id == id
150     end
151
152     # We don't care about the time, as it is explicitly set on create/update/delete
153     # We don't care about the visibility as it is implicit based on the action
154     # and set manually before the actual delete
155     self.visible = true
156
157     description = pt.find("description").first
158     raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
159
160     self.description = description.content
161
162     self.tags = pt.find("tag").collect do |tag|
163       Tracetag.new(:tag => tag.content)
164     end
165   end
166
167   def xml_file
168     file.open do |tracefile|
169       filetype = Open3.capture2("/usr/bin/file", "-Lbz", tracefile.path).first.chomp
170       gzipped = filetype.include?("gzip compressed")
171       bzipped = filetype.include?("bzip2 compressed")
172       zipped = filetype.include?("Zip archive")
173       tarred = filetype.include?("tar archive")
174
175       if gzipped || bzipped || zipped || tarred
176         file = Tempfile.new("trace.#{id}")
177
178         if tarred && gzipped
179           system("tar", "-zxOf", tracefile.path, :out => file.path)
180         elsif tarred && bzipped
181           system("tar", "-jxOf", tracefile.path, :out => file.path)
182         elsif tarred
183           system("tar", "-xOf", tracefile.path, :out => file.path)
184         elsif gzipped
185           system("gunzip", "-c", tracefile.path, :out => file.path)
186         elsif bzipped
187           system("bunzip2", "-c", tracefile.path, :out => file.path)
188         elsif zipped
189           system("unzip", "-p", tracefile.path, "-x", "__MACOSX/*", :out => file.path, :err => "/dev/null")
190         end
191
192         file.unlink
193       else
194         file = File.open(tracefile.path)
195       end
196
197       file
198     end
199   end
200
201   def import
202     logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
203
204     file.open do |file|
205       gpx = GPX::File.new(file.path)
206
207       f_lat = 0
208       f_lon = 0
209       first = true
210
211       # If there are any existing points for this trace then delete them
212       Tracepoint.where(:gpx_id => id).delete_all
213
214       gpx.points.each_slice(1_000) do |points|
215         # Gather the trace points together for a bulk import
216         tracepoints = []
217
218         points.each do |point|
219           if first
220             f_lat = point.latitude
221             f_lon = point.longitude
222             first = false
223           end
224
225           tp = Tracepoint.new
226           tp.lat = point.latitude
227           tp.lon = point.longitude
228           tp.altitude = point.altitude
229           tp.timestamp = point.timestamp
230           tp.gpx_id = id
231           tp.trackid = point.segment
232           tracepoints << tp
233         end
234
235         # Run the before_save and before_create callbacks, and then import them in bulk with activerecord-import
236         tracepoints.each do |tp|
237           tp.run_callbacks(:save) { false }
238           tp.run_callbacks(:create) { false }
239         end
240
241         Tracepoint.import!(tracepoints)
242       end
243
244       if gpx.actual_points.positive?
245         max_lat = Tracepoint.where(:gpx_id => id).maximum(:latitude)
246         min_lat = Tracepoint.where(:gpx_id => id).minimum(:latitude)
247         max_lon = Tracepoint.where(:gpx_id => id).maximum(:longitude)
248         min_lon = Tracepoint.where(:gpx_id => id).minimum(:longitude)
249
250         max_lat = max_lat.to_f / 10000000
251         min_lat = min_lat.to_f / 10000000
252         max_lon = max_lon.to_f / 10000000
253         min_lon = min_lon.to_f / 10000000
254
255         self.latitude = f_lat
256         self.longitude = f_lon
257         image.attach(:io => gpx.picture(min_lat, min_lon, max_lat, max_lon, gpx.actual_points), :filename => "#{id}.gif", :content_type => "image/gif")
258         icon.attach(:io => gpx.icon(min_lat, min_lon, max_lat, max_lon), :filename => "#{id}_icon.gif", :content_type => "image/gif")
259         self.size = gpx.actual_points
260         self.inserted = true
261         save!
262       end
263
264       logger.info "done trace #{id}"
265
266       gpx
267     end
268   end
269
270   private
271
272   def content_type(file)
273     case Open3.capture2("/usr/bin/file", "-Lbz", file).first.chomp
274     when /.*\btar archive\b.*\bgzip\b/ then "application/x-tar+gzip"
275     when /.*\btar archive\b.*\bbzip2\b/ then "application/x-tar+x-bzip2"
276     when /.*\btar archive\b/ then "application/x-tar"
277     when /.*\bZip archive\b/ then "application/zip"
278     when /.*\bXML\b.*\bgzip\b/ then "application/gzip"
279     when /.*\bXML\b.*\bbzip2\b/ then "application/x-bzip2"
280     else "application/gpx+xml"
281     end
282   end
283
284   def set_filename
285     file.blob.update(:filename => "#{id}#{extension_name}") if file.attached?
286   end
287 end