-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtask.rb
More file actions
98 lines (76 loc) · 2.23 KB
/
task.rb
File metadata and controls
98 lines (76 loc) · 2.23 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
94
95
96
97
98
module ConvertApi
class Task
def initialize(from_format, to_format, params, conversion_timeout: nil)
@from_format = from_format
@to_format = to_format
@conversion_timeout = conversion_timeout || config.conversion_timeout
@params = normalize_params(params).merge(
Timeout: @conversion_timeout,
StoreFile: true,
)
@async = @params.delete(:Async)
@converter = detect_converter
end
attr_reader :converter
def run
read_timeout = @conversion_timeout + config.conversion_timeout_delta if @conversion_timeout
response = ConvertApi.client.post(
request_path,
@params,
read_timeout: read_timeout,
)
return AsyncResult.new(response) if async?
Result.new(response)
end
private
def async?
@async.to_s.downcase == 'true'
end
def request_path
from_format = @from_format || detect_format
converter_path = converter ? "/converter/#{converter}" : ''
async = async? ? 'async/' : ''
"#{async}convert/#{from_format}/to/#{@to_format}#{converter_path}"
end
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
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.each do |key, value|
return value if key.to_s.downcase == 'converter'
end
nil
end
def config
ConvertApi.config
end
end
end