File: twitter.rb

package info (click to toggle)
mikutter 3.8.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 10,544 kB
  • sloc: ruby: 20,548; sh: 99; makefile: 19
file content (581 lines) | stat: -rw-r--r-- 20,795 bytes parent folder | download
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# -*- coding: utf-8 -*-
require 'json'
require 'twitter-text'

module Plugin::Twitter; end

require_relative 'builder'
require_relative 'model'
require_relative 'mikutwitter'

Plugin.create(:twitter) do

  defevent :favorite,
           priority: :ui_favorited,
           prototype: [Diva::Model, Plugin::Twitter::User, Plugin::Twitter::Message]

  defevent :unfavorite,
           priority: :ui_favorited,
           prototype: [Diva::Model, Plugin::Twitter::User, Plugin::Twitter::Message]

  favorites = Hash.new{ |h, k| h[k] = Set.new } # {user_id: set(message_id)}
  unfavorites = Hash.new{ |h, k| h[k] = Set.new } # {user_id: set(message_id)}

  @twitter_configuration = JSON.parse(file_get_contents(File.join(__dir__, 'configuration.json'.freeze)), symbolize_names: true)

  # Twitter API help/configuration.json を叩いて最新情報を取得する
  Delayer.new do
    twitter = Enumerator.new{|y|
      Plugin.filtering(:worlds, y)
    }.find{|world|
      world.class.slug == :twitter
    }
    if twitter
      (twitter/:help/:configuration).json(cache: true).next do |configuration|
        @twitter_configuration = configuration.symbolize
      end
    end
  end

  # Serviceと、Messageの配列を受け取り、一度以上受け取ったことのあるものを除外して返すフィルタを作成して返す。
  # ただし、除外したかどうかはService毎に記録する。
  # また、アカウント登録前等、serviceがnilの時はシステムメッセージ以外を全て削除し、記録しない。
  # ==== Return
  # フィルタのプロシージャ(Proc)
  def gen_message_filter_with_service
    service_filters = Hash.new{|h,k|h[k] = gen_message_filter}
    ->(service, messages, &cancel) do
      if service
        [service] + service_filters[service.user_obj.id].(messages)
      else
        system = messages.select(&:system?)
        if system.empty?
          cancel.call
        else
          [nil, system]
        end
      end
    end
  end

  # Messageの配列を受け取り、一度以上受け取ったことのあるものを除外して返すフィルタを作成して返す
  # ==== Return
  # フィルタのプロシージャ(Proc)
  def gen_message_filter
    appeared = Set.new
    ->(messages) do
      [messages.select{ |message| appeared.add(message.id) unless appeared.include?(message.id) }]
    end
  end

  # URL _url_ がTwitterに投稿された時に何文字としてカウントされるかを返す
  # ==== Args
  # [url] String URL
  # ==== Return
  # Fixnum URLの長さ
  def posted_url_length(url)
    if url.start_with?('https://'.freeze)
      @twitter_configuration[:short_url_length_https] || 23
    else
      @twitter_configuration[:short_url_length] || 22
    end
  end

  filter_update(&gen_message_filter_with_service)

  filter_mention(&gen_message_filter_with_service)

  filter_direct_messages(&gen_message_filter_with_service)

  filter_appear(&gen_message_filter)

  defspell(:destroy, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){ tweet.from_me?(twitter) }
          ) do |twitter, tweet|
    (twitter/"statuses/destroy".freeze/tweet.id).message.next{ |destroyed_tweet|
      destroyed_tweet[:rule] = :destroy
      Plugin.call(:destroyed, [destroyed_tweet])
      destroyed_tweet
    }
  end

  defspell(:destroy_share, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){ shared?(twitter, tweet) }
          ) do |twitter, tweet|
    shared(twitter, tweet).next{ |retweet|
      destroy(twitter, retweet)
    }
  end

  defspell(:favorite, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){
             !favorited?(twitter, tweet)
           }) do |twitter, tweet|
    Plugin.call(:before_favorite, twitter, twitter.user_obj, tweet)
    (twitter/'favorites/create'.freeze).message(id: tweet.id).next{ |favorited_tweet|
      Plugin.call(:favorite, twitter, twitter.user_obj, favorited_tweet)
      favorited_tweet
    }.trap{ |e|
      Plugin.call(:fail_favorite, twitter, twitter.user_obj, tweet)
      Deferred.fail(e)
    }
  end

  defspell(:favorited, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){ favorited?(twitter.user_obj, tweet) }
          ) do |twitter, tweet|
    Delayer::Deferred.new.next{
      favorited?(twitter.user, tweet)
    }
  end

  defspell(:favorited, :twitter_user, :twitter_tweet,
           condition: ->(user, tweet){ tweet.favorited_by.include?(user) }
          ) do |user, tweet|
    Delayer::Deferred.new.next{
      favorited?(user, tweet)
    }
  end

  defspell(:compose, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet, visibility: nil){
             !(visibility && visibility != :public)
           }) do |twitter, tweet, body:, **options|
    twitter.post_tweet(message: body, replyto: tweet, **options)
  end

  defspell(:compose, :twitter, :twitter_direct_message,
           condition: ->(twitter, direct_message, visibility: nil){
             !(visibility && visibility != :direct)
           }) do |twitter, direct_message, body:, **options|
    twitter.post_dm(user: direct_message.user, text: body, **options)
  end

  defspell(:compose, :twitter, :twitter_user,
           condition: ->(twitter, user, visibility: nil){
             !(visibility && ![:public, :direct].include?(visibility))
           }) do |twitter, user, visibility: nil, body:, **options|
    case visibility
    when :public, nil
      twitter.post_tweet(message: body, receiver: user, **options)
    when :direct
      twitter.post_dm(user: user, text: body, **options)
    else
      raise "invalid visibility `#{visibility.inspect}'."
    end
  end

  # 宛先なしのタイムラインへのツイートか、 _to_ オプション引数で複数宛てにする場合。
  # Twitterでは複数宛先は対応していないため、 _to_ オプションの1つめの値に対する投稿とする
  defspell(:compose, :twitter,
           condition: ->(twitter, to: nil){
             first = Array(to).compact.first
             !(first && !compose?(twitter, first))
           }) do |twitter, body:, to: nil, **options|
    first = Array(to).compact.first
    if first
      compose(twitter, first, body: body, **options)
    else
      twitter.post_tweet(to: to, message: body, **options)
    end
  end

  defspell(:share, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){ !tweet.protected? }
          ) do |twitter, tweet|
    twitter.retweet(id: tweet.id).next{|retweeted|
      Plugin.call(:posted, twitter, [retweeted])
      Plugin.call(:update, twitter, [retweeted])
      retweeted
    }
  end

  defspell(:shared, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){ tweet.retweeted_users.include?(twitter.user_obj) }
          ) do |twitter, tweet|
    Delayer::Deferred.new.next{
      retweet = tweet.retweeted_statuses.find{|rt| rt.user == twitter.user_obj }
      if retweet
        retweet
      else
        raise "ReTweet not found."
      end
    }
  end

  defspell(:unfavorite, :twitter, :twitter_tweet,
           condition: ->(twitter, tweet){
             favorited?(twitter, tweet)
           }) do |twitter, tweet|
    (twitter/'favorites/destroy'.freeze).message(id: tweet.id).next{ |unfavorited_tweet|
      Plugin.call(:unfavorite, twitter, twitter.user_obj, unfavorited_tweet)
      unfavorited_tweet
    }
  end

  defspell(:search, :twitter) do |twitter, **options|
    twitter.search(**options)
  end

  defspell(:update_profile_name, :twitter) do |twitter, name:|
    (twitter/'account/update_profile').user(name: name)
  end

  defspell(:update_profile_location, :twitter) do |twitter, location:|
    (twitter/'account/update_profile').user(location: location)
  end

  defspell(:update_profile_url, :twitter) do |twitter, url:|
    (twitter/'account/update_profile').user(url: url)
  end

  defspell(:update_profile_biography, :twitter) do |twitter, biography:|
    (twitter/'account/update_profile').user(description: biography)
  end

  defspell(:update_profile_icon, :twitter, :photo) do |twitter, photo|
    photo.download.next{ |downloaded|
      (twitter/'account/update_profile_image').user(image: Base64.encode64(downloaded.blob))
    }
  end

  defspell(:remain_charcount, :twitter) do |twitter, body:|
    body = trim_hidden_regions(body)
    Twitter::TwitterText::Extractor.extract_urls(body).map{|url|
      posted_url_length = Plugin.filtering(:tco_url_length, url, 0).last
      if url.length < posted_url_length
        -(posted_url_length - url.length)
      else
        url.length - posted_url_length
      end
    }.inject(140 - body.size, &:+)
  end

  def trim_hidden_regions(text)
    trim_hidden_header(trim_hidden_footer(text))
  end

  # 文字列からhidden headerを除いた文字列を返す。
  # hidden headerが含まれていない場合は、 _text_ を返す。
  def trim_hidden_header(text)
    return text unless UserConfig[:auto_populate_reply_metadata]
    mentions = text.match(%r[\A((?:@[a-zA-Z0-9_]+\s+)+)])
    forecast_receivers_sn = Set.new
    if reply?
      @to.first.each_ancestor.each do |m|
        forecast_receivers_sn << m.user.idname
        forecast_receivers_sn.merge(m.receive_user_screen_names)
      end
    end
    if mentions
      specific_screen_names = Set.new(mentions[1].split(/\s+/).map{|s|s[1, s.size]})
      [*(specific_screen_names - forecast_receivers_sn).map{|s|"@#{s}"}, text[mentions.end(0),text.size]].join(' '.freeze)
    else
      text
    end
  end

  # 文字列からhidden footerを除いた文字列を返す。
  # hidden footerが含まれていない場合は、 _text_ を返す。
  def trim_hidden_footer(text)
    attachment_url = text.match(%r[\A(.*?)\s+(https?://twitter.com/(?:#!/)?(?:[a-zA-Z0-9_]+)/status(?:es)?/(?:\d+)(?:\?.*)?)\Z]m)
    if attachment_url
      attachment_url[1]
    else
      text
    end
  end

  # リツイートを削除した時、ちゃんとリツイートリストからそれを削除する
  on_destroyed do |messages|
    messages.each{ |message|
      if message.retweet?
        source = message.retweet_source(false)
        if source
          Plugin.call(:retweet_destroyed, source, message.user, message[:id])
          source.retweeted_sources.delete(message) end end } end

  onappear do |messages|
    retweets = messages.select(&:retweet?).map do |message|
      result = message.retweet_ancestors.to_a[-2]
      fail "invalid retweet #{message.inspect}. ancestors: #{message.retweet_ancestors.to_a.inspect}" unless result.is_a?(Plugin::Twitter::Message)
      result
    end
    if not retweets.empty?
      Plugin.call(:retweet, retweets)
    end
  end

  # 同じツイートに対するfavoriteイベントは一度しか発生させない
  filter_favorite do |service, user, message|
    Plugin.filter_cancel! if favorites[user[:id]].include? message[:id]
    favorites[user[:id]] << message[:id]
    [service, user, message]
  end

  # 同じツイートに対するunfavoriteイベントは一度しか発生させない
  filter_unfavorite do |service, user, message|
    Plugin.filter_cancel! if unfavorites[user[:id]].include? message[:id]
    unfavorites[user[:id]] << message[:id]
    [service, user, message]
  end

  # followers_createdイベントが発生したら、followイベントも発生させる
  on_followers_created do |service, users|
    users.each do |user|
      Plugin.call(:follow, user, service.user_obj)
    end
  end

  # followings_createdイベントが発生したら、followイベントも発生させる
  on_followings_created do |service, users|
    users.each do |user|
      Plugin.call(:follow, service.user_obj, user)
    end
  end

  # t.coによって短縮されたURLの長さを求める
  filter_tco_url_length do |url, length|
    [url, posted_url_length(url)]
  end

  # Twitter Entity情報を元にScoreをあれする
  filter_score_filter do |message, note, yielder|
    if message == note && %i<twitter_tweet twitter_direct_message>.include?(message.class.slug)
      score = score_by_entity(message) + extended_entity_media(message)
      if !score.all?{|n| n.class.slug == :score_text }
        yielder << score
      end
    end
    [message, note, yielder]
  end

  # 正規表現マッチで、ユーザのSNっぽいやつをユーザページにリンクする
  filter_score_filter do |message, note, yielder|
    if message != note && %i<twitter_tweet twitter_direct_message>.include?(message.class.slug)
      score = score_by_screen_name_regexp(note.description)
      yielder << score if score.size >= 2
    end
    [message, note, yielder]
  end

  # 正規表現マッチで、ハッシュタグっぽいやつをHashTag Modelにリンクする
  filter_score_filter do |message, note, yielder|
    if message != note && %i<twitter_tweet twitter_direct_message>.include?(message.class.slug)
      score = score_by_hashtag_regexp(note.description)
      yielder << score if score.size >= 2
    end
    [message, note, yielder]
  end

  def score_by_entity(tweet)
    score = Array.new
    cur = 0
    text = tweet.description
    tweet[:entities].flat_map{|kind, entities|
      case kind
      when :hashtags
        entity_hashtag(tweet, entities)
      when :urls
        entity_urls(tweet, entities)
      when :user_mentions
        entitiy_users(tweet, entities)
      when :symbols
      # 誰得
      when :media
        entity_media(tweet, entities)
      end
    }.compact.sort_by{|range, _|
      range.first
    }.each do |range, note|
      if range.first != cur
        score << text_note(
          description: text[cur...range.first])
      end
      score << note
      cur = range.last
    end
    if cur == 0
      return [text_note(description: text)]
    end
    if cur != text.size
      score << text_note(
        description: text[cur...text.size])
    end
    score
  end

  def extended_entity_media(tweet)
    extended_entities = (tweet[:extended_entities][:media] rescue nil)
    if extended_entities
      space = text_note(description: ' ')
      result = extended_entities.map{ |media|
        case media[:type]
        when 'photo'
          photo = Diva::Model(:photo)&.generate(photo_variant_seeds(media), perma_link: media[:media_url_https])
          photo ||= Enumerator.new{|y| Plugin.filtering(:photo_filter, media[:media_url_https], y) }.first
          if photo
            Diva::Model(:score_hyperlink).new(
              description: photo.uri,
              uri: photo.uri,
              reference: photo)
          else
            Diva::Model(:score_hyperlink).new(
              description: media[:media_url_https],
              uri: media[:media_url_https])
          end
        when 'video'
          variant = Array(media[:video_info][:variants])
                      .select{|v|v[:content_type] == "video/mp4"}
                      .sort_by{|v|v[:bitrate]}
                      .last
          Diva::Model(:score_hyperlink).new(
            description: "#{media[:display_url]} (%.1fs)" % (media.dig(:video_info, :duration_millis)/1000.0),
            uri: variant[:url])
        when 'animated_gif'
          variant = Array(media[:video_info][:variants])
                      .select{|v|v[:content_type] == "video/mp4"}
                      .sort_by{|v|v[:bitrate]}
                      .last
          Diva::Model(:score_hyperlink).new(
            description: "#{media[:display_url]} (GIF)",
            uri: variant[:url])
        end
      }.flat_map{|media| [media, space] }
      result.pop
      result
    else
      []
    end
  end

  def photo_variant_seeds(media)
    Enumerator.new do |yielder|
      yielder << { policy: :original,
                   photo: "#{media[:media_url_https]}:orig" }
      media[:sizes].select{ |size_name, size|
        size.has_key?(:w) && size.has_key?(:h) && size.has_key?(:resize)
      }.each do |size_name, size|
        yielder << { name: size_name.to_sym,
                     width: size[:w],
                     height: size[:h],
                     policy: size[:resize].to_sym,
                     photo: "#{media[:media_url_https]}:#{size_name}" }
      end
    end
  end

  def entity_media(tweet, media_list)
    entities_to_notes(media_list) do |media_entity|
      text_note(description: '')
    end
  end

  def entitiy_users(tweet, user_entities)
    entities_to_notes(user_entities) do |user_entity|
      user = Plugin::Twitter::User.findbyid(user_entity[:id], Diva::DataSource::USE_LOCAL_ONLY)
      if user
        Diva::Model(:score_hyperlink).new(
          description: "@#{user.idname}",
          uri: user.uri,
          reference: user)
      else
        screen_name = user_entity[:screen_name] || tweet.description[Range.new(*user_entity[:indices])]
        Diva::Model(:score_hyperlink).new(
          description: "@#{screen_name}",
          uri: "https://twitter.com/#{screen_name}")
      end
    end
  end

  def entity_urls(tweet, urls)
    entities_to_notes(urls) do |url_entity|
      begin
        uri = Diva::URI.new(url_entity[:expanded_url] || url_entity[:url])
        uri.freeze
        Diva::Model(:score_hyperlink).new(
          description: url_entity[:display_url] || url_entity[:expanded_url] || url_entity[:url],
          uri: uri)
      rescue Addressable::URI::InvalidURIError => e
        text_note(description: url_entity[:display_url] || url_entity[:expanded_url] || url_entity[:url])
      end
    end
  end

  def entity_hashtag(tweet, hashtag_entities)
    entities_to_notes(hashtag_entities) do |hashtag|
      Plugin::Twitter::HashTag.new(name: hashtag[:text])
    end
  end

  def entities_to_notes(entities)
    entities.map do |media|
      [ Range.new(*media[:indices], false),
        yield(media) ]
    end
  end

  def score_by_screen_name_regexp(text)
    score_by_regexp(text,
                    pattern: Plugin::Twitter::Message::MentionMatcher,
                    reference_generator: ->(name){ Plugin::Twitter::User.findbyidname(name, Diva::DataSource::USE_LOCAL_ONLY) },
                    uri_generator: ->(name){ "https://twitter.com/#{CGI.escape(name)}" })
  end

  def score_by_hashtag_regexp(text)
    score_by_regexp(text,
                    pattern: /(?:#|#)[a-zA-Z0-9_]+/,
                    reference_generator: ->(name){ Plugin::Twitter::HashTag.new(name: name) },
                    uri_generator: ->(name){ "https://twitter.com/hashtag/#{CGI.escape(name)}" })
  end

  def score_by_regexp(text, score=Array.new, pattern:, reference_generator:, uri_generator:)
    lead, target, trail = text.partition(pattern)
    score << text_note(description: lead)
    if !(target.empty? || trail.empty?)
      trim = target[1, target.size]
      score << Diva::Model(:score_hyperlink).new(
        description: target,
        uri: uri_generator.(trim),
        reference: reference_generator.(trim))
      score_by_regexp(trail, score,
                      pattern: pattern,
                      reference_generator: reference_generator,
                      uri_generator: uri_generator)
    else
      score
    end
  end

  # TextNoteを作成する。
  # _description:_ から実体参照をアンエスケープした文字列を使ってText Noteを作る。
  # Plugin::Twitter::Message#descriptionの結果が実体参照をエスケープすると
  # Entityのインデックスがずれるので、このメソッドで行う。
  def text_note(description:)
    Diva::Model(:score_text).new(description: description.gsub(Plugin::Twitter::Message::DESCRIPTION_UNESCAPE_REGEXP, &Plugin::Twitter::Message::DESCRIPTION_UNESCAPE_RULE))
  end

  # トークン切れの警告
  MikuTwitter::AuthenticationFailedAction.register do |service, method = nil, url = nil, options = nil, res = nil|
    activity(:system, _("アカウントエラー (@{user})", user: service.user),
             description: _("ユーザ @{user} のOAuth 認証が失敗しました (@{response})\n設定から、認証をやり直してください。",
                            user: service.user, response: res))
    nil
  end

  world_setting(:twitter, _('Twitter')) do
    ck, cs = Plugin.filtering(:twitter_default_api_keys, nil, nil)
    builder = Plugin::Twitter::Builder.new(
      ck || Environment::TWITTER_CONSUMER_KEY,
      cs || Environment::TWITTER_CONSUMER_SECRET)
    label _("Webページにアクセスして表示された番号を、「トークン」に入力して、次へボタンを押してください。")
    link builder.authorize_url
    input "トークン", :token
    result = await_input

    world = await builder.build(result[:token])
    label _("このアカウントでログインしますか?")
    link world.user_obj
    world
  end
end