Debian Codegraph @

plugin/mastodon/api.rb

raw symbols SCIP
1 require 'httpclient'
2 require 'json'
3 require 'stringio'
4
5 module Plugin::Mastodon
6 class APIResult
7 attr_reader :value
8 attr_reader :header
9
10 def initialize(value, header = nil)
11 @value = value
12 @header = header
13 end
14
15 def [](idx)
16 @value[idx]
17 end
18
19 def []=(idx, val)
20 @value[idx] = val
21 end
22
23 def to_h(&block)
24 @value.to_h(&block)
25 end
26
27 def to_a
28 @value.to_a
29 end
30 end
31
32 class API
33 LINK_HEADER_MATCHER = %r<^<(.*)>; rel="(.*)"$>.freeze
34 ExceptionResponse = Data.define(:body) do
35 def code
36 0
37 end
38 end
39
40 class << self
41 def build_query_recurse(params, results = [], files = [], prefix = '', to_multipart = false)
42 if params.is_a? Hash
43 # key-value pairs
44 params.each do |key, val|
45 inner_prefix = "#{prefix}[#{key.to_s}]"
46 results, files, to_multipart = build_query_recurse(val, results, files, inner_prefix, to_multipart)
47 end
48 elsif params.is_a? Array
49 params.each_index do |i|
50 inner_prefix = "#{prefix}[#{i}]"
51 results, files, to_multipart = build_query_recurse(params[i], results, files, inner_prefix, to_multipart)
52 end
53 elsif params.is_a? Set
54 results, files, to_multipart = build_query_recurse(params.to_a, results, files, prefix, to_multipart)
55 else
56 key = "#{prefix}".sub('[', '').sub(']', '')
57 /^(.*)\[\d+\]$/.match(key) do |m|
58 key = "#{m[1]}[]"
59 end
60 value = params
61 if value.is_a?(Pathname) || value.is_a?(Plugin::Photo::Photo)
62 to_multipart = true
63 end
64
65 case value
66 when Pathname
67 # multipart/form-data にするが、POSTリクエストではない可能性がある(PATCH等)ため、ある程度自力でつくる。
68 # boundary作成や実際のbody構築はhttpclientに任せる。
69 filename = value.basename.to_s
70 disposition = "form-data; name=\"#{key}\"; filename=\"#{filename}\""
71 f = File.open(value.to_s, 'rb')
72 files << f
73 results << {
74 "Content-Type" => "application/octet-stream",
75 "Content-Disposition" => disposition,
76 :content => f,
77 }
78 when Plugin::Photo::Photo
79 filename = Pathname(value.perma_link.path).basename.to_s
80 disposition = "form-data; name=\"#{key}\"; filename=\"#{filename}\""
81 results << {
82 "Content-Type" => "application/octet-stream",
83 "Content-Disposition" => "form-data; name=\"#{key}\"; filename=\"#{filename}\"",
84 :content => StringIO.new(value.blob, 'r'),
85 }
86 else
87 if to_multipart
88 results << {
89 "Content-Type" => "application/octet-stream",
90 "Content-Disposition" => "form-data; name=\"#{key}\"",
91 :content => value,
92 }
93 else
94 results << [key, value]
95 end
96 end
97 end
98 [results, files, to_multipart]
99 end
100
101 # httpclient向けにパラメータHashを変換する
102 def build_query(params, headers)
103 results, files, to_multipart = build_query_recurse(params)
104 if to_multipart
105 headers << ["Content-Type", "multipart/form-data"]
106 end
107 [results, headers, files]
108 end
109
110 # 直接エンドポイントを指定してサーバにHTTPリクエストを行う。
111 # ==== Args
112 # [method] Symbol HTTP method. :get :post :put :patch :delete のいずれか。
113 # [domain] String サーバのドメイン
114 # [path] String エンドポイントのパス
115 # [access_token] String アクセストークン。認証不要のエンドポイントへのアクセスなら省略するかnilを指定可能
116 # [_opts] 使われていない。 TODO: 消す
117 # [headers] Array 追加で送るHTTPヘッダ。[[name, value], ...] のような形式で渡す
118 # [**params] URLのクエリ部分。
119 # ==== Return
120 # [Delayer::Deferred] HTTPレスポンスを受け取るDeferred
121 # HTTPレスポンスが2xx → 成功。APIResponseを渡す
122 # else → 失敗。HTTPClient::Responseを渡す
123 def call(method, domain, path = nil, access_token = nil, _opts = {}, headers = [], **params)
124 promise = Delayer::Deferred.new(true)
125 Thread.new do
126 uri = domain_path_to_uri(domain, path)
127 promise.call(raw_response!(method, uri, access_token, headers, **params))
128 rescue => err
129 promise.fail(err)
130 end
131 promise.next{ |response|
132 case response.status
133 when 200...300
134 parse_link(response, JSON.parse(response.content, symbolize_names: true))
135 else
136 Delayer::Deferred.fail(response)
137 end
138 }
139 end
140
141 # TODO: callを使うようにしてdeprecateにする
142 def call!(method, domain, path = nil, access_token = nil, opts = {}, headers = [], **params)
143 uri = domain_path_to_uri(domain, path)
144 resp = raw_response!(method, uri, access_token, headers, **params)
145 case resp&.status
146 when 200
147 parse_link(resp, JSON.parse(resp.content, symbolize_names: true))
148 end
149 end
150
151 def raw_response!(method, uri, access_token, headers, **params)
152 if access_token && !access_token.empty?
153 headers += [["Authorization", "Bearer " + access_token]]
154 end
155 query_timer(method, uri, params, headers) do
156 send_request(method, params, headers, uri)
157 end
158 end
159
160 private def domain_path_to_uri(domain, path)
161 if domain.is_a? Diva::URI
162 domain
163 else
164 Diva::URI.new('https://' + domain + path)
165 end
166 end
167
168 private def query_timer(method, uri, params, headers, &block)
169 start_time = Time.new.freeze
170 serial = uri.to_s.hash ^ params.freeze.hash
171 Plugin.call(:query_start,
172 serial: serial,
173 method: method,
174 path: uri,
175 options: params,
176 headers: headers,
177 start_time: start_time)
178 result = block.call
179 Plugin.call(:query_end,
180 serial: serial,
181 method: method,
182 path: uri,
183 options: params,
184 start_time: start_time,
185 end_time: Time.new.freeze,
186 res: result)
187 result
188 rescue => exc
189 Plugin.call(:query_end,
190 serial: serial,
191 method: method,
192 path: uri,
193 options: params,
194 start_time: start_time,
195 end_time: Time.new.freeze,
196 res: ExceptionResponse.new("#{exc.message}\n" + exc.backtrace.join("\n")))
197 raise
198 end
199
200 private def send_request(method, params, headers, uri)
201 query, headers, files = build_query(params, headers)
202 body = nil
203 if method != :get # :post, :patch
204 body = query
205 query = nil
206 end
207 client = HTTPClient.new
208 client.ssl_config.set_default_paths
209 client.request(method, uri.to_s, query, body, headers)
210 ensure
211 files&.each(&:close)
212 end
213
214 def parse_link(resp, hash)
215 link = resp.header['Link'].first
216 return APIResult.new(hash) unless hash.is_a?(Array) && link
217 APIResult.new(
218 hash,
219 link
220 .split(', ')
221 .map(&LINK_HEADER_MATCHER.method(:match))
222 .compact
223 .map { |matched| [matched[2].to_sym, Diva::URI.new(matched[1])] }
224 .to_h
225 )
226 end
227
228 def status(domain, id)
229 call(:get, domain, '/api/v1/statuses/' + id.to_s)
230 end
231
232 def status!(domain, id)
233 call!(:get, domain, '/api/v1/statuses/' + id.to_s)
234 end
235
236 def status_by_url(domain, access_token, url)
237 call(:get, domain, '/api/v2/search', access_token, q: url.to_s, resolve: true).next{ |resp|
238 resp[:statuses]
239 }
240 end
241
242 def status_by_url!(domain, access_token, url)
243 call!(:get, domain, '/api/v2/search', access_token, q: url.to_s, resolve: true).next{ |resp|
244 resp[:statuses]
245 }
246 end
247
248 def account_by_url(domain, access_token, url)
249 call(:get, domain, '/api/v2/search', access_token, q: url.to_s, resolve: true).next{ |resp|
250 resp[:accounts]
251 }
252 end
253
254 # _world_ における、 _status_ のIDを検索して返す。
255 # _status_ が _world_ の所属するのと同じサーバに投稿されたものなら、 _status_ のID。
256 # 異なるサーバの _status_ なら、 _world_ のサーバに問い合わせて、そのIDを返すDeferredをリクエストする。
257 # ==== Args
258 # [world] World Model
259 # [status] トゥート
260 # ==== Return
261 # [Delayer::Deferred] _status_ のローカルにおけるID
262 def get_local_status_id(world, status)
263 if world.domain == status.domain
264 Delayer::Deferred.new{ status.id }
265 else
266 status_by_url(world.domain, world.access_token, status.url).next{ |statuses|
267 statuses.dig(0, :id).tap do |id|
268 raise 'Status id does not found.' unless id
269 end
270 }
271 end
272 end
273
274 # _world_ における、 _account_ のIDを検索して返す。
275 # _account_ が _world_ の所属するのと同じサーバに投稿されたものなら、 _account_ のID。
276 # 異なるサーバの _account_ なら、 _world_ のサーバに問い合わせて、そのIDを返すDeferredをリクエストする。
277 # ==== Args
278 # [world] World Model
279 # [account] アカウント (Plugin::Mastodon::Account)
280 # ==== Return
281 # [Delayer::Deferred] _account_ のローカルにおけるID
282 def get_local_account_id(world, account)
283 if world.domain == account.domain
284 Delayer::Deferred.new{ account.id }
285 else
286 account_by_url(world.domain, world.access_token, account.url).next{ |accounts|
287 accounts&.dig(0, :id)
288 }
289 end
290 end
291
292 # Link headerがあるAPIを連続的に叩いて1要素ずつyieldする
293 # ==== Args
294 # [method] HTTPメソッド
295 # [domain] 対象ドメイン
296 # [path] APIパス
297 # [access_token] トークン
298 # [opts] オプション
299 # [:direction] :next or :prev
300 # [:wait] APIコール間にsleepで待機する秒数
301 # [headers] 追加ヘッダ
302 # [params] GET/POSTパラメータ
303 def all!(method, domain, path = nil, access_token = nil, opts = {}, headers = [], **params)
304 opts[:direction] ||= :next
305 opts[:wait] ||= 1
306
307 while true
308 list = API.call!(method, domain, path, access_token, opts, headers, **params)
309
310 if list && list.value.is_a?(Array)
311 list.value.each { |hash| yield hash }
312 end
313
314 break unless list.header.has_key?(opts[:direction])
315
316 url = list.header[opts[:direction]]
317 params = URI.decode_www_form(url.query).to_h.symbolize
318
319 sleep opts[:wait]
320 end
321 end
322
323 def all_with_world!(world, method, path = nil, opts = {}, headers = [], **params, &block)
324 all!(method, world.domain, path, world.access_token, opts, headers, **params, &block)
325 end
326
327 end
328 end
329
330 end