File: world.rb

package info (click to toggle)
mikutter 4.1.3%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 9,260 kB
  • sloc: ruby: 20,126; sh: 183; makefile: 19
file content (342 lines) | stat: -rw-r--r-- 10,937 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
# coding: utf-8
module Plugin::Mastodon
  class World < Diva::Model
    extend Memoist

    register :mastodon, name: Plugin[:mastodon]._('Mastodon')

    field.string :id, required: true
    field.string :slug, required: true
    alias :name :slug
    field.string :domain, required: true
    field.string :access_token, required: true
    field.has :account, Account, required: true

    alias :user_obj :account

    @@lists = Hash.new
    @@followings = Hash.new
    @@followers = Hash.new
    @@blocks = Hash.new

    memoize def path
      "/#{account.acct.split('@').reverse.join('/')}"
    end

    def inspect
      "mastodon-world(#{account.acct})"
    end

    def icon
      account.icon
    end

    def title
      account.title
    end

    def server
      @server ||= Plugin::Mastodon::Instance.load(domain)
    end

    def sse
      Plugin::Mastodon::SSEAuthorizedType.new(world: self)
    end

    def rest
      Plugin::Mastodon::RestAuthorizedType.new(world: self)
    end

    def datasource_slug(type, n = nil)
      case type
      when :home
        # ホームTL
        "mastodon-#{account.acct}-home".to_sym
      when :direct
        # DM TL
        "mastodon-#{account.acct}-direct".to_sym
      when :list
        # リストTL
        "mastodon-#{account.acct}-list-#{n}".to_sym
      else
        "mastodon-#{account.acct}-#{type.to_s}".to_sym
      end
    end

    def get_lists
      Delayer::Deferred.new do
        if @@lists[uri.to_s]
          @@lists[uri.to_s]  # TODO: キャッシュはAPIクラスで行いたい
        else
          API.call(:get, domain, '/api/v1/lists', access_token).next do |lists|
            @@lists[uri.to_s] = lists.value
          end
        end
      end
    end

    def update_mutes!
      params = { limit: 80 }
      since_id = nil
      Status.clear_mutes
      while mutes = Plugin::Mastodon::API.call!(:get, domain, '/api/v1/mutes', access_token, **params)
        Status.add_mutes(mutes.value)
        return unless mutes.header && mutes.header[:prev]
        url = mutes.header[:prev]
        params = URI.decode_www_form(url.query).to_h.map{|k,v| [k.to_sym, v] }.to_h
        return if params[:since_id].to_i == since_id
        since_id = params[:since_id].to_i

        sleep 1
      end
    end

    # 投稿する
    # opts[:in_reply_to_id] Integer 返信先Statusの(ローカル)ID
    # opts[:media_ids] Array 添付画像IDの配列(最大4)
    # opts[:sensitive] True | False NSFWフラグの明示的な指定
    # opts[:spoiler_text] String ContentWarning用のコメント
    # opts[:visibility] String 公開範囲。 "direct", "private", "unlisted", "public" のいずれか。
    def post(to: nil, message:, **params)
      params[:status] = message
      if to ||= params[:replyto]
        API.get_local_status_id(self, to).next{ |status_id|
          API.call(:post, domain, '/api/v1/statuses', access_token, in_reply_to_id: status_id, **params)
        }.terminate(Plugin[:mastodon]._('返信先Statusが%{domain}内に見つかりませんでした:%{url}') % {domain: domain, url: to.url})
      else
        API.call(:post, domain, '/api/v1/statuses', access_token, **params)
      end
    end

    # _status_ をboostする。
    # ==== Args
    # [status] boostするtoot
    # ==== Return
    # [Delayer::Deferred] boost完了したら、新たに作られたstatusを返すDeferred
    def reblog(status)
      Plugin::Mastodon::API.get_local_status_id(self, status.actual_status).next{ |status_id|
        new_status_hash = +Plugin::Mastodon::API.call(:post, domain, '/api/v1/statuses/' + status_id.to_s + '/reblog', access_token)
        new_status = Plugin::Mastodon::Status.build(server, new_status_hash.value)
        Plugin.call(:share, new_status.user, status)
        new_status
      }
    end

    def get_accounts!(type)
      promise = Delayer::Deferred.new(true)
      Thread.new do
        accounts = []
        params = {
          limit: 80
        }
        API.all_with_world!(self, :get, "/api/v1/accounts/#{account.id}/#{type}", **params) do |hash|
          accounts << hash
        end
        promise.call(accounts.map {|hash| Account.new hash })
      rescue Exception => e
        Plugin::Mastodon::Util.ppf e if Mopt.error_level >= 2 # warn
        promise.fail("failed to get #{type}")
      end
      promise
    end

    def following?(acct)
      acct = acct.acct if acct.is_a?(Account)
      @@followings[uri.to_s].to_a.any? { |account| account.acct == acct }
    end

    def followings(cache: true, **opts)
      promise = Delayer::Deferred.new(true)
      Thread.new do
        next promise.call(@@followings[uri.to_s]) if cache && @@followings[uri.to_s]
        get_accounts!('following').next do |accounts|
          @@followings[uri.to_s] = accounts
          promise.call(accounts)
        end
      end
      promise
    end

    def followers(cache: true, **opts)
      promise = Delayer::Deferred.new(true)
      Thread.new do
        next promise.call(@@followers[uri.to_s]) if cache && @@followers[uri.to_s]
        get_accounts!('followers').next do |accounts|
          @@followers[uri.to_s] = accounts
          promise.call(accounts)
        end
      end
      promise
    end

    def blocks
      promise = Delayer::Deferred.new(true)
      Thread.new do
        accounts = []
        params = {
          limit: 80
        }
        API.all_with_world!(self, :get, "/api/v1/blocks", **params) do |hash|
          accounts << hash
        end
        @@blocks[uri.to_s] = accounts.map { |hash| Account.new hash }
        promise.call(@@blocks[uri.to_s])
      rescue Exception => e
        Plugin::Mastodon::Util.ppf e if Mopt.error_level >= 2 # warn
        promise.fail('failed to get blocks')
      end
      promise
    end

    def block?(acct)
      @@blocks[uri.to_s].to_a.any? { |acc| acc.acct == acct }
    end

    def account_action(account, type)
      Plugin::Mastodon::API.get_local_account_id(self, account).next{ |account_id|
        Plugin::Mastodon::API.call(:post, domain, "/api/v1/accounts/#{account_id}/#{type}", access_token)
      }
    end

    def follow(account)
      account_action(account, "follow").next{ |ret|
        @@followings[uri.to_s] = [*@@followings[uri.to_s], account]
        followings(cache: false)
        ret
      }
    end

    def unfollow(account)
      account_action(account, "unfollow").next{ |ret|
        if @@followings[uri.to_s]
          @@followings[uri.to_s].delete_if do |acc|
            acc.acct == account.acct
          end
          followings(cache: false)
        end
        ret
      }
    end

    def mute(account)
      account_action(account, "mute").next{ update_mutes! }
    end

    def unmute(account)
      account_action(account, "unmute").next{ update_mutes! }
    end

    def block(account)
      account_action(account, "block").next{
        if @@followings[uri.to_s]
          @@followings[uri.to_s].delete_if do |acc|
            acc.acct == account.acct
          end
        end
        blocks
      }
    end

    def unblock(account)
      account_action(account, "unblock").next{ blocks }
    end

    def pin(status)
      Plugin::Mastodon::API.get_local_status_id(self, status).next{ |status_id|
        Plugin::Mastodon::API.call(:post, domain, "/api/v1/statuses/#{status_id}/pin", access_token)
      }.next{
        status.pinned = true
      }
    end

    def unpin(status)
      Plugin::Mastodon::API.get_local_status_id(self, status).next{ |status_id|
        Plugin::Mastodon::API.call(:post, domain, "/api/v1/statuses/#{status_id}/unpin", access_token)
      }.next{
        status.pinned = false
      }
    end

    def report_for_spam(statuses, comment)
      Deferred.when(
        Plugin::Mastodon::API.get_local_account_id(self, statuses.first.account),
        Deferred.when(statuses.map { |status| Plugin::Mastodon::API.get_local_status_id(self, status) })
      ).next{ |account_id, spam_ids|
        Plugin::Mastodon::API.call(:post, domain, "/api/v1/reports", access_token,
                     account_id: account_id,
                     status_ids: spam_ids,
                     comment: comment)
      }
    end

    def update_account
      Plugin::Mastodon::API.call(:get, domain, '/api/v1/accounts/verify_credentials', access_token).next{ |resp|
        resp[:acct] = resp[:acct] + '@' + domain
        self.account = Plugin::Mastodon::Account.new(resp.value)
        Plugin.call(:world_modify, self)
      }
    end

    def update_profile(**opts)
      params = {}

      # 以下の2つはupdate_profile*系spellのAPIとしてのパラメータ名とMastodon APIのパラメータ名に違いがある

      # 表示名
      params[:display_name] = opts[:name] if opts[:name]
      # bio
      params[:note] = opts[:biography] if opts[:biography]

      # フォロー承認制
      params[:locked] = opts[:locked] if opts[:locked]
      # botアカウントであることの表明
      params[:bot] = opts[:bot] if opts[:bot]
      if [:privacy, :sensitive, :language].any?{|key| opts[:source] && opts[:source][key] }
        params[:source] = Hash.new
        # デフォルト公開範囲
        params[:source][:privacy] = opts[:source_privacy] if opts[:source_privacy]
        # デフォルトでNSFW
        params[:source][:sensitive] = opts[:source_sensitive] if opts[:source_sensitive]
        # 投稿する言語設定(ISO639-1形式(ex: "ja") or nil(自動検出))
        params[:source][:language] = opts[:source_language] if opts[:source_language]
      end
      # プロフィール補足情報
      if (1..4).any?{|i| opts[:"field_name#{i}"] && opts[:"field_value#{i}"] }
        params[:fields_attributes] = Array.new
        (1..4).each do |i|
          name = opts[:"field_name#{i}"]
          next unless name
          value = opts[:"field_value#{i}"]
          next unless value
          params[:fields_attributes] << { name: name, value: value }
        end
      end
      ds = []
      if opts[:icon]
        if opts[:icon].is_a?(Plugin::Photo::Photo)
          ds << opts[:icon].download.next{|photo| [:avatar, photo] }
        else
          params[:avatar] = opts[:icon]
        end
      end
      if opts[:header]
        if opts[:header].is_a?(Plugin::Photo::Photo)
          ds << opts[:header].download.next{|photo| [:header, photo] }
        else
          params[:header] = opts[:header]
        end
      end
      if ds.empty?
        ds << Delayer::Deferred.new.next{ [:none, nil] }
      end
      Delayer::Deferred.when(ds).next{|vs|
        vs.each do |key, val|
          params[key] = val
        end
        new_account = +Plugin::Mastodon::API.call(:patch, domain, '/api/v1/accounts/update_credentials', access_token, **params)
        self.account = Plugin::Mastodon::Account.new(new_account.value)
        Plugin.call(:world_modify, self)
      }
    end
  end
end