1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 module ApplicationHelper
7 controller.current_user
10 def self.match_uuid(uuid)
11 /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
15 if Rails.configuration.Services.Controller.ExternalURL.port == 443
16 "#{Rails.configuration.Services.Controller.ExternalURL.hostname}"
18 "#{Rails.configuration.Services.Controller.ExternalURL.hostname}:#{Rails.configuration.Services.Controller.ExternalURL.port}"
22 def current_uuid_prefix
23 Rails.configuration.ClusterID
26 def render_markup(markup)
27 allowed_tags = Rails::Html::Sanitizer.white_list_sanitizer.allowed_tags + %w(table tbody th tr td col colgroup caption thead tfoot)
28 sanitize(raw(RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile)), tags: allowed_tags) if markup
31 def human_readable_bytes_html(n)
32 return h(n) unless n.is_a? Integer
33 return "0 bytes" if (n == 0)
39 (1024*1024*1024) => "GiB",
40 (1024*1024*1024*1024) => "TiB"
45 if sig >=1 and sig < 1024
47 return "%i #{v}" % sig
49 return "%0.1f #{v}" % sig
57 def resource_class_for_uuid(attrvalue, opts={})
58 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
61 # When using {remote:true}, or using {method:...} to use an HTTP
62 # method other than GET, move the target URI from href to
63 # data-remote-href. Otherwise, browsers offer features like "open in
64 # new window" and "copy link address" which bypass Rails' click
65 # handler and therefore end up at incorrect/nonexistent routes (by
66 # ignoring data-method) and expect to receive pages rather than
67 # javascript responses.
69 # See assets/javascripts/link_to_remote.js for supporting code.
70 def link_to *args, &block
71 if (args.last and args.last.is_a? Hash and
72 (args.last[:remote] or
73 (args.last[:method] and
74 args.last[:method].to_s.upcase != 'GET')))
76 # Capybara/phantomjs can't click_link without an href, even if
77 # the click handler means it never gets used.
78 raw super.gsub(' href="', ' href="#" data-remote-href="')
80 # Regular browsers work as desired: users can click A elements
81 # without hrefs, and click handlers fire; but there's no "copy
82 # link address" option in the right-click menu.
83 raw super.gsub(' href="', ' data-remote-href="')
91 # Returns HTML that links to the Arvados object specified in +attrvalue+
92 # Provides various output control and styling options.
94 # +attrvalue+ an Arvados model object or uuid
96 # +opts+ a set of flags to control output:
98 # [:link_text] the link text to use (may include HTML), overrides everything else
100 # [:friendly_name] whether to use the "friendly" name in the link text (by
101 # calling #friendly_link_name on the object), otherwise use the uuid
103 # [:with_class_name] prefix the link text with the class name of the model
105 # [:no_tags] disable tags in the link text (default is to show tags).
106 # Currently tags are only shown for Collections.
108 # [:thumbnail] if the object is a collection, show an image thumbnail if the
109 # collection consists of a single image file.
111 # [:no_link] don't create a link, just return the link text
113 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
115 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
116 if (resource_class = resource_class_for_uuid(attrvalue, opts))
117 if attrvalue.is_a? ArvadosBase
119 link_uuid = attrvalue.uuid
122 link_uuid = attrvalue
124 link_name = opts[:link_text]
127 link_name = object.andand.default_name || resource_class.default_name
129 if opts[:friendly_name]
130 if attrvalue.respond_to? :friendly_link_name
131 link_name = attrvalue.friendly_link_name opts[:lookup]
134 if resource_class.name == 'Collection'
135 if CollectionsHelper.match(link_uuid)
136 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
138 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
141 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
143 rescue ArvadosApiClient::NotFoundException
144 # If that lookup failed, the link will too. So don't make one.
149 if link_name.nil? or link_name.empty?
150 link_name = attrvalue
152 if opts[:with_class_name]
153 link_name = "#{resource_class.to_s}: #{link_name}"
155 if !opts[:no_tags] and resource_class == Collection
156 links_for_object(link_uuid).each do |tag|
157 if tag.link_class.in? ["tag", "identifier"]
158 tags += ' <span class="label label-info">'
159 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
164 if opts[:thumbnail] and resource_class == Collection
165 # add an image thumbnail if the collection consists of a single image file.
166 collections_for_object(link_uuid).each do |c|
167 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
169 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
174 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
175 if opts[:no_link] or (resource_class == User && !current_user)
178 controller_class = resource_class.to_s.tableize
179 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
180 controller_class = 'projects'
182 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
185 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
186 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
194 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
195 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
197 return link_to_if_arvados_object attrvalue, opts
200 readable = object_readable attrvalue, resource_class
202 link_to_if_arvados_object attrvalue, opts
203 elsif opts[:required] and current_user # no need to show this for anonymous user
204 raw('<div><input type="text" style="border:none;width:100%;background:#ffdddd" disabled=true class="required unreadable-input" value="') + link_text_if_not_readable + raw('" ></input></div>')
206 link_text_if_not_readable
210 # This method takes advantage of preloaded collections and objects.
211 # Hence you can improve performance by first preloading objects
212 # related to the page context before using this method.
213 def object_readable attrvalue, resource_class=nil
214 # if it is a collection filename, check readable for the locator
215 attrvalue = attrvalue.split('/')[0] if attrvalue
217 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
218 return if resource_class.nil?
221 if resource_class.to_s == 'Collection'
222 if CollectionsHelper.match(attrvalue)
223 found = collection_for_pdh(attrvalue)
224 return_value = found.first if found.any?
226 found = collections_for_object(attrvalue)
227 return_value = found.first if found.any?
230 return_value = object_for_dataclass(resource_class, attrvalue)
235 # Render an editable attribute with the attrvalue of the attr.
236 # The htmloptions are added to the editable element's list of attributes.
237 # The nonhtml_options are only used to customize the display of the element.
238 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
239 attrvalue = object.send(attr) if attrvalue.nil?
240 if not object.attribute_editable?(attr)
241 if attrvalue && attrvalue.length > 0
242 return render_attribute_as_textile( object, attr, attrvalue, false )
244 return (attr == 'name' and object.andand.default_name) ||
251 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
252 if attrtype == 'text' or attr == 'description'
253 input_type = 'textarea'
254 elsif attrtype == 'datetime'
256 elsif attrtype == 'boolean'
257 input_type = 'select'
258 opt_selection = ([{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json
263 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
264 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
269 key: object.class.to_s.underscore
273 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
275 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
276 ajax_options['data-pk'][:defaults] = object.attributes
278 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
279 @unique_id ||= (Time.now.to_f*1000000).to_i
280 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
282 span_tag = content_tag 'span', rendervalue, {
283 "data-emptytext" => '(none)',
284 "data-placement" => "bottom",
285 "data-type" => input_type,
286 "data-source" => opt_selection,
287 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
288 "data-name" => htmloptions['selection_name'] || attr,
289 "data-object-uuid" => object.uuid,
290 "data-toggle" => "manual",
291 "data-value" => htmloptions['data-value'] || attrvalue,
293 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
294 }.merge(htmloptions).merge(ajax_options)
296 edit_tiptitle = 'edit'
297 edit_tiptitle = 'Warning: do not use hyphens in the repository name as they will be stripped' if (object.class.to_s == 'Repository' and attr == 'name')
299 edit_button = raw('<a href="#" class="btn btn-xs btn-' + (nonhtml_options[:btnclass] || 'default') + ' btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (nonhtml_options[:tiptitle] || edit_tiptitle) + '"><i class="fa fa-fw fa-pencil"></i>' + (nonhtml_options[:btntext] || '') + '</a>')
301 if nonhtml_options[:btnplacement] == :left
302 edit_button + ' ' + span_tag
303 elsif nonhtml_options[:btnplacement] == :top
304 edit_button + raw('<br/>') + span_tag
306 span_tag + ' ' + edit_button
310 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
313 attrvalue = value_info
315 if value_info.is_a? Hash
316 if value_info[:output_of]
317 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
319 if value_info[:dataclass]
320 dataclass = value_info[:dataclass]
322 if value_info[:optional] != nil
323 required = (value_info[:optional] != "true")
325 if value_info[:required] != nil
326 required = value_info[:required]
329 # Pick a suitable attrvalue to show as the current value (i.e.,
330 # the one that would be used if we ran the pipeline right now).
331 if value_info[:value]
332 attrvalue = value_info[:value]
333 elsif value_info[:default]
334 attrvalue = value_info[:default]
338 preconfigured_search_str = value_info[:search_for]
341 if not object.andand.attribute_editable?(attr)
342 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
347 dataclass = dataclass.constantize
351 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
354 id = "#{object.uuid}-#{subattr.join('-')}"
359 if value_info.is_a? Hash
363 if (dataclass == Collection) or (dataclass == File)
364 selection_param = object.class.to_s.underscore + dn
365 display_value = attrvalue
366 if value_info.is_a?(Hash)
367 if (link = Link.find? value_info[:link_uuid])
368 display_value = link.name
369 elsif value_info[:link_name]
370 display_value = value_info[:link_name]
371 elsif (sn = value_info[:selection_name]) && sn != ""
375 if (attr == :components) and (subattr.size > 2)
376 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
378 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
380 modal_path = choose_collections_path \
381 ({ title: chooser_title,
382 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
384 action_href: pipeline_instance_path(id: object.uuid),
385 action_method: 'patch',
386 preconfigured_search_str: (preconfigured_search_str || ""),
389 use_preview_selection: dataclass == File ? true : nil,
390 selection_param: selection_param,
391 success: 'page-refresh'
395 return content_tag('div', :class => 'input-group') do
396 html = text_field_tag(dn, display_value,
398 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
399 html + content_tag('span', :class => 'input-group-btn') do
402 { :class => "btn btn-primary",
410 if attrvalue.is_a? String
412 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
413 # TODO: find a way to edit with x-editable
417 # When datatype is a String or Fixnum, link_to the attrvalue
418 lt = link_to attrvalue, '#', {
419 "data-emptytext" => "none",
420 "data-placement" => "bottom",
421 "data-type" => datatype,
422 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
423 "data-title" => "Set value for #{subattr[-1].to_s}",
425 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
426 "data-value" => attrvalue,
427 # "clear" button interferes with form-control's up/down arrows
428 "data-clear" => false,
429 :class => "editable #{'required' if required} form-control",
436 def get_cwl_main(workflow)
437 if workflow[:"$graph"].nil?
440 workflow[:"$graph"].each do |tool|
441 if tool[:id] == "#main"
448 def get_cwl_inputs(workflow)
449 get_cwl_main(workflow)[:inputs]
453 def cwl_shortname(id)
457 return id.split("/")[-1]
460 def cwl_input_info(input_schema)
461 required = !(input_schema[:type].include? "null")
462 if input_schema[:type].is_a? Array
463 primary_type = input_schema[:type].select { |n| n != "null" }[0]
464 elsif input_schema[:type].is_a? String
465 primary_type = input_schema[:type]
466 elsif input_schema[:type].is_a? Hash
467 primary_type = input_schema[:type]
469 param_id = cwl_shortname(input_schema[:id])
470 return required, primary_type, param_id
473 def cwl_input_value(object, input_schema, set_attr_path)
476 set_attr_path.each do |a|
478 attrvalue = attrvalue[a.to_sym]
483 def cwl_inputs_required(object, inputs_schema, set_attr_path)
485 inputs_schema.each do |input|
486 required, _, param_id = cwl_input_info(input)
487 _, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
488 r += 1 if required and attrvalue.nil?
493 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
494 required, primary_type, param_id = cwl_input_info(input_schema)
496 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
497 attrvalue = if attrvalue.nil? then "" else attrvalue end
499 id = "#{object.uuid}-#{param_id}"
501 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
503 if ["Directory", "File"].include? primary_type
504 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
505 selection_param = object.class.to_s.underscore + dn
506 if attrvalue.is_a? Hash
507 display_value = attrvalue[:"http://arvados.org/cwl#collectionUUID"] || attrvalue[:"arv:collection"] || attrvalue[:location]
508 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
509 locationre = CollectionsHelper.match(attrvalue[:location][5..-1])
511 if locationre and locationre[4]
512 display_value = "#{Collection.find(re[1]).name} / #{locationre[4][1..-1]}"
514 display_value = Collection.find(re[1]).name
518 modal_path = choose_collections_path \
519 ({ title: chooser_title,
520 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
522 action_href: container_request_path(id: object.uuid),
523 action_method: 'patch',
524 preconfigured_search_str: "",
527 use_preview_selection: primary_type == 'File' ? true : nil,
528 selection_param: selection_param,
529 success: 'page-refresh'
533 return content_tag('div', :class => 'input-group') do
534 html = text_field_tag(dn, display_value,
536 "form-control #{'required' if required}")
537 html + content_tag('span', :class => 'input-group-btn') do
540 { :class => "btn btn-primary",
546 elsif "boolean" == primary_type
547 return link_to attrvalue.to_s, '#', {
548 "data-emptytext" => "none",
549 "data-placement" => "bottom",
550 "data-type" => "select",
551 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
552 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
553 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
555 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
556 "data-value" => attrvalue.to_s,
557 # "clear" button interferes with form-control's up/down arrows
558 "data-clear" => false,
559 :class => "editable #{'required' if required} form-control",
562 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
563 return link_to attrvalue, '#', {
564 "data-emptytext" => "none",
565 "data-placement" => "bottom",
566 "data-type" => "select",
567 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
568 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
569 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
571 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
572 "data-value" => attrvalue,
573 # "clear" button interferes with form-control's up/down arrows
574 "data-clear" => false,
575 :class => "editable #{'required' if required} form-control",
578 elsif primary_type.is_a? String
579 if ["int", "long"].include? primary_type
585 return link_to attrvalue, '#', {
586 "data-emptytext" => "none",
587 "data-placement" => "bottom",
588 "data-type" => datatype,
589 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
590 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
592 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
593 "data-value" => attrvalue,
594 # "clear" button interferes with form-control's up/down arrows
595 "data-clear" => false,
596 :class => "editable #{'required' if required} form-control",
600 return "Unable to render editing control for parameter type #{primary_type}"
604 def render_arvados_object_list_start(list, button_text, button_href,
605 params={}, *rest, &block)
606 show_max = params.delete(:show_max) || 3
607 params[:class] ||= 'btn btn-xs btn-default'
608 list[0...show_max].each { |item| yield item }
609 unless list[show_max].nil?
610 link_to(h(button_text) +
611 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
612 button_href, params, *rest)
616 def render_controller_partial partial, opts
617 cname = opts.delete :controller_name
619 render opts.merge(partial: "#{cname}/#{partial}")
620 rescue ActionView::MissingTemplate
621 render opts.merge(partial: "application/#{partial}")
625 RESOURCE_CLASS_ICONS = {
626 "Collection" => "fa-archive",
627 "ContainerRequest" => "fa-gears",
628 "Group" => "fa-users",
629 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
631 "KeepDisk" => "fa-hdd-o",
632 "KeepService" => "fa-exchange",
633 "Link" => "fa-arrows-h",
634 "Node" => "fa-cloud",
635 "PipelineInstance" => "fa-gears",
636 "PipelineTemplate" => "fa-gears",
637 "Repository" => "fa-code-fork",
638 "Specimen" => "fa-flask",
639 "Trait" => "fa-clipboard",
641 "VirtualMachine" => "fa-terminal",
642 "Workflow" => "fa-gears",
644 DEFAULT_ICON_CLASS = "fa-cube"
646 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
647 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
650 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
651 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
654 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
655 case class_name = object.class.to_s
657 object.group_class ? 'fa-folder' : 'fa-users'
659 RESOURCE_CLASS_ICONS.fetch(class_name, default)
663 def chooser_preview_url_for object, use_preview_selection=false
664 case object.class.to_s
666 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
672 def render_attribute_as_textile( object, attr, attrvalue, truncate )
673 if attrvalue && (is_textile? object, attr)
674 markup = render_markup attrvalue
675 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
682 def render_localized_date(date, opts="")
683 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
686 def render_time duration, use_words, round_to_min=true
687 render_runtime duration, use_words, round_to_min
690 # Keep locators are expected to be of the form \"...<pdh/file_path>\" or \"...<uuid/file_path>\"
691 JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*|[a-z0-9]{5}-4zz18-[a-z0-9]{15}[^'"]*)(?=['"]|\z|$)/
692 def keep_locator_in_json str
693 # Return a list of all matches
694 str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
698 def is_textile?( object, attr )
699 object.textile_attributes.andand.include?(attr)