Change underscores to camelcase in "kind" strings as documented.
[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
5   def self.uuid_infix_object_kind
6     @@uuid_infix_object_kind ||= {
7       '4zz18' => 'arvados#collection',
8       'tpzed' => 'arvados#user',
9       'ozdt8' => 'arvados#apiClient',
10       '8i9sb' => 'arvados#job',
11       'o0j2j' => 'arvados#link',
12       '57u5n' => 'arvados#log',
13       'j58dm' => 'arvados#specimen',
14       'p5p6p' => 'arvados#pipelineTemplate',
15       'mxsvm' => 'arvados#pipelineTemplate', # legacy Pipeline objects
16       'd1hrv' => 'arvados#pipelineInstance',
17       'uo14g' => 'arvados#pipelineInstance', # legacy PipelineInstance objects
18       'j7d0g' => 'arvados#group',
19       'ldvyl' => 'arvados#group' # only needed for legacy Project objects
20     }
21   end
22
23   def initialize(*args)
24     super(*args)
25     @attribute_sortkey ||= {
26       'id' => nil,
27       'uuid' => '000',
28       'owner_uuid' => '001',
29       'created_at' => '002',
30       'modified_at' => '003',
31       'modified_by_user_uuid' => '004',
32       'modified_by_client_uuid' => '005',
33       'name' => '050',
34       'tail_kind' => '100',
35       'tail_uuid' => '100',
36       'head_kind' => '101',
37       'head_uuid' => '101',
38       'info' => 'zzz-000',
39       'updated_at' => 'zzz-999'
40     }
41   end
42
43   def self.columns
44     return @columns unless @columns.nil?
45     @columns = []
46     @attribute_info ||= {}
47     return @columns if $arvados_api_client.arvados_schema[self.to_s.to_sym].nil?
48     $arvados_api_client.arvados_schema[self.to_s.to_sym].each do |coldef|
49       k = coldef[:name].to_sym
50       if coldef[:type] == coldef[:type].downcase
51         @columns << column(k, coldef[:type].to_sym)
52       else
53         @columns << column(k, :text)
54         serialize k, coldef[:type].constantize
55       end
56       attr_accessible k
57       @attribute_info[k] = coldef
58     end
59     attr_reader :etag
60     attr_reader :kind
61     @columns
62   end
63   def self.column(name, sql_type = nil, default = nil, null = true)
64     ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
65   end
66   def self.attribute_info
67     self.columns
68     @attribute_info
69   end
70   def self.find(uuid)
71     if uuid.class != String or uuid.length < 27 then
72       raise 'argument to find() must be a uuid string. Acceptable formats: warehouse locator or string with format xxxxx-xxxxx-xxxxxxxxxxxxxxx'
73     end
74     new.private_reload(uuid)
75   end
76   def self.order(*args)
77     ArvadosResourceList.new(self).order(*args)
78   end
79   def self.where(*args)
80     ArvadosResourceList.new(self).where(*args)
81   end
82   def self.limit(*args)
83     ArvadosResourceList.new(self).limit(*args)
84   end
85   def self.eager(*args)
86     ArvadosResourceList.new(self).eager(*args)
87   end
88   def self.all(*args)
89     ArvadosResourceList.new(self).all(*args)
90   end
91   def save
92     obdata = {}
93     self.class.columns.each do |col|
94       obdata[col.name.to_sym] = self.send(col.name.to_sym)
95     end
96     obdata.delete :id
97     postdata = { self.class.to_s.underscore => obdata }
98     if etag
99       postdata['_method'] = 'PUT'
100       obdata.delete :uuid
101       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
102     else
103       resp = $arvados_api_client.api(self.class, '', postdata)
104     end
105     return false if !resp[:etag] || !resp[:uuid]
106
107     # set read-only non-database attributes
108     @etag = resp[:etag]
109     @kind = resp[:kind]
110
111     # these attrs can be modified by "save" -- we should update our copies
112     %w(uuid owner_uuid created_at
113        modified_at modified_by_user_uuid modified_by_client_uuid
114       ).each do |attr|
115       if self.respond_to? "#{attr}=".to_sym
116         self.send(attr + '=', resp[attr.to_sym])
117       end
118     end
119
120     self
121   end
122   def save!
123     self.save or raise Exception.new("Save failed")
124   end
125
126   def destroy
127     if etag || uuid
128       postdata = { '_method' => 'DELETE' }
129       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
130       resp[:etag] && resp[:uuid] && resp
131     else
132       true
133     end
134   end
135       
136   def links(*args)
137     o = {}
138     o.merge!(args.pop) if args[-1].is_a? Hash
139     o[:link_class] ||= args.shift
140     o[:name] ||= args.shift
141     o[:head_kind] ||= args.shift
142     o[:tail_kind] = self.kind
143     o[:tail_uuid] = self.uuid
144     if all_links
145       return all_links.select do |m|
146         ok = true
147         o.each do |k,v|
148           if !v.nil?
149             test_v = m.send(k)
150             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
151               ok = false
152             end
153           end
154         end
155         ok
156       end
157     end
158     @links = $arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
159     @links = $arvados_api_client.unpack_api_response(@links)
160   end
161   def all_links
162     return @all_links if @all_links
163     res = $arvados_api_client.api Link, '', {
164       _method: 'GET',
165       where: {
166         tail_kind: self.kind,
167         tail_uuid: self.uuid
168       },
169       eager: true
170     }
171     @all_links = $arvados_api_client.unpack_api_response(res)
172   end
173   def reload
174     private_reload(self.uuid)
175   end
176   def private_reload(uuid_or_hash)
177     raise "No such object" if !uuid_or_hash
178     if uuid_or_hash.is_a? Hash
179       hash = uuid_or_hash
180     else
181       hash = $arvados_api_client.api(self.class, '/' + uuid_or_hash)
182     end
183     hash.each do |k,v|
184       if self.respond_to?(k.to_s + '=')
185         self.send(k.to_s + '=', v)
186       else
187         # When ArvadosApiClient#schema starts telling us what to expect
188         # in API responses (not just the server side database
189         # columns), this sort of awfulness can be avoided:
190         self.instance_variable_set('@' + k.to_s, v)
191         if !self.respond_to? k
192           singleton = class << self; self end
193           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
194         end
195       end
196     end
197     @all_links = nil
198     self
199   end
200   def dup
201     super.forget_uuid!
202   end
203
204   def attributes_for_display
205     self.attributes.reject { |k,v|
206       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
207     }.sort_by { |k,v|
208       attribute_sortkey[k] or k
209     }
210   end
211
212   def self.creatable?
213     current_user
214   end
215
216   def editable?
217     (current_user and current_user.is_active and
218      (current_user.is_admin or
219       current_user.uuid == self.owner_uuid))
220   end
221
222   def attribute_editable?(attr)
223     if "created_at modified_at modified_by_user_uuid modified_by_client_uuid updated_at".index(attr.to_s)
224       false
225     elsif not (current_user.andand.is_active)
226       false
227     elsif "uuid owner_uuid".index(attr.to_s) or current_user.is_admin
228       current_user.is_admin
229     else
230       current_user.uuid == self.owner_uuid or current_user.uuid == self.uuid
231     end
232   end
233
234   def self.resource_class_for_uuid(uuid, opts={})
235     if uuid.is_a? ArvadosBase
236       return uuid.class
237     end
238     unless uuid.is_a? String
239       return nil
240     end
241     if opts[:class].is_a? Class
242       return opts[:class]
243     end
244     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
245       return Collection
246     end
247     resource_class = nil
248     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
249       resource_class ||= $arvados_api_client.
250         kind_class(self.uuid_infix_object_kind[re[1]])
251     end
252     if opts[:referring_object] and
253         opts[:referring_attr] and
254         opts[:referring_attr].match /_uuid$/
255       resource_class ||= $arvados_api_client.
256         kind_class(opts[:referring_object].
257                    attributes[opts[:referring_attr].
258                               sub(/_uuid$/, '_kind')])
259     end
260     resource_class
261   end
262
263   def friendly_link_name
264     if self.class.column_names.include? 'name'
265       self.name
266     end
267   end
268
269   protected
270
271   def forget_uuid!
272     self.uuid = nil
273     @etag = nil
274     self
275   end
276
277   def self.current_user
278     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
279     Thread.current[:user]
280   end
281   def current_user
282     self.class.current_user
283   end
284 end