3504: Fix collection page rendering to work with collections as regular uuids.
[arvados.git] / apps / workbench / app / models / arvados_base.rb
1 class ArvadosBase < ActiveRecord::Base
2   self.abstract_class = true
3   attr_accessor :attribute_sortkey
4   attr_accessor :create_params
5
6   def self.arvados_api_client
7     ArvadosApiClient.new_or_current
8   end
9
10   def arvados_api_client
11     ArvadosApiClient.new_or_current
12   end
13
14   def self.uuid_infix_object_kind
15     @@uuid_infix_object_kind ||=
16       begin
17         infix_kind = {}
18         arvados_api_client.discovery[:schemas].each do |name, schema|
19           if schema[:uuidPrefix]
20             infix_kind[schema[:uuidPrefix]] =
21               'arvados#' + name.to_s.camelcase(:lower)
22           end
23         end
24
25         # Recognize obsolete types.
26         infix_kind.
27           merge('mxsvm' => 'arvados#pipelineTemplate', # Pipeline
28                 'uo14g' => 'arvados#pipelineInstance', # PipelineInvocation
29                 'ldvyl' => 'arvados#group') # Project
30       end
31   end
32
33   def initialize raw_params={}, create_params={}
34     super self.class.permit_attribute_params(raw_params)
35     @create_params = create_params
36     @attribute_sortkey ||= {
37       'id' => nil,
38       'name' => '000',
39       'owner_uuid' => '002',
40       'event_type' => '100',
41       'link_class' => '100',
42       'group_class' => '100',
43       'tail_uuid' => '101',
44       'head_uuid' => '102',
45       'object_uuid' => '102',
46       'summary' => '104',
47       'description' => '104',
48       'properties' => '150',
49       'info' => '150',
50       'created_at' => '200',
51       'modified_at' => '201',
52       'modified_by_user_uuid' => '202',
53       'modified_by_client_uuid' => '203',
54       'uuid' => '999',
55     }
56   end
57
58   def self.columns
59     return @columns if @columns.andand.any?
60     @columns = []
61     @attribute_info ||= {}
62     schema = arvados_api_client.discovery[:schemas][self.to_s.to_sym]
63     return @columns if schema.nil?
64     schema[:properties].each do |k, coldef|
65       case k
66       when :etag, :kind
67         attr_reader k
68       else
69         if coldef[:type] == coldef[:type].downcase
70           # boolean, integer, etc.
71           @columns << column(k, coldef[:type].to_sym)
72         else
73           # Hash, Array
74           @columns << column(k, :text)
75           serialize k, coldef[:type].constantize
76         end
77         @attribute_info[k] = coldef
78       end
79     end
80     @columns
81   end
82
83   def self.column(name, sql_type = nil, default = nil, null = true)
84     ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
85   end
86
87   def self.attribute_info
88     self.columns
89     @attribute_info
90   end
91
92   def self.find(uuid, opts={})
93     if uuid.class != String or uuid.length < 27 then
94       raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
95     end
96
97     if self == ArvadosBase
98       # Determine type from uuid and defer to the appropriate subclass.
99       return resource_class_for_uuid(uuid).find(uuid, opts)
100     end
101
102     # Only do one lookup on the API side per {class, uuid, workbench
103     # request} unless {cache: false} is given via opts.
104     cache_key = "request_#{Thread.current.object_id}_#{self.to_s}_#{uuid}"
105     if opts[:cache] == false
106       Rails.cache.write cache_key, arvados_api_client.api(self, '/' + uuid)
107     end
108     hash = Rails.cache.fetch cache_key do
109       arvados_api_client.api(self, '/' + uuid)
110     end
111     new.private_reload(hash)
112   end
113
114   def self.find?(*args)
115     find(*args) rescue nil
116   end
117
118   def self.order(*args)
119     ArvadosResourceList.new(self).order(*args)
120   end
121
122   def self.filter(*args)
123     ArvadosResourceList.new(self).filter(*args)
124   end
125
126   def self.where(*args)
127     ArvadosResourceList.new(self).where(*args)
128   end
129
130   def self.limit(*args)
131     ArvadosResourceList.new(self).limit(*args)
132   end
133
134   def self.select(*args)
135     ArvadosResourceList.new(self).select(*args)
136   end
137
138   def self.eager(*args)
139     ArvadosResourceList.new(self).eager(*args)
140   end
141
142   def self.all(*args)
143     ArvadosResourceList.new(self).all(*args)
144   end
145
146   def self.permit_attribute_params raw_params
147     # strong_parameters does not provide security in Workbench: anyone
148     # who can get this far can just as well do a call directly to our
149     # database (Arvados) with the same credentials we use.
150     #
151     # The following permit! is necessary even with
152     # "ActionController::Parameters.permit_all_parameters = true",
153     # because permit_all does not permit nested attributes.
154     ActionController::Parameters.new(raw_params).permit!
155   end
156
157   def self.create raw_params={}, create_params={}
158     x = super(permit_attribute_params(raw_params))
159     x.create_params = create_params
160     x
161   end
162
163   def update_attributes raw_params={}
164     super(self.class.permit_attribute_params(raw_params))
165   end
166
167   def save
168     obdata = {}
169     self.class.columns.each do |col|
170       obdata[col.name.to_sym] = self.send(col.name.to_sym)
171     end
172     obdata.delete :id
173     postdata = { self.class.to_s.underscore => obdata }
174     if etag
175       postdata['_method'] = 'PUT'
176       obdata.delete :uuid
177       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
178     else
179       postdata.merge!(@create_params) if @create_params
180       resp = arvados_api_client.api(self.class, '', postdata)
181     end
182     return false if !resp[:etag] || !resp[:uuid]
183
184     # set read-only non-database attributes
185     @etag = resp[:etag]
186     @kind = resp[:kind]
187
188     # attributes can be modified during "save" -- we should update our copies
189     resp.keys.each do |attr|
190       if self.respond_to? "#{attr}=".to_sym
191         self.send(attr.to_s + '=', resp[attr.to_sym])
192       end
193     end
194
195     @new_record = false
196
197     self
198   end
199
200   def save!
201     self.save or raise Exception.new("Save failed")
202   end
203
204   def destroy
205     if etag || uuid
206       postdata = { '_method' => 'DELETE' }
207       resp = arvados_api_client.api(self.class, '/' + uuid, postdata)
208       resp[:etag] && resp[:uuid] && resp
209     else
210       true
211     end
212   end
213
214   def links(*args)
215     o = {}
216     o.merge!(args.pop) if args[-1].is_a? Hash
217     o[:link_class] ||= args.shift
218     o[:name] ||= args.shift
219     o[:tail_uuid] = self.uuid
220     if all_links
221       return all_links.select do |m|
222         ok = true
223         o.each do |k,v|
224           if !v.nil?
225             test_v = m.send(k)
226             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
227               ok = false
228             end
229           end
230         end
231         ok
232       end
233     end
234     @links = arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
235     @links = arvados_api_client.unpack_api_response(@links)
236   end
237
238   def all_links
239     return @all_links if @all_links
240     res = arvados_api_client.api Link, '', {
241       _method: 'GET',
242       where: {
243         tail_kind: self.kind,
244         tail_uuid: self.uuid
245       },
246       eager: true
247     }
248     @all_links = arvados_api_client.unpack_api_response(res)
249   end
250
251   def reload
252     private_reload(self.uuid)
253   end
254
255   def private_reload(uuid_or_hash)
256     raise "No such object" if !uuid_or_hash
257     if uuid_or_hash.is_a? Hash
258       hash = uuid_or_hash
259     else
260       hash = arvados_api_client.api(self.class, '/' + uuid_or_hash)
261     end
262     hash.each do |k,v|
263       if self.respond_to?(k.to_s + '=')
264         self.send(k.to_s + '=', v)
265       else
266         # When ArvadosApiClient#schema starts telling us what to expect
267         # in API responses (not just the server side database
268         # columns), this sort of awfulness can be avoided:
269         self.instance_variable_set('@' + k.to_s, v)
270         if !self.respond_to? k
271           singleton = class << self; self end
272           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
273         end
274       end
275     end
276     @all_links = nil
277     @new_record = false
278     self
279   end
280
281   def to_param
282     uuid
283   end
284
285   def initialize_copy orig
286     super
287     forget_uuid!
288   end
289
290   def attributes_for_display
291     self.attributes.reject { |k,v|
292       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
293     }.sort_by { |k,v|
294       attribute_sortkey[k] or k
295     }
296   end
297
298   def class_for_display
299     self.class.to_s.underscore.humanize
300   end
301
302   def self.class_for_display
303     self.to_s.underscore.humanize
304   end
305
306   def self.creatable?
307     current_user
308   end
309
310   def self.goes_in_projects?
311     false
312   end
313
314   def editable?
315     (current_user and current_user.is_active and
316      (current_user.is_admin or
317       current_user.uuid == self.owner_uuid or
318       new_record? or
319       (writable_by.include? current_user.uuid rescue false)))
320   end
321
322   def attribute_editable?(attr, ever=nil)
323     if %w(created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at).include? attr.to_s
324       false
325     elsif not (current_user.andand.is_active)
326       false
327     elsif attr == 'uuid'
328       current_user.is_admin
329     elsif ever
330       true
331     else
332       editable?
333     end
334   end
335
336   def self.resource_class_for_uuid(uuid, opts={})
337     if uuid.is_a? ArvadosBase
338       return uuid.class
339     end
340     unless uuid.is_a? String
341       return nil
342     end
343     if opts[:class].is_a? Class
344       return opts[:class]
345     end
346     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
347       return Collection
348     end
349     resource_class = nil
350     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
351       resource_class ||= arvados_api_client.
352         kind_class(self.uuid_infix_object_kind[re[1]])
353     end
354     if opts[:referring_object] and
355         opts[:referring_attr] and
356         opts[:referring_attr].match /_uuid$/
357       resource_class ||= arvados_api_client.
358         kind_class(opts[:referring_object].
359                    attributes[opts[:referring_attr].
360                               sub(/_uuid$/, '_kind')])
361     end
362     resource_class
363   end
364
365   def resource_param_name
366     self.class.to_s.underscore
367   end
368
369   def friendly_link_name
370     (name if self.respond_to? :name) || default_name
371   end
372
373   def content_summary
374     self.class_for_display
375   end
376
377   def selection_label
378     friendly_link_name
379   end
380
381   def self.default_name
382     self.to_s.underscore.humanize
383   end
384
385   def controller
386     (self.class.to_s.pluralize + 'Controller').constantize
387   end
388
389   def controller_name
390     self.class.to_s.tableize
391   end
392
393   # Placeholder for name when name is missing or empty
394   def default_name
395     if self.respond_to? :name
396       "New #{class_for_display.downcase}"
397     else
398       uuid
399     end
400   end
401
402   def owner
403     ArvadosBase.find(owner_uuid) rescue nil
404   end
405
406   protected
407
408   def forget_uuid!
409     self.uuid = nil
410     @etag = nil
411     self
412   end
413
414   def self.current_user
415     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
416     Thread.current[:user]
417   end
418   def current_user
419     self.class.current_user
420   end
421 end