Don't forget to lycansubscribe
1require 'didkit'
2require 'minisky'
3
4require_relative 'at_uri'
5require_relative 'models/post'
6require_relative 'models/user'
7
8class PostDownloader
9 attr_accessor :report, :stop_when_empty
10
11 def initialize
12 @sky = Minisky.new(ENV['APPVIEW_HOST'] || 'public.api.bsky.app', nil)
13
14 @total_count = 0
15 @oldest_imported = Time.now
16 @account_status_cache = {}
17 end
18
19 def import_from_queue(queue)
20 loop do
21 items = queue.pop_batch
22
23 if items.empty?
24 if @stop_when_empty
25 return
26 else
27 sleep 1
28 next
29 end
30 end
31
32 @report&.update(queue: { length: queue.length })
33
34 process_items(items)
35 end
36 end
37
38 def process_items(items)
39 existing_posts = Post.where(rkey: items.map { |x| AT_URI(x.post_uri).rkey }).to_a
40
41 items.dup.each do |item|
42 if post = existing_posts.detect { |post| post.at_uri == item.post_uri }
43 update_item(item, post)
44 items.delete(item)
45 end
46 end
47
48 return if items.empty?
49
50 begin
51 response = @sky.get_request('app.bsky.feed.getPosts', { uris: items.map(&:post_uri).uniq })
52
53 response['posts'].each do |data|
54 begin
55 item = items.detect { |x| x.post_uri == data['uri'] }
56 items.delete(item)
57
58 post = save_post(data['uri'], data['record'])
59
60 if post.valid?
61 update_item(item, post)
62 else
63 puts "Invalid post #{item.post_uri}: #{post.errors.full_messages.join("; ")}"
64 invalidate_item(item)
65 end
66 rescue InvalidRecordError => e
67 puts "Error in PostDownloader: #{item.post_uri}: #{e.class}: #{e}"
68
69 item = items.detect { |x| x.post_uri == data['uri'] }
70 item.update!(queue: nil)
71 items.delete(item)
72 end
73 end
74
75 check_missing_items(items)
76 rescue StandardError => e
77 puts "Error in PostDownloader: #{e.class}: #{e}"
78 end
79 end
80
81 def save_post(post_uri, record)
82 did, _, rkey = AT_URI(post_uri)
83
84 author = User.find_or_create_by!(did: did)
85
86 if post = Post.find_by(user: author, rkey: rkey)
87 return post
88 else
89 post = build_post(author, rkey, record)
90 post.save
91 post
92 end
93 end
94
95 def build_post(author, rkey, record)
96 text = record.delete('text')
97 created = record.delete('createdAt')
98
99 record.delete('$type')
100
101 Post.new(
102 user: author,
103 rkey: rkey,
104 time: Time.parse(created),
105 text: text,
106 data: JSON.generate(record)
107 )
108 rescue StandardError
109 raise InvalidRecordError
110 end
111
112 def update_item(item, post)
113 item.update!(post: post, post_uri: nil, queue: nil)
114
115 @total_count += 1
116 @oldest_imported = [@oldest_imported, item.time].min
117
118 @report&.update(downloader: { downloaded_posts: @total_count, oldest_date: @oldest_imported })
119 end
120
121 def invalidate_item(item)
122 @total_count += 1
123 @oldest_imported = [@oldest_imported, item.time].min
124
125 @report&.update(downloader: { downloaded_posts: @total_count, oldest_date: @oldest_imported })
126
127 item.destroy
128 end
129
130 def check_missing_items(items)
131 return if items.empty?
132
133 dids = items.map { |x| AT_URI(x.post_uri).repo }.uniq
134 response = @sky.get_request('app.bsky.actor.getProfiles', { actors: dids })
135 active_dids = response['profiles'].map { |x| x['did'] }
136
137 items.each do |item|
138 did = AT_URI(item.post_uri).repo
139 did_obj = DID.new(did)
140
141 if active_dids.include?(did)
142 # account exists but post doesn't, delete the post reference
143 item.destroy
144 else
145 begin
146 status = if @account_status_cache.has_key?(did) # don't retry if status was nil
147 @account_status_cache[did]
148 else
149 @account_status_cache[did] ||= did_obj.account_status
150 end
151
152 case status
153 when :active
154 # account is active but wasn't returned in getProfiles, probably was suspended on the AppView
155 puts "#{item.post_uri}: account #{did} exists on the PDS, account must have been taken down"
156 item.destroy
157 when nil
158 # account was deleted, so all posts were deleted too
159 puts "#{item.post_uri}: account #{did} doesn't exist on the PDS, post must have been deleted"
160 item.destroy
161 else
162 # account is inactive/suspended, but could come back, so leave it for now
163 puts "#{item.post_uri}: account #{did} is inactive: #{status}"
164 end
165 rescue StandardError => e
166 hostname = did_obj.document.pds_host rescue "???"
167 puts "#{item.post_uri}: couldn't check account status for #{did} on #{hostname}: #{e.class}: #{e}"
168
169 # delete reference if the account's PDS is the old bsky.social (so it must have been deleted pre Nov 2023)
170 item.destroy if hostname == 'bsky.social'
171 end
172 end
173
174 if !item.destroyed?
175 item.update!(queue: nil)
176 end
177 end
178 end
179end