Merge branch '8784-dir-listings'
[arvados.git] / apps / workbench / app / helpers / collections_helper.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 module CollectionsHelper
6   def d3ify_links(links)
7     links.collect do |x|
8       {source: x.tail_uuid, target: x.head_uuid, type: x.name}
9     end
10   end
11
12   ##
13   # Regex match for collection portable data hash, returns a regex match object with the
14   # hash in group 1, (optional) size in group 2, (optional) subsequent uuid
15   # fields in group 3, and (optional) file path within the collection as group
16   # 4
17   # returns nil for no match.
18   #
19   # +pdh+ the portable data hash string to match
20   #
21   def self.match(pdh)
22     /^([a-f0-9]{32})(\+\d+)(\+[^+]+)*?(\/.*)?$/.match(pdh.to_s)
23   end
24
25   ##
26   # Regex match for collection UUIDs, returns a regex match object with the
27   # uuid in group 1, empty groups 2 and 3 (for consistency with the match
28   # method above), and (optional) file path within the collection as group
29   # 4.
30   # returns nil for no match.
31   #
32   def self.match_uuid_with_optional_filepath(uuid_with_optional_file)
33     /^([0-9a-z]{5}-4zz18-[0-9a-z]{15})()()(\/.*)?$/.match(uuid_with_optional_file.to_s)
34   end
35
36   ##
37   # Regex match for common image file extensions, returns a regex match object
38   # with the matched extension in group 1; or nil for no match.
39   #
40   # +file+ the file string to match
41   #
42   def self.is_image file
43     /\.(jpg|jpeg|gif|png|svg)$/i.match(file)
44   end
45
46   ##
47   # Generates a relative file path than can be appended to the URL of a
48   # collection to get a file download link without adding a spurious ./ at the
49   # beginning for files in the default stream.
50   #
51   # +file+ an entry in the Collection.files list in the form [stream, name, size]
52   #
53   def self.file_path file
54     f0 = file[0]
55     f0 = '' if f0 == '.'
56     f0 = f0[2..-1] if f0[0..1] == './'
57     f0 += '/' if not f0.empty?
58     file_path = "#{f0}#{file[1]}"
59   end
60
61   ##
62   # Check if collection preview is allowed for the given filename with extension
63   #
64   def preview_allowed_for file_name
65     file_type = MIME::Types.type_for(file_name).first
66     if file_type.nil?
67       false
68     elsif (file_type.raw_media_type == "text") || (file_type.raw_media_type == "image")
69       true
70     elsif (file_type.raw_media_type == "application") &&
71           (Rails.configuration.application_mimetypes_with_view_icon.include? (file_type.sub_type))
72       true
73     else
74       false
75     end
76   end
77 end