-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdata_uri.rb
More file actions
93 lines (75 loc) · 1.64 KB
/
Copy pathdata_uri.rb
File metadata and controls
93 lines (75 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
class DataUri
REGEXP = %r{
\Adata:
(?<mediatype>
(?<mimetype> .+? / .+? )?
(?<parameters> (?: ; .+? = .+? )* )
)?
(?<extension>;base64)?
,
(?<data>.*)
}x.freeze
attr_reader :uri, :match
def initialize(uri)
match = REGEXP.match(uri)
raise ArgumentError, 'invalid data URI' unless match
@uri = uri
@match = match
validate_base64_content
end
def self.valid?(uri)
begin
DataUri.new(uri)
true
rescue ArgumentError
false
end
end
def self.esip6?(uri)
begin
parameters = DataUri.new(uri).parameters
parameters.include?("rule=esip6")
rescue ArgumentError
false
end
end
def validate_base64_content
if base64?
begin
Base64.strict_decode64(data)
rescue ArgumentError
raise ArgumentError, 'malformed base64 content'
end
end
end
def mediatype
"#{mimetype}#{parameters}"
end
def decoded_data
return data unless base64?
Base64.decode64(data)
end
def base64?
!String(extension).empty?
end
def mimetype
if String(match[:mimetype]).empty? || uri.starts_with?("data:,")
return 'text/plain'
end
match[:mimetype]
end
def data
# Special case: if it's "data:," with no mediatype, return everything after comma
if uri.start_with?("data:,")
return uri[6..-1] # Everything after "data:,"
end
match[:data]
end
def parameters
return [] if String(match[:mimetype]).empty? && String(match[:parameters]).empty?
match[:parameters].split(";").reject(&:empty?)
end
def extension
match[:extension]
end
end