Debian Codegraph @

plugin/mastodon/model/status.rb

raw symbols SCIP
1 # coding: utf-8
2
3 module Plugin::Mastodon
4 # https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#status
5 # 必ずStatus.buildメソッドを通して生成すること
6 class Status < Diva::Model
7 extend Gem::Deprecate
8 include Diva::Model::MessageMixin
9
10 register :mastodon_status, name: Plugin[:mastodon]._('トゥート'), timeline: true, reply: true, myself: true
11
12 field.string :id, required: true
13 field.string :original_uri, required: true # APIから取得するfediverse uniqueなURI文字列
14 field.uri :url, required: true
15 field.has :account, Account, required: true
16 field.string :in_reply_to_id
17 field.string :in_reply_to_account_id
18 field.has :reblog, Status
19 field.string :content, required: true
20 field.time :created_at, required: true
21 field.time :modified
22 field.time :created
23 field.int :reblogs_count
24 field.int :favourites_count
25 field.bool :reblogged
26 field.bool :favourited
27 field.bool :muted
28 field.bool :sensitive
29 field.string :spoiler_text
30 field.string :visibility
31 field.has :application, Application
32 field.string :language
33 field.bool :pinned
34 field.bool :bookmarked
35
36 field.string :domain, required: true # APIには無い追加フィールド
37
38 field.has :emojis, [Emoji]
39 field.has :media_attachments, [Attachment]
40 field.has :mentions, [Mention]
41 field.has :tags, [Tag]
42 field.has :card, Card
43 field.has :poll, Poll
44
45 attr_accessor :reblog_status_uris # :: [String] APIには無い追加フィールド
46 # ブーストしたStatusのuri(これらはreblogフィールドの値としてこのオブジェクトを持つ)と、acctを保持する。
47 attr_accessor :favorite_accts # :: [String] APIには無い追加フィールド
48 attr_accessor :description
49 attr_accessor :score
50
51 alias :uri :url # mikutter側の都合で、URI.parse可能である必要がある(API仕様上のuriフィールドとは異なる)。
52 alias :perma_link :url
53 alias :muted? :muted
54 alias :pinned? :pinned
55 alias :bookmarked? :bookmarked
56 alias :retweet_ancestor :reblog
57 alias :sensitive? :sensitive # NSFW系プラグイン用
58
59 @@mute_mutex = Thread::Mutex.new
60
61 VALID_URL_PRECEDING_CHARS = /(?:[^A-Z0-9@@$##]|^)/io
62 VALID_URL_QUERY_CHARS = /[a-z0-9!?\*'\(\);:&=\+\$\/%#\[\]\-_\.,~|@]/i
63 VALID_URL_QUERY_ENDING_CHARS = /[a-z0-9_&=#\/\-]/i
64 URL_PATTERN = %r{
65 (#{VALID_URL_PRECEDING_CHARS})
66 (
67 (https?:\/\/)
68 ((?:(?!-)[a-z0-9-]{1,63}(?<!-)\.)*(?:xn--)?[a-z]{2,})
69 (?::(\d{1,5}))?
70 (\/
71 [^\s#?!$&'\*,;=]*
72 (?:\#[^\s#?!$&'\*,;=]*)?
73 )?
74 (\?#{VALID_URL_QUERY_CHARS}*#{VALID_URL_QUERY_ENDING_CHARS})?
75 )
76 }iox
77 TOOT_URI_RE = %r!\Ahttps://([^/]+)/@\w{1,30}/(\d+)\z!.freeze
78 TOOT_ACTIVITY_URI_RE = %r!\Ahttps://(?<domain>[^/]*)/users/(?<acct>[^/]*)/statuses/(?<status_id>[^/]*)/activity\z!.freeze
79 USERNAME_RE = /[a-z0-9_]+([a-z0-9_\.-]+[a-z0-9_]+)?/i
80 MENTION_RE = /(?<=^|[^\/[:word:]])@((#{USERNAME_RE})(?:@[[:word:]\.\-]+[[:word:]]+)?)/i
81
82 handle TOOT_URI_RE do |uri|
83 Status.findbyuri(uri) || Status.fetch(uri)
84 end
85
86 class << self
87 @@status_storage = WeakStorage.new(String, Status, name: 'toot')
88
89 def add_status_storage(toot)
90 raise "uri must not nil. but given #{toot.uri.inspect}" unless toot.uri
91 if @@status_storage.has_key?("#{toot.domain}:#{toot.uri}")
92 warn "key already exists: #{toot.domain}:#{toot.uri}"
93 end
94 @@status_storage["#{toot.domain}:#{toot.uri}"] = toot
95 end
96
97 # urlで検索する。
98 # 但しブーストの場合はfediverse uri
99 def findbyuri(uri, domain: nil)
100 domain ||= Diva::URI(uri).host
101 @@status_storage["#{domain}:#{uri}"]
102 end
103
104 def add_mutes(account_hashes)
105 @@mute_mutex.synchronize {
106 @@mutes ||= []
107 @@mutes += account_hashes.map do |hash|
108 hash = Account.regularize_acct hash
109 hash[:acct]
110 end
111 @@mutes = @@mutes.uniq
112 }
113 end
114
115 def clear_mutes
116 @@mute_mutex.synchronize {
117 @@mutes = []
118 }
119 end
120
121 def muted?(acct)
122 @@mute_mutex.synchronize {
123 @@mutes.any? { |a| a == acct }
124 }
125 end
126
127 # Mastodon APIレスポンスのJSONをパースした結果のHashを受け取り、それに対応する
128 # インスタンスを返す。
129 # ==== Args
130 # [server] Mastodonサーバ (Plugin::Mastodon::Instance)
131 # [record] APIレスポンスのstatusオブジェクト (Hash)
132 # ==== Return
133 # Plugin::Mastodon::Status
134 def build(server, record)
135 json2status(server.domain, record)
136 end
137
138 # buildと似ているが、配列を受け取って複数のインスタンスを同時に取得できる。
139 # ==== Args
140 # [server] Mastodonサーバ (Plugin::Mastodon::Instance)
141 # [json] APIレスポンスのstatusオブジェクトの配列 (Array)
142 # ==== Return
143 # Plugin::Mastodon::Status の配列
144 def bulk_build(server, json)
145 json.map do |record|
146 build(server, record)
147 end.to_a
148 end
149
150 def json2status(domain_name, record)
151 record[:domain] = domain_name
152 is_boost = false
153
154 if record[:reblog]
155 is_boost = true
156
157 boost_record = Plugin::Mastodon::Util.deep_dup(record)
158 boost_record[:reblog] = nil
159
160 record = record[:reblog]
161 record[:domain] = domain_name
162 end
163 uri = record[:url] # quoting_messages等のために@@status_storageには:urlで入れておく
164
165 status = merge_or_create(domain_name, uri, record)
166 return nil unless status
167
168 # ブーストの処理
169 if !is_boost
170 status
171 # ブーストではないので、普通にstatusを返す。
172 else
173 boost_uri = boost_record[:uri] # reblogには:urlが無いので:uriで入れておく
174 boost = merge_or_create(domain_name, boost_uri, {**boost_record, url: boost_uri})
175 return nil unless boost
176 status.reblog_status_uris << { uri: boost_uri, acct: boost_record[:account][:acct] }
177 status.reblog_status_uris.uniq!
178
179 # ageなどの対応
180 status.set_modified(boost.modified) if UserConfig[:retweeted_by_anyone_age] and (UserConfig[:retweeted_by_myself_age] or !boost.account.me?)
181
182 boost[:retweet] = boost.reblog = status
183 # わかりづらいが「ブーストした」statusの'reblog'プロパティにブースト元のstatusを入れている
184 boost
185 # 「ブーストした」statusを返す(appearしたのはそれに間違いないので。ブースト元はdon't care。
186 # Gtk::TimeLine#block_addではmessage.retweet?ならmessage.retweet_sourceを取り出して追加する。
187 end
188 end
189
190 def merge_or_create(domain_name, uri, new_hash)
191 @@mutes ||= []
192 if new_hash[:account] && new_hash[:account][:acct]
193 account_hash = Account.regularize_acct(new_hash[:account])
194 if @@mutes.index(account_hash[:acct])
195 return nil
196 end
197 end
198
199 status = findbyuri(uri, domain: domain_name)
200 if status
201 status = status.merge(domain_name, new_hash)
202 else
203 status = Status.new(new_hash)
204 end
205 status
206 end
207
208 def fetch(uri)
209 if m = TOOT_URI_RE.match(uri.to_s)
210 domain_name = m[1]
211 id = m[2]
212 Plugin::Mastodon::API.status(domain_name, id).next{ |resp|
213 Status.build(Plugin::Mastodon::Instance.load(domain_name), resp.value)
214 }
215 else
216 Delayer::Deferred.new(true).tap{|d| d.fail(nil) }
217 end
218 end
219 end
220
221 def initialize(hash)
222 @reblog_status_uris = []
223 @favorite_accts = []
224
225 if hash[:created_at].is_a? String
226 # タイムゾーン考慮
227 hash[:created_at] = Time.parse(hash[:created_at]).localtime
228 end
229 # cairo_sub_parts_message_base用
230 hash[:created] = hash[:created_at]
231 hash[:modified] = hash[:created_at] unless hash[:modified]
232
233 # mikutterはuriをURI型であるとみなす
234 hash[:original_uri] = hash[:uri]
235 hash.delete :uri
236
237 # sub_parts_client用
238 if hash[:application] && hash[:application][:name]
239 hash[:source] = hash[:application][:name]
240 end
241
242 # Mentionのacctにドメイン付加
243 if hash[:mentions]
244 hash[:mentions].each_index do |i|
245 acct = hash[:mentions][i][:acct]
246 hash[:mentions][i][:acct] = Account.regularize_acct_by_domain(hash[:domain], acct)
247 end
248 end
249
250 # notification用
251 hash[:retweet] = hash[:reblog]
252
253 super hash
254
255 self[:user] = self[:account]
256 if self.reblog.is_a?(Status) && self.reblog.account.is_a?(Account)
257 self.reblog[:user] = self.reblog.account
258 end
259
260 @emoji_score = Hash.new
261
262 content = actual_status.content
263 unless spoiler_text.empty?
264 content = spoiler_text + "<br>----<br>" + content
265 end
266 @description, @score = Plugin::Mastodon::Parser.dictate_score(content, mentions: mentions, emojis: emojis, media_attachments: media_attachments, poll: poll)
267
268 self.class.add_status_storage(self)
269 Plugin.call(:mastodon_appear_toots, [self])
270 end
271
272 def inspect
273 "mastodon-status(#{uri} #{description})"
274 end
275
276 def merge(domain_name, new_hash)
277 # 取得元が発言者の所属サーバーであれば優先する
278 account_domain = account&.domain
279 account_domain2 = Account.domain(new_hash[:account][:url])
280 if !domain || domain != account_domain && domain_name == account_domain2
281 self.id = new_hash[:id]
282 self.domain = domain_name
283 if !(application && self[:source]) && new_hash[:application]
284 self.application = Application.new(new_hash[:application])
285 self[:source] = application.name
286 end
287 end
288 reblogs_count = new_hash[:reblogs_count]
289 favourites_count = new_hash[:favourites_count]
290 pinned = new_hash[:pinned]
291 self
292 end
293
294 def actual_status
295 reblog || self
296 end
297
298 def icon
299 actual_status.account.icon
300 end
301
302 def user
303 account
304 end
305
306 def server
307 @server ||= Plugin::Mastodon::Instance.load(domain)
308 end
309
310 def retweet_count
311 [actual_status.reblog_status_uris.size, actual_status.reblogs_count].compact.max
312 end
313
314 def favorite_count
315 [@favorite_accts.size, actual_status.favourites_count].compact.max
316 end
317
318 def retweet?
319 reblog.is_a? Status
320 end
321
322 def retweeted_by
323 actual_status
324 .reblog_status_uris
325 .lazy
326 .filter_map { |v| v[:acct] }
327 .filter_map(&Account.method(:findbyacct))
328 .uniq
329 .to_a
330 end
331
332 def shared?(counterpart=nil)
333 counterpart ||= Plugin.filtering(:world_current, nil).first
334 if counterpart.respond_to?(:user_obj)
335 counterpart = counterpart.user_obj
336 end
337 if counterpart.is_a?(Account)
338 actual_status.retweeted_by.include?(counterpart)
339 end
340 end
341
342 alias :retweeted? :shared?
343
344 def favorited_by
345 @favorite_accts.lazy.filter_map(&Account.method(:findbyacct)).uniq.to_a
346 end
347
348 def favorite?(counterpart = nil)
349 counterpart ||= Plugin.filtering(:world_current, nil).first
350 if counterpart.respond_to?(:user_obj)
351 counterpart = counterpart.user_obj
352 end
353
354 if counterpart.is_a?(Account)
355 @favorite_accts.include?(counterpart.idname)
356 end
357 end
358
359 # sub_parts_client用
360 def source
361 actual_status.application&.name
362 end
363
364 def add_attachments(text)
365 if media_attachments && !media_attachments.empty?
366 media_attachments.each do |attachment|
367 url = attachment.text_url || attachment.url
368 if !text.include?(url.to_s)
369 text += " <a href=\"#{url}\">#{url}</a>"
370 end
371 end
372 end
373 text
374 end
375
376 # 自分が _self_ にリプライを返していればtrue
377 def mentioned_by_me?
378 children.any?(&:from_me?)
379 end
380
381 # _self_ を宛先としたStatusのリストを返す
382 def children
383 @children ||= Set.new(retweeted_statuses)
384 end
385
386 protected def add_child(child)
387 children << child
388 end
389
390 # この投稿の投稿主のアカウントの全権限を所有していればtrueを返す
391 def from_me?(world = Plugin.collect(:worlds))
392 account.me?(world)
393 end
394
395 # 通知用
396 # 自分へのmention
397 def mention_to_me?(world)
398 return false if mentions.empty?
399 return false if (!world.respond_to?(:account) || !world.account.respond_to?(:acct))
400 mentions.map{|mention| mention.acct }.include?(world.account.acct)
401 end
402
403 # 自分へのreblog
404 def reblog_to_me?(world)
405 return false unless reblog
406 reblog.from_me?(world)
407 end
408
409 def to_me_world
410 world = Plugin.filtering(:world_current, nil).first
411 return nil if (!mention_to_me?(world) && !reblog_to_me?(world))
412 world
413 end
414
415 def to_me?(world = nil)
416 if world
417 if world.is_a? Plugin::Mastodon::World
418 return mention_to_me?(world) || reblog_to_me?(world)
419 else
420 return false
421 end
422 end
423 !!to_me_world
424 end
425
426 # activity用
427 def to_s
428 description
429 end
430
431 # ふぁぼ
432 def favorite(do_fav)
433 world, = Plugin.filtering(:world_current, nil)
434 if do_fav
435 Plugin[:mastodon].favorite(world, self)
436 else
437 Plugin[:mastodon].unfavorite(world, self)
438 end
439 end
440
441 def retweeted_statuses
442 reblog_status_uris.map{|pair| self.class.findbyuri(pair[:uri]) }.compact
443 end
444
445 alias :retweeted_sources :retweeted_statuses
446
447 # Message#.introducer
448 # 本当はreblogがあればreblogをreblogした最後のStatusを返す
449 # reblogがなければselfを返す
450 def introducer(world = nil)
451 self
452 end
453
454 # 返信スレッド用
455 def around(force_retrieve=false)
456 if force_retrieve
457 resp = Plugin::Mastodon::API.call!(:get, domain, '/api/v1/statuses/' + id + '/context')
458 return [self] unless resp
459 @around = [*Status.bulk_build(server, resp[:ancestors]),
460 self,
461 *Status.bulk_build(server, resp[:descendants])]
462 else
463 @around || [self]
464 end
465 end
466
467 # tootのリプライ先を再帰的に遡って、見つかった順に列挙する。
468 # 最初に列挙する要素は常に _self_ で、ある要素は次の要素へのリプライとなっている。
469 # ==== Args
470 # [force_retrieve] サーバへの問い合わせを許可するフラグ
471 # ==== Return
472 # Enumerator :: リプライツリーを祖先方向に辿って列挙する (Plugin::Mastodon::Status)
473 def ancestors(force_retrieve=false)
474 if force_retrieve
475 @ancestors ||= ancestors_force.freeze
476 else
477 [self, *replyto_source&.ancestors].freeze
478 end
479 end
480
481 private def ancestors_force
482 resp = Plugin::Mastodon::API.call!(:get, domain, '/api/v1/statuses/' + id + '/context')
483 if resp
484 [self, *Status.bulk_build(server, resp[:ancestors]).reverse]
485 else
486 [self]
487 end
488 end
489
490 # 返信表示用
491 def has_receive_message?
492 !!in_reply_to_id
493 end
494
495 def repliable?(counterpart=nil)
496 true
497 end
498
499 # 返信表示用
500 def replyto_source(force_retrieve=false)
501 # TODO: サーバ+IDでStatusを保存するWeakStoreを使ってキャッシュしたいわね
502 @replyto_source ||=
503 force_retrieve ? replyto_source_force : nil
504 end
505
506 private def replyto_source_force
507 unless domain
508 # 何故かreplyviewerに渡されたStatusからdomainが消失することがあるので復元を試みる
509 world, = Plugin.filtering(:mastodon_current, nil)
510 if world
511 # 見つかったworldでstatusを取得し、id, domain, in_reply_to_idを上書きする。
512 status = Plugin::Mastodon::API.status_by_url!(world.domain, world.access_token, url)
513 if status
514 self[:id] = status[:id]
515 self[:domain] = world.domain
516 self[:in_reply_to_id] = status[:in_reply_to_id]
517 if status[:reblog]
518 self.reblog[:id] = status[:reblog][:id]
519 self.reblog[:domain] = world.domain
520 self.reblog[:in_reply_to_id] = status[:reblog][:in_reply_to_id]
521 end
522 end
523 end
524 end
525 Plugin::Mastodon::API.status!(domain, in_reply_to_id)
526 &.yield_self { |r| Status.build(server, r.value) }
527 &.tap { |parent| parent.add_child(self) }
528 end
529
530 # 返信表示用
531 def replyto_source_d(force_retrieve=true)
532 promise = Delayer::Deferred.new(true)
533 Thread.new do
534 result = replyto_source(force_retrieve)
535 if result.is_a? Status
536 promise.call(result)
537 else
538 promise.fail(result)
539 end
540 rescue Exception => e
541 promise.fail(e)
542 end
543 promise
544 end
545
546 def retweet_source(force_retrieve=false)
547 reblog
548 end
549
550 def retweet_source_d(force_retrieve=false)
551 promise = Delayer::Deferred.new(true)
552 Thread.new do
553 if reblog.is_a? Status
554 promise.call(reblog)
555 else
556 promise.fail(reblog)
557 end
558 rescue Exception => e
559 promise.fail(e)
560 end
561 promise
562 end
563
564 def retweet_ancestors(force_retrieve=false)
565 if reblog.is_a? Status
566 [self, reblog]
567 else
568 [self]
569 end
570 end
571
572 def rebloggable?(world = nil)
573 !actual_status.shared?(world) && !['private', 'direct'].include?(actual_status.visibility)
574 end
575
576 # 最終更新日時を取得する
577 def modified
578 @value[:modified] ||= [created, *(@retweets || []).map{ |x| x.modified }].compact.max
579 end
580 # 最終更新日時を更新する
581 def set_modified(time)
582 if modified < time
583 self[:modified] = time
584 Plugin::call(:message_modified, self)
585 end
586 self
587 end
588
589 def post(message:, **kwrest)
590 world, = Plugin.filtering(:world_current, nil)
591 Plugin[:mastodon].compose(self, world, body: message, **kwrest)
592 end
593 deprecate :post, :none, 2018, 11
594
595 def receive_user_idnames
596 mentions.map(&:acct)
597 end
598 end
599 end