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) ||
250 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
251 if attrtype == 'text' or attr == 'description'
252 input_type = 'textarea'
253 elsif attrtype == 'datetime'
259 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
260 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
265 key: object.class.to_s.underscore
269 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
271 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
272 ajax_options['data-pk'][:defaults] = object.attributes
274 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
275 @unique_id ||= (Time.now.to_f*1000000).to_i
276 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
278 span_tag = content_tag 'span', rendervalue, {
279 "data-emptytext" => '(none)',
280 "data-placement" => "bottom",
281 "data-type" => input_type,
282 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
283 "data-name" => htmloptions['selection_name'] || attr,
284 "data-object-uuid" => object.uuid,
285 "data-toggle" => "manual",
286 "data-value" => htmloptions['data-value'] || attrvalue,
288 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
289 }.merge(htmloptions).merge(ajax_options)
291 edit_tiptitle = 'edit'
292 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')
294 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>')
296 if nonhtml_options[:btnplacement] == :left
297 edit_button + ' ' + span_tag
298 elsif nonhtml_options[:btnplacement] == :top
299 edit_button + raw('<br/>') + span_tag
301 span_tag + ' ' + edit_button
305 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
308 attrvalue = value_info
310 if value_info.is_a? Hash
311 if value_info[:output_of]
312 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
314 if value_info[:dataclass]
315 dataclass = value_info[:dataclass]
317 if value_info[:optional] != nil
318 required = (value_info[:optional] != "true")
320 if value_info[:required] != nil
321 required = value_info[:required]
324 # Pick a suitable attrvalue to show as the current value (i.e.,
325 # the one that would be used if we ran the pipeline right now).
326 if value_info[:value]
327 attrvalue = value_info[:value]
328 elsif value_info[:default]
329 attrvalue = value_info[:default]
333 preconfigured_search_str = value_info[:search_for]
336 if not object.andand.attribute_editable?(attr)
337 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
342 dataclass = dataclass.constantize
346 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
349 id = "#{object.uuid}-#{subattr.join('-')}"
354 if value_info.is_a? Hash
358 if (dataclass == Collection) or (dataclass == File)
359 selection_param = object.class.to_s.underscore + dn
360 display_value = attrvalue
361 if value_info.is_a?(Hash)
362 if (link = Link.find? value_info[:link_uuid])
363 display_value = link.name
364 elsif value_info[:link_name]
365 display_value = value_info[:link_name]
366 elsif (sn = value_info[:selection_name]) && sn != ""
370 if (attr == :components) and (subattr.size > 2)
371 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
373 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
375 modal_path = choose_collections_path \
376 ({ title: chooser_title,
377 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
379 action_href: pipeline_instance_path(id: object.uuid),
380 action_method: 'patch',
381 preconfigured_search_str: (preconfigured_search_str || ""),
384 use_preview_selection: dataclass == File ? true : nil,
385 selection_param: selection_param,
386 success: 'page-refresh'
390 return content_tag('div', :class => 'input-group') do
391 html = text_field_tag(dn, display_value,
393 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
394 html + content_tag('span', :class => 'input-group-btn') do
397 { :class => "btn btn-primary",
405 if attrvalue.is_a? String
407 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
408 # TODO: find a way to edit with x-editable
412 # When datatype is a String or Fixnum, link_to the attrvalue
413 lt = link_to attrvalue, '#', {
414 "data-emptytext" => "none",
415 "data-placement" => "bottom",
416 "data-type" => datatype,
417 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
418 "data-title" => "Set value for #{subattr[-1].to_s}",
420 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
421 "data-value" => attrvalue,
422 # "clear" button interferes with form-control's up/down arrows
423 "data-clear" => false,
424 :class => "editable #{'required' if required} form-control",
431 def get_cwl_main(workflow)
432 if workflow[:"$graph"].nil?
435 workflow[:"$graph"].each do |tool|
436 if tool[:id] == "#main"
443 def get_cwl_inputs(workflow)
444 get_cwl_main(workflow)[:inputs]
448 def cwl_shortname(id)
452 return id.split("/")[-1]
455 def cwl_input_info(input_schema)
456 required = !(input_schema[:type].include? "null")
457 if input_schema[:type].is_a? Array
458 primary_type = input_schema[:type].select { |n| n != "null" }[0]
459 elsif input_schema[:type].is_a? String
460 primary_type = input_schema[:type]
461 elsif input_schema[:type].is_a? Hash
462 primary_type = input_schema[:type]
464 param_id = cwl_shortname(input_schema[:id])
465 return required, primary_type, param_id
468 def cwl_input_value(object, input_schema, set_attr_path)
471 set_attr_path.each do |a|
473 attrvalue = attrvalue[a.to_sym]
478 def cwl_inputs_required(object, inputs_schema, set_attr_path)
480 inputs_schema.each do |input|
481 required, _, param_id = cwl_input_info(input)
482 _, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
483 r += 1 if required and attrvalue.nil?
488 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
489 required, primary_type, param_id = cwl_input_info(input_schema)
491 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
492 attrvalue = if attrvalue.nil? then "" else attrvalue end
494 id = "#{object.uuid}-#{param_id}"
496 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
498 if ["Directory", "File"].include? primary_type
499 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
500 selection_param = object.class.to_s.underscore + dn
501 if attrvalue.is_a? Hash
502 display_value = attrvalue[:"http://arvados.org/cwl#collectionUUID"] || attrvalue[:"arv:collection"] || attrvalue[:location]
503 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
504 locationre = CollectionsHelper.match(attrvalue[:location][5..-1])
506 if locationre and locationre[4]
507 display_value = "#{Collection.find(re[1]).name} / #{locationre[4][1..-1]}"
509 display_value = Collection.find(re[1]).name
513 modal_path = choose_collections_path \
514 ({ title: chooser_title,
515 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
517 action_href: container_request_path(id: object.uuid),
518 action_method: 'patch',
519 preconfigured_search_str: "",
522 use_preview_selection: primary_type == 'File' ? true : nil,
523 selection_param: selection_param,
524 success: 'page-refresh'
528 return content_tag('div', :class => 'input-group') do
529 html = text_field_tag(dn, display_value,
531 "form-control #{'required' if required}")
532 html + content_tag('span', :class => 'input-group-btn') do
535 { :class => "btn btn-primary",
541 elsif "boolean" == primary_type
542 return link_to attrvalue.to_s, '#', {
543 "data-emptytext" => "none",
544 "data-placement" => "bottom",
545 "data-type" => "select",
546 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
547 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
548 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
550 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
551 "data-value" => attrvalue.to_s,
552 # "clear" button interferes with form-control's up/down arrows
553 "data-clear" => false,
554 :class => "editable #{'required' if required} form-control",
557 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
558 return link_to attrvalue, '#', {
559 "data-emptytext" => "none",
560 "data-placement" => "bottom",
561 "data-type" => "select",
562 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
563 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
564 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
566 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
567 "data-value" => attrvalue,
568 # "clear" button interferes with form-control's up/down arrows
569 "data-clear" => false,
570 :class => "editable #{'required' if required} form-control",
573 elsif primary_type.is_a? String
574 if ["int", "long"].include? primary_type
580 return link_to attrvalue, '#', {
581 "data-emptytext" => "none",
582 "data-placement" => "bottom",
583 "data-type" => datatype,
584 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
585 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
587 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
588 "data-value" => attrvalue,
589 # "clear" button interferes with form-control's up/down arrows
590 "data-clear" => false,
591 :class => "editable #{'required' if required} form-control",
595 return "Unable to render editing control for parameter type #{primary_type}"
599 def render_arvados_object_list_start(list, button_text, button_href,
600 params={}, *rest, &block)
601 show_max = params.delete(:show_max) || 3
602 params[:class] ||= 'btn btn-xs btn-default'
603 list[0...show_max].each { |item| yield item }
604 unless list[show_max].nil?
605 link_to(h(button_text) +
606 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
607 button_href, params, *rest)
611 def render_controller_partial partial, opts
612 cname = opts.delete :controller_name
614 render opts.merge(partial: "#{cname}/#{partial}")
615 rescue ActionView::MissingTemplate
616 render opts.merge(partial: "application/#{partial}")
620 RESOURCE_CLASS_ICONS = {
621 "Collection" => "fa-archive",
622 "ContainerRequest" => "fa-gears",
623 "Group" => "fa-users",
624 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
626 "KeepDisk" => "fa-hdd-o",
627 "KeepService" => "fa-exchange",
628 "Link" => "fa-arrows-h",
629 "Node" => "fa-cloud",
630 "PipelineInstance" => "fa-gears",
631 "PipelineTemplate" => "fa-gears",
632 "Repository" => "fa-code-fork",
633 "Specimen" => "fa-flask",
634 "Trait" => "fa-clipboard",
636 "VirtualMachine" => "fa-terminal",
637 "Workflow" => "fa-gears",
639 DEFAULT_ICON_CLASS = "fa-cube"
641 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
642 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
645 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
646 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
649 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
650 case class_name = object.class.to_s
652 object.group_class ? 'fa-folder' : 'fa-users'
654 RESOURCE_CLASS_ICONS.fetch(class_name, default)
658 def chooser_preview_url_for object, use_preview_selection=false
659 case object.class.to_s
661 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
667 def render_attribute_as_textile( object, attr, attrvalue, truncate )
668 if attrvalue && (is_textile? object, attr)
669 markup = render_markup attrvalue
670 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
677 def render_localized_date(date, opts="")
678 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
681 def render_time duration, use_words, round_to_min=true
682 render_runtime duration, use_words, round_to_min
685 # Keep locators are expected to be of the form \"...<pdh/file_path>\" or \"...<uuid/file_path>\"
686 JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*|[a-z0-9]{5}-4zz18-[a-z0-9]{15}[^'"]*)(?=['"]|\z|$)/
687 def keep_locator_in_json str
688 # Return a list of all matches
689 str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
693 def is_textile?( object, attr )
694 object.textile_attributes.andand.include?(attr)