-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmastodon_platform.rb
More file actions
300 lines (232 loc) · 7.69 KB
/
Copy pathmastodon_platform.rb
File metadata and controls
300 lines (232 loc) · 7.69 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
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
require 'net/http'
require 'json'
require 'uri'
require 'date'
require 'openssl'
class MastodonPlatform
def initialize
@access_token = nil
@account_id = nil
@instance = nil
end
def platform_name
'Mastodon'
end
def authenticate
@instance = ENV['MASTODON_INSTANCE']
@access_token = ENV['MASTODON_ACCESS_TOKEN']
if @instance.nil? || @instance.empty?
print "Enter your Mastodon instance (e.g., mastodon.social): "
@instance = STDIN.gets.chomp
end
if @access_token.nil? || @access_token.empty?
print "Enter your access token: "
@access_token = STDIN.gets.chomp
end
@instance = @instance.gsub(%r{^https?://}, '').chomp('/')
uri = URI("https://#{@instance}/api/v1/accounts/verify_credentials")
http = create_http(uri)
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{@access_token}"
response = http.request(request)
if response.code == '200'
data = JSON.parse(response.body)
@account_id = data['id']
username = data['acct'] || data['username']
puts "✅ Successfully authenticated as #{username}@#{@instance}"
else
puts "❌ Authentication failed: #{response.body}"
exit 1
end
end
def fetch_old_posts(cutoff_date, start_date, exclude_ids)
old_posts = []
puts "🔍 Scanning for posts older than #{cutoff_date}..."
paginate("/api/v1/accounts/#{@account_id}/statuses", exclude_replies: true, exclude_reblogs: true) do |status|
created_at = DateTime.parse(status['created_at'])
break :stop if created_at.to_date <= cutoff_date && start_date && created_at.to_date < start_date
if created_at.to_date <= cutoff_date && !exclude_ids.include?(status['id']) &&
(start_date.nil? || created_at.to_date >= start_date)
old_posts << {
uri: status['id'],
created_at: created_at,
text: (status['content'] || '').gsub(/<[^>]*>/, '').slice(0, 100)
}
end
end
puts
old_posts
end
def fetch_old_replies(cutoff_date, start_date, exclude_ids)
old_replies = []
puts "🔍 Scanning for replies older than #{cutoff_date}..."
paginate("/api/v1/accounts/#{@account_id}/statuses", exclude_reblogs: true) do |status|
created_at = DateTime.parse(status['created_at'])
is_reply = !status['in_reply_to_id'].nil?
next unless is_reply
break :stop if created_at.to_date <= cutoff_date && start_date && created_at.to_date < start_date
if created_at.to_date <= cutoff_date && !exclude_ids.include?(status['id']) &&
(start_date.nil? || created_at.to_date >= start_date)
old_replies << {
uri: status['id'],
created_at: created_at,
text: (status['content'] || '').gsub(/<[^>]*>/, '').slice(0, 100)
}
end
end
puts
old_replies
end
def fetch_old_likes(cutoff_date, start_date, exclude_ids)
old_likes = []
puts "🔍 Scanning for favourites older than #{cutoff_date}..."
paginate("/api/v1/favourites") do |status|
created_at = DateTime.parse(status['created_at'])
if created_at.to_date <= cutoff_date && !exclude_ids.include?(status['id']) &&
(start_date.nil? || created_at.to_date >= start_date)
old_likes << {
uri: status['id'],
created_at: created_at
}
end
end
puts
old_likes
end
def fetch_old_reposts(cutoff_date, start_date, exclude_ids)
old_reposts = []
puts "🔍 Scanning for boosts older than #{cutoff_date}..."
paginate("/api/v1/accounts/#{@account_id}/statuses") do |status|
next unless status['reblog']
created_at = DateTime.parse(status['created_at'])
break :stop if created_at.to_date <= cutoff_date && start_date && created_at.to_date < start_date
if created_at.to_date <= cutoff_date && !exclude_ids.include?(status['id']) &&
(start_date.nil? || created_at.to_date >= start_date)
old_reposts << {
uri: status['id'],
created_at: created_at
}
end
end
puts
old_reposts
end
def fetch_record_by_id(id, collection)
uri = URI("https://#{@instance}/api/v1/statuses/#{id}")
http = create_http(uri)
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{@access_token}"
response = http.request(request)
if response.code == '200'
status = JSON.parse(response.body)
created_at = DateTime.parse(status['created_at'])
result = {
uri: status['id'],
created_at: created_at
}
if status['reblog']
result[:reply] = nil
elsif status['in_reply_to_id']
result[:reply] = status['in_reply_to_id']
result[:text] = (status['content'] || '').gsub(/<[^>]*>/, '').slice(0, 100)
else
result[:text] = (status['content'] || '').gsub(/<[^>]*>/, '').slice(0, 100)
end
result
else
nil
end
rescue => e
nil
end
def collection_for_type(type)
case type
when :post, :reply then 'status'
when :repost then 'reblog'
when :like then 'favourite'
end
end
def delete_post(status_id)
request_with_retry(:delete, "/api/v1/statuses/#{status_id}")
end
def delete_like(status_id)
request_with_retry(:post, "/api/v1/statuses/#{status_id}/unfavourite")
end
def delete_repost(status_id)
request_with_retry(:post, "/api/v1/statuses/#{status_id}/unreblog")
end
def delete_delay
# Mastodon rate limit: 30 deletes per 30 minutes for statuses/unreblog,
# unfavourites fall under the general 300/5min limit.
# Pace conservatively to avoid constant 429s; retry logic handles bursts.
5.0
end
def item_id(item)
item[:uri]
end
private
def request_with_retry(method, path, retries: 5)
retries.times do |attempt|
uri = URI("https://#{@instance}#{path}")
http = create_http(uri)
request = case method
when :delete then Net::HTTP::Delete.new(uri)
when :post then Net::HTTP::Post.new(uri)
end
request['Authorization'] = "Bearer #{@access_token}"
response = http.request(request)
if response.code == '429'
wait = (response['Retry-After'] || 30).to_i
puts "⏳ Rate limited, waiting #{wait}s..."
sleep(wait)
next
end
return response.code == '200'
end
false
end
def paginate(path, params = {})
url = "https://#{@instance}#{path}"
query_params = params.map { |k, v| "#{k}=#{v}" }.join('&')
url += "?#{query_params}" unless query_params.empty?
loop do
uri = URI(url)
http = create_http(uri)
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{@access_token}"
response = http.request(request)
if response.code != '200'
puts "❌ Failed to fetch data: #{response.body}"
break
end
statuses = JSON.parse(response.body)
break if statuses.empty?
stop = false
statuses.each do |status|
result = yield status
if result == :stop
stop = true
break
end
end
break if stop
# Parse Link header for next page
link_header = response['Link']
break unless link_header
next_link = link_header.split(',').find { |l| l.include?('rel="next"') }
break unless next_link
url = next_link.match(/<([^>]+)>/)[1]
print "."
end
end
def create_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.cert_store = OpenSSL::X509::Store.new.tap do |store|
store.set_default_paths
store.flags = OpenSSL::X509::V_FLAG_NO_CHECK_TIME
end
http
end
end