fix current_user in model
[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#api_client',
10       '8i9sb' => 'arvados#job',
11       'o0j2j' => 'arvados#link',
12       '57u5n' => 'arvados#log',
13       'j58dm' => 'arvados#specimen',
14       'p5p6p' => 'arvados#pipeline_template',
15       'mxsvm' => 'arvados#pipeline_template', # legacy Pipeline objects
16       'd1hrv' => 'arvados#pipeline_instance',
17       'uo14g' => 'arvados#pipeline_instance', # 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' => '001',
29       'created_at' => '002',
30       'modified_at' => '003',
31       'modified_by_user' => '004',
32       'modified_by_client' => '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.where(*args)
77     ArvadosResourceList.new(self).where(*args)
78   end
79   def self.limit(*args)
80     ArvadosResourceList.new(self).limit(*args)
81   end
82   def self.eager(*args)
83     ArvadosResourceList.new(self).eager(*args)
84   end
85   def self.all(*args)
86     ArvadosResourceList.new(self).all(*args)
87   end
88   def save
89     obdata = {}
90     self.class.columns.each do |col|
91       obdata[col.name.to_sym] = self.send(col.name.to_sym)
92     end
93     obdata.delete :id
94     postdata = { self.class.to_s.underscore => obdata }
95     if etag
96       postdata['_method'] = 'PUT'
97       obdata.delete :uuid
98       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
99     else
100       resp = $arvados_api_client.api(self.class, '', postdata)
101     end
102     return false if !resp[:etag] || !resp[:uuid]
103
104     # set read-only non-database attributes
105     @etag = resp[:etag]
106     @kind = resp[:kind]
107
108     # these attrs can be modified by "save" -- we should update our copies
109     %w(uuid owner created_at
110        modified_at modified_by_user modified_by_client
111       ).each do |attr|
112       self.send(attr + '=', resp[attr.to_sym])
113     end
114
115     self
116   end
117   def save!
118     self.save or raise Exception.new("Save failed")
119   end
120
121   def destroy
122     if etag || uuid
123       postdata = { '_method' => 'DELETE' }
124       resp = $arvados_api_client.api(self.class, '/' + uuid, postdata)
125       resp[:etag] && resp[:uuid] && resp
126     else
127       true
128     end
129   end
130       
131   def links(*args)
132     o = {}
133     o.merge!(args.pop) if args[-1].is_a? Hash
134     o[:link_class] ||= args.shift
135     o[:name] ||= args.shift
136     o[:head_kind] ||= args.shift
137     o[:tail_kind] = self.kind
138     o[:tail_uuid] = self.uuid
139     if all_links
140       return all_links.select do |m|
141         ok = true
142         o.each do |k,v|
143           if !v.nil?
144             test_v = m.send(k)
145             if (v.respond_to?(:uuid) ? v.uuid : v.to_s) != (test_v.respond_to?(:uuid) ? test_v.uuid : test_v.to_s)
146               ok = false
147             end
148           end
149         end
150         ok
151       end
152     end
153     @links = $arvados_api_client.api Link, '', { _method: 'GET', where: o, eager: true }
154     @links = $arvados_api_client.unpack_api_response(@links)
155   end
156   def all_links
157     return @all_links if @all_links
158     res = $arvados_api_client.api Link, '', {
159       _method: 'GET',
160       where: {
161         tail_kind: self.kind,
162         tail_uuid: self.uuid
163       },
164       eager: true
165     }
166     @all_links = $arvados_api_client.unpack_api_response(res)
167   end
168   def reload
169     private_reload(self.uuid)
170   end
171   def private_reload(uuid_or_hash)
172     raise "No such object" if !uuid_or_hash
173     if uuid_or_hash.is_a? Hash
174       hash = uuid_or_hash
175     else
176       hash = $arvados_api_client.api(self.class, '/' + uuid_or_hash)
177     end
178     hash.each do |k,v|
179       if self.respond_to?(k.to_s + '=')
180         self.send(k.to_s + '=', v)
181       else
182         # When ArvadosApiClient#schema starts telling us what to expect
183         # in API responses (not just the server side database
184         # columns), this sort of awfulness can be avoided:
185         self.instance_variable_set('@' + k.to_s, v)
186         if !self.respond_to? k
187           singleton = class << self; self end
188           singleton.send :define_method, k, lambda { instance_variable_get('@' + k.to_s) }
189         end
190       end
191     end
192     @all_links = nil
193     self
194   end
195   def dup
196     super.forget_uuid!
197   end
198
199   def attributes_for_display
200     self.attributes.reject { |k,v|
201       attribute_sortkey.has_key?(k) and !attribute_sortkey[k]
202     }.sort_by { |k,v|
203       attribute_sortkey[k] or k
204     }
205   end
206
207   def editable?
208     (current_user and
209      (current_user.is_admin or
210       current_user.uuid == self.owner))
211   end
212
213   def attribute_editable?(attr)
214     if "created_at modified_at modified_by_user modified_by_client updated_at".index(attr.to_s)
215       false
216     elsif "uuid owner".index(attr.to_s)
217       current_user and current_user.is_admin
218     else
219       current_user and current_user.uuid == owner
220     end
221   end
222
223   def self.resource_class_for_uuid(uuid, opts={})
224     if uuid.is_a? ArvadosBase
225       return uuid.class
226     end
227     unless uuid.is_a? String
228       return nil
229     end
230     if opts[:class].is_a? Class
231       return opts[:class]
232     end
233     if uuid.match /^[0-9a-f]{32}(\+[^,]+)*(,[0-9a-f]{32}(\+[^,]+)*)*$/
234       return Collection
235     end
236     resource_class = nil
237     uuid.match /^[0-9a-z]{5}-([0-9a-z]{5})-[0-9a-z]{15}$/ do |re|
238       resource_class ||= $arvados_api_client.
239         kind_class(self.uuid_infix_object_kind[re[1]])
240     end
241     if opts[:referring_object] and
242         opts[:referring_attr] and
243         opts[:referring_attr].match /_uuid$/
244       resource_class ||= $arvados_api_client.
245         kind_class(opts[:referring_object].
246                    attributes[opts[:referring_attr].
247                               sub(/_uuid$/, '_kind')])
248     end
249     resource_class
250   end
251
252   protected
253
254   def forget_uuid!
255     self.uuid = nil
256     @etag = nil
257     self
258   end
259
260   def current_user
261     Thread.current[:user] ||= User.current if Thread.current[:arvados_api_token]
262     Thread.current[:user]
263   end
264 end