-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtask.rb
More file actions
82 lines (64 loc) · 2 KB
/
task.rb
File metadata and controls
82 lines (64 loc) · 2 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
module ConvertApi
class Task
def initialize(from_format, to_format, params, conversion_timeout: nil)
@from_format = from_format
@to_format = to_format
@params = params
@conversion_timeout = conversion_timeout || config.conversion_timeout
end
def run
params = { Timeout: @conversion_timeout, StoreFile: true }.merge(normalize_params(@params))
from_format = @from_format || detect_format(params)
read_timeout = @conversion_timeout + config.conversion_timeout_delta if @conversion_timeout
converter = detect_converter(params)
converter_path = converter ? "/converter/#{converter}" : ''
response = ConvertApi.client.post(
"convert/#{from_format}/to/#{@to_format}#{converter_path}",
params,
read_timeout: read_timeout,
)
Result.new(response)
end
private
def normalize_params(params)
result = {}
symbolize_keys(params).each do |key, value|
case
when key != :StoreFile && key.to_s.end_with?('File')
result[key] = FileParam.build(value)
when key == :Files
result[:Files] = files_batch(value)
else
result[key] = value
end
end
result
end
def symbolize_keys(hash)
hash.map { |k, v| [k.to_sym, v] }.to_h
end
def files_batch(values)
files = Array(values).map { |file| FileParam.build(file) }
# upload files in parallel
files
.select { |file| file.is_a?(UploadIO) }
.map { |upload_io| Thread.new { upload_io.file_id } }
.map(&:join)
files
end
def detect_format(params)
return DEFAULT_URL_FORMAT if params[:Url]
resource = params[:File] || Array(params[:Files]).first
FormatDetector.new(resource, @to_format).run
end
def detect_converter(params)
params.each do |key, value|
return value if key.to_s.downcase == 'converter'
end
nil
end
def config
ConvertApi.config
end
end
end