Module: Sinatra::SinatraRbbt

Includes:
RbbtHTMLHelpers
Defined in:
lib/rbbt/workflow/rest/util.rb,
lib/rbbt/workflow/rest/email.rb,
lib/rbbt/workflow/rest/notes.rb,
lib/rbbt/workflow/rest/render.rb

Constant Summary

Constants included from RbbtHTMLHelpers

RbbtHTMLHelpers::PAGESIZE

Instance Method Summary collapse

Methods included from RbbtHTMLHelpers

#add_user_defaults, #clean_list_id, #clear_user_defaults, #entity_action_render, #entity_list_action_render, #entity_list_render, #entity_render, #followed_users, #form_input, #format_float, #html_options_str, #included, #link_to_resource, #locate_file, locate_file, #log, #paginate, #parameter_controls, #parse_page, #process_result, #record_css, #record_js, #redirect_to_entity, #save_user_defaults, #serve_css, #serve_js, #setup_entity, #table, #user_action_defaults, #workflow_partial, #workflow_render, #workflow_render_result

Instance Method Details

#add_context_job(workflow, task, jobname) ⇒ Object



199
200
201
202
203
204
205
# File 'lib/rbbt/workflow/rest/util.rb', line 199

def add_context_job(workflow, task, jobname)
  jobname = File.basename(jobname)
  context = session["context"] || {}
  context[workflow] ||= {}
  context[workflow][task] = jobname
  session["context"] = context
end

#add_param(url, key, value) ⇒ Object



207
208
209
210
211
212
213
# File 'lib/rbbt/workflow/rest/util.rb', line 207

def add_param(url, key, value)
  if url =~ /\?/
    url += "&#{ key }=#{ value }"
  else
    url += "?#{ key }=#{ value }"
  end
end

#add_params(url, hash) ⇒ Object



215
216
217
218
219
220
# File 'lib/rbbt/workflow/rest/util.rb', line 215

def add_params(url, hash)
  hash.each do |key, value|
    url = add_param url, key, value
  end
  url
end

#cache(type, options, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/rbbt/workflow/rest/util.rb', line 19

def cache(type, options, &block)
  cache_type, update, check = Misc.process_options options, :cache_type, :update, :check
  
  check = [check] if not check.nil? and not Array === check

  params = options
  params[:visualization_params].delete :_xhr if params.include? :visualization_params
  name = type  + ":" + Misc.hash2md5(params)

  cache_type ||= :memory
  
  case cache_type.to_sym
  when :sync, :synchronous

    path = File.join(settings.cache_dir, "sinatra", name)
    task = Task.setup(:name => "Sinatra cache", :result_type => :string, &block)
    step = Step.new(path, task, nil, nil, self)

    step.clean if old_cache(path, check)

    begin
      case
      when (not step.started? and not update == 'check')
        step.run
      when (step.started? and update == 'reload')
        step.clean
        step.run
      end
    rescue
    end

    begin
      case
      when step.error?
        status 500
        status = step.status || "error"
        messages = step.messages || []
        backtrace = step.info[:backtrace] || []
        step.clean
        "<span class='status'>" << status.to_s << "</span> " << "\n" <<
        "<span class='cache_message'>" << messages.last << "</span> "  << "\n" <<
        "<ul class='backtrace'>" + backtrace.collect{|line| "<li>" << line << "</li>"} * "\n"
      when step.done?
        step.load
      else
        if request.xhr? 
          status 202
          "<span class='status'>" << (step.status || "starting").to_s << "</span>"
        else
          raise Retry unless step.done? and not step.error?
          step.load
        end
      end
    rescue Retry
      retry
    end


  when :async, :asynchronous
    path = File.join(settings.cache_dir, "sinatra", name)
    task = Task.setup(:result_type => :string, &block)
    step = Step.new(path, task, nil, nil, self)

    step.clean if old_cache(path, check)

    Step.log_relay_step = step
    case
    when (step.started? and update == 'delete')
      step.abort unless step.done?
      sleep 1
      step.clean
      sleep 1
    when (step.started? and update == 'abort')
      step.abort
      sleep 1
    when (not step.started? and not update == 'check')
      step.fork
      sleep 0.5
      sleep 2 unless step.done?
    when (step.started? and update == 'reload')
      step.clean
      step.fork
      sleep 0.5
      sleep 2 unless step.done?
    end
    Step.log_relay_step = nil

    begin
      case
      when step.aborted?
        status 299
        step.clean
        "<span class='status'>" << "aborted" << "</span>"

      when (not step.started?)
        status 202
        "<span class='status'>" << "not started" << "</span>"

      when step.error?
        status 500
        status = step.status || "error"
        messages = step.messages || []
        backtrace = step.info[:backtrace] || []
        step.clean
        if request.xhr? 
          workflow_render('error', :message => (messages[-2] || messages * ", "), :backtrace => backtrace)
        else
          workflow_render('error', :message => (messages[-2] || messages * ", "), :backtrace => backtrace, :_layout => false)
        end
 
      when step.done?
        step.load
      else
        status 202
        if request.xhr? 
          workflow_render('wait',  :step => step, :_layout => false)
        else
          sleep 3
          if step.done?
            status 200
            step.load
          else
            workflow_render('wait',  :step => step)
          end
        end
      end
    rescue Retry
      retry
    end

  when :memory
    @@cache ||= {}
    @@cache.delete name if update == "reload" or not check.nil?
    @@cache[name] ||= yield
  else
    yield
  end
end

#can_send_email?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/rbbt/workflow/rest/email.rb', line 10

def can_send_email?
  Rbbt.etc.smtp_config.exists?
end

#clean_jobname(name) ⇒ Object



387
388
389
# File 'lib/rbbt/workflow/rest/util.rb', line 387

def clean_jobname(name)
  name.sub(/(.*)_.*/,'\1')
end

#context_job(workflow, task) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/rbbt/workflow/rest/util.rb', line 174

def context_job(workflow, task)
  return nil if not defined? session
  return nil if not session.include? "context"
  return nil if not session["context"].include? workflow
  return nil if not session["context"][workflow].include? task
  jobname = session["context"][workflow][task]

  if authorized?
    real_jobname = File.join(user, jobname)
  else
    real_jobname = jobname
  end

  return job_cache(workflow.to_s, task.to_s, jobname) do 
    workflow.load_id File.join(task.to_s, real_jobname) 
  end
end

#continue_job(job, workflow, task_name, inputs = {}) ⇒ Object



391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/rbbt/workflow/rest/util.rb', line 391

def continue_job(job, workflow, task_name, inputs = {})
  task_info = workflow.task_info(task_name)

  job_inputs = job.info[:inputs]
  job_input_types = task_info[:input_types]
  IndiferentHash.setup(job_inputs)
  IndiferentHash.setup(job_input_types)
  IndiferentHash.setup(inputs)

  fixed_inputs = {}
  task_info[:inputs].each do |input|
    fixed_inputs[input] = job_inputs[input] if job_inputs.include? input
    if inputs.include? input
      if Step === inputs[input]
        step = inputs[input]
        name = step.name
        input_task_name = step.task.name

        case job_input_types[input] 
        when :array
          fixed_inputs[input] =  ["local:#{ input_task_name }:#{name}"]
        when :tsv
          fixed_inputs[input] =  {"local:#{ input_task_name }:#{name}" => nil}
        else
          fixed_inputs[input] =  "local:#{ input_task_name }:#{name}"
        end
      else
        fixed_inputs[input] = inputs[input] 
      end
    end
  end

  new_job = job_cache workflow.to_s, task_name, job.name do
    workflow.job(task_name, clean_jobname(job.name), fixed_inputs)
  end

  result = result_cache workflow.to_s, task_name, new_job.name do
    new_job.run
  end

  [new_job, result]
end

#del_context_job(workflow, task) ⇒ Object



192
193
194
195
196
197
# File 'lib/rbbt/workflow/rest/util.rb', line 192

def del_context_job(workflow, task)
  context = session["context"] || {}
  context[workflow] ||= {}
  context[workflow].delete task
  session["context"] = context
end

#delete_notes_markup(path, params, user = nil, shared = false) ⇒ Object



58
59
60
61
# File 'lib/rbbt/workflow/rest/notes.rb', line 58

def delete_notes_markup(path, params, user = nil, shared = false)
  filepath, layout = notes_filepath(path, params, user, shared)
  FileUtils.rm(filepath) rescue ""
end

#fix_input(type, value, param_file = nil) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/rbbt/workflow/rest/util.rb', line 313

def fix_input(type, value, param_file = nil)
  case type
  when nil, :string, :select
    value
  when :integer
    value.to_i
  when :float
    value.to_f
  when :boolean
    Persist::TRUE_STRINGS.include? value.chomp.strip

  when :text
    case 
    when (param_file.nil? and not (value.nil? or value.empty?))
      value.gsub(/\r\n/, "\n")
    when (not param_file.nil?)
      value[:tempfile].read
    end

  when :array
    case 
    when (param_file.nil? and not (value.nil? or value.empty?))
      case
      when String === value
        value.split(/\n|,/).collect{|l| l.strip}
      when Array === value
        value
      else
        raise "Input #{ input } must be Array or String: #{value.class}"
      end
    when (not param_file.nil?)
      text = value[:tempfile].read
      text.split(/\n|,/).collect{|l| l.strip}
    end

  when :tsv
    case 
    when (param_file.nil? and not (value.nil? or value.empty?))
      TSV.open(StringIO.new(value))
    when (not param_file.nil?)
      text = value[:tempfile].read
      TSV.open(StringIO.new(text))
    end
  end
end

{{{ Processing markup



83
84
85
86
87
# File 'lib/rbbt/workflow/rest/notes.rb', line 83

def gene_links(markup)
  markup.gsub(/Gene ([^\s]+)/) do |gene|
    Gene.setup($1, "Associated Gene Name", "Hsa/jun2011").ensembl.link
  end
end

#get_email(params) ⇒ Object

{{{ Params



223
224
225
226
# File 'lib/rbbt/workflow/rest/util.rb', line 223

def get_email(params)
  IndiferentHash.setup(params)
  params.delete :email
end

#get_inputs(workflow, name, params) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/rbbt/workflow/rest/util.rb', line 359

def get_inputs(workflow, name, params)
  inputs = {}

  input_types = workflow.rec_input_types(name)
  IndiferentHash.setup(input_types)

  params.each do |param,value|
    next if param == "noinputs"
    if param =~ /(.*)_param_file$/
      param_file = param
      param = $1
    else
      param_file = nil
    end

    next unless input_types.include? param

    if authorized? and String === value
      value.sub!(/local:(.*):(.*)/, 'local:\1:' + user + '/\2')
    end

    new_value = fix_input(input_types[param], value, param_file)
    inputs[param] = new_value unless new_value.nil?
  end

  IndiferentHash.setup inputs
end

#get_jobname(params) ⇒ Object



228
229
230
231
232
233
# File 'lib/rbbt/workflow/rest/util.rb', line 228

def get_jobname(params)
  IndiferentHash.setup(params)
  jobname = params.delete :jobname
  jobname = "Default" if jobname.nil? or jobname.empty?
  jobname
end

#get_notes_markup(path, params, user = nil, shared = false) ⇒ Object



53
54
55
56
# File 'lib/rbbt/workflow/rest/notes.rb', line 53

def get_notes_markup(path, params, user = nil, shared = false)
  filepath, layout = notes_filepath(path, params, user, shared)
  Open.read(filepath) rescue ""
end

#get_visualization_parameters(params) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/rbbt/workflow/rest/util.rb', line 235

def get_visualization_parameters(params)
  IndiferentHash.setup(params)

  format = params.delete :_format
  format = "html" if format.nil?
  format = format.to_s

  if params.include? :_pfield
    pfield = params.delete :_pfield
    pnum = params.delete :_pnum
    psize = params.delete :_psize
    pnum = pnum.to_i

    case params["_paginate"]
    when "Asc"
      pnum = pnum.abs
    when "Desc"
      pnum = - pnum.abs
    when "Next"
      if pnum < 0
        pnum = pnum - 1
      else
        pnum = pnum + 1
      end
    when "Prev"
      if pnum < 0
        pnum = pnum + 1
      else
        pnum = pnum - 1
      end
    end

    pnum = 1 if pnum == 0

    params.delete "_page"

    params[:_page] = [pfield, pnum, psize] * "~" 
  end

  if params.include? :_ffield
    ffield = params.delete :_ffield
    fquery = params.delete :_fquery

    if fquery.nil? or fquery.strip.empty?
      params[:_filter] = nil
    else
      params[:_filter] = [ffield, fquery] * "~"
    end
  end

  page = params.delete :_page


  filter = params.delete :_filter

  size = params.delete(:_size) || params.delete("_size")
  
  layout = params.delete :_layout

  layout ||= "false" if request.xhr?
  layout = "true" if layout.nil?
  layout = layout == "true"

  { :_format => format, 
    :_page => page, 
    :_filter => filter, 
    :_layout => layout,
    :_size => size,
    :_xhr => request.xhr?,
  }
end

#has_all_inputs(workflow, name, params) ⇒ Object



307
308
309
310
311
# File 'lib/rbbt/workflow/rest/util.rb', line 307

def has_all_inputs(workflow, name, params)
  IndiferentHash.setup(params)

  workflow.rec_inputs(name).reject{|input| params.include? input}.empty?
end

#job_cache(workflow, task, jobname) ⇒ Object



158
159
160
161
162
163
164
# File 'lib/rbbt/workflow/rest/util.rb', line 158

def job_cache(workflow, task, jobname)
  jobname = File.basename(jobname)
  @job_cache ||= {}
  @job_cache[workflow] ||= {}
  @job_cache[workflow][task] ||= {}
  @job_cache[workflow][task][jobname] ||= yield
end


89
90
91
92
93
94
95
96
97
98
# File 'lib/rbbt/workflow/rest/notes.rb', line 89

def kegg_links(markup)
  markup.gsub(/KEGG:"([^"]+)"/) do |match|
    pathway = KEGG.name2id($1).select{|id| id =~ /^hsa/}.first
    if pathway
      KeggPathway.setup(pathway, "Hsa/jun2011").link
    else
      match
    end
  end
end

#notes_filepath(path, params, user = nil, shared = false) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rbbt/workflow/rest/notes.rb', line 29

def notes_filepath(path, params, user = nil, shared = false)
  path = 'news' if path.empty?
  if user and shared
    filepath = File.join(*[settings.note_dir, user, '.shared', path].compact)
  else
    filepath = File.join(*[settings.note_dir, user, path].compact)
  end

  filepath = File.expand_path(filepath)
  raise "Ilegal: #{ path }" unless Misc.path_relative_to(settings.note_dir, filepath)


  params.delete('_update')
  params.delete('_')

  layout = params.delete('_layout')
  layout = false if params.delete(:_xhr) and layout.nil? 
  layout = true if layout.nil?

  filepath << "?" << Misc.hash2GET_params(params) if params.any?

  [filepath, layout]
end

#old_cache(path, check) ⇒ Object



12
13
14
15
16
17
# File 'lib/rbbt/workflow/rest/util.rb', line 12

def old_cache(path, check)
  return false if check.nil?
  return false if not File.exists? path
  check = [check] unless Array === check
  return check.select{|file| not File.exists?(file) or File.mtime(file) > File.mtime(path)}.any?
end

#production?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/rbbt/workflow/rest/util.rb', line 8

def production?
  ENV.include? "RACK_ENV" and not ENV["RACK_ENV"].nil? and ENV['RACK_ENV'].downcase == "production"
end

#render_notes(path, params, user = nil, shared = false) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rbbt/workflow/rest/notes.rb', line 100

def render_notes(path, params, user = nil, shared = false)
  html_header = ""
  html_header += "<a class='back_note' href='#{ request.env['REQUEST_URI'].sub(/\/notes/, '').sub(/^\/shared\/\w+\//, '/')}'>Page</a>\n\n" unless path == 'news'
  if request.env['REQUEST_URI'].sub(/\/notes/, '') !~ /^\/shared\//
    html_header +=  "<a class='edit_note' href='#{ request.env['REQUEST_URI'].sub(/\/notes/, '/notes/edit')}' >Edit</a>\n"
    html_header += "<a class='delete_note DELETE' href='#{ request.env['REQUEST_URI'].sub(/\/notes/, '/notes')}'>Delete</a>\n\n"
  end

  markup = get_notes_markup(path, params, user, shared)

  markup = gene_links(markup)
  markup = kegg_links(markup)
  engine = Markdown
  if layout
    workflow_render("layout", nil, nil, params) do 
      html_header + "<div class='note'>" + engine.new(markup).to_html + "</div>"
    end
  else
    html_header + "<div class='note'>" + engine.new(markup).to_html + "</div>"
  end
end

#result_cache(workflow, task, jobname) ⇒ Object



166
167
168
169
170
171
172
# File 'lib/rbbt/workflow/rest/util.rb', line 166

def result_cache(workflow, task, jobname)
  jobname = File.basename(jobname)
  @result_cache ||= {}
  @result_cache[workflow] ||= {}
  @result_cache[workflow][task] ||= {}
  @result_cache[workflow][task][jobname] ||= yield
end

#save_notes(path, params, markup, user = nil) ⇒ Object



63
64
65
66
# File 'lib/rbbt/workflow/rest/notes.rb', line 63

def save_notes(path, params, markup, user = nil)
  filepath, layout = notes_filepath(path, params, user)
  Open.write(filepath, markup)
end

#send_email(workflow, to, subject, message) ⇒ Object



14
15
16
17
18
19
# File 'lib/rbbt/workflow/rest/email.rb', line 14

def send_email(workflow, to, subject, message)
  Log.low "Sending email to: #{ to }. Subject: #{ subject }"
  raise "Cannot send emails, config is missing" if not can_send_email?
  mail_options = Rbbt.etc.smtp_config.yaml
  Misc.send_email("no-replay@#{workflow.to_s}", to, subject, message, mail_options)
end

#share_notes(path, params, markup, user = nil) ⇒ Object



68
69
70
71
72
73
# File 'lib/rbbt/workflow/rest/notes.rb', line 68

def share_notes(path, params, markup, user = nil)
  filepath, layout = notes_filepath(path, params, user, false)
  shared_filepath, layout = notes_filepath(path, params, user, true)
  FileUtils.mkdir_p(File.dirname(shared_filepath)) unless File.exists? File.dirname(shared_filepath)
  FileUtils.ln_s(filepath, shared_filepath)
end

#shared_notes(user) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/rbbt/workflow/rest/notes.rb', line 18

def shared_notes(user)
  notes = {}
  Dir.glob(File.join(*[settings.note_dir, user, '.shared', '/**/*'].compact)).each do |path|
    next if File.directory? path
    path.sub!(/.*?notes\//,'')
    path.sub!(/^#{user}\/.shared\//,'')
    notes[path] = "/notes/shared/#{ user }/" + path
  end
  notes
end

#unshare_notes(path, params, markup, user = nil) ⇒ Object



75
76
77
78
# File 'lib/rbbt/workflow/rest/notes.rb', line 75

def unshare_notes(path, params, markup, user = nil)
  shared_filepath, layout = notes_filepath(path, params, user, true)
  FileUtils.rm(shared_filepath)
end

#user_notes(user = nil) ⇒ Object

{{{ Locating markup



7
8
9
10
11
12
13
14
15
16
# File 'lib/rbbt/workflow/rest/notes.rb', line 7

def user_notes(user = nil)
  notes = {}
  Dir.glob(File.join(*[settings.note_dir, user, '/**/*'].compact)).each do |path|
    next if File.directory? path
    path.sub!(/.*?notes\//,'')
    path.sub!(/^#{user}\//,'') if user
    notes[path] = '/notes/' + path
  end
  notes
end

#valid_email?(email) ⇒ Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/rbbt/workflow/rest/email.rb', line 6

def valid_email?(email)
  !!(email =~ /\w@\w/)
end