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 StandardError => e
67 puts "Error in PostDownloader: #{item.post_uri}: #{e.class}: #{e}"
68 end
69 end
70
71 check_missing_items(items)
72 rescue StandardError => e
73 puts "Error in PostDownloader: #{e.class}: #{e}"
74 end
75 end
76
77 def save_post(post_uri, record)
78 did, _, rkey = AT_URI(post_uri)
79
80 text = record.delete('text')
81 created = record.delete('createdAt')
82 record.delete('$type')
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 end
89
90 Post.create(
91 user: author,
92 rkey: rkey,
93 time: Time.parse(created),
94 text: text,
95 data: JSON.generate(record)
96 )
97 end
98
99 def update_item(item, post)
100 item.update!(post: post, post_uri: nil, queue: nil)
101
102 @total_count += 1
103 @oldest_imported = [@oldest_imported, item.time].min
104
105 @report&.update(downloader: { downloaded_posts: @total_count, oldest_date: @oldest_imported })
106 end
107
108 def invalidate_item(item)
109 @total_count += 1
110 @oldest_imported = [@oldest_imported, item.time].min
111
112 @report&.update(downloader: { downloaded_posts: @total_count, oldest_date: @oldest_imported })
113
114 item.destroy
115 end
116
117 def check_missing_items(items)
118 return if items.empty?
119
120 dids = items.map { |x| AT_URI(x.post_uri).repo }.uniq
121 response = @sky.get_request('app.bsky.actor.getProfiles', { actors: dids })
122 active_dids = response['profiles'].map { |x| x['did'] }
123
124 items.each do |item|
125 did = AT_URI(item.post_uri).repo
126 did_obj = DID.new(did)
127
128 if active_dids.include?(did)
129 # account exists but post doesn't, delete the post reference
130 item.destroy
131 else
132 begin
133 status = if @account_status_cache.has_key?(did) # don't retry if status was nil
134 @account_status_cache[did]
135 else
136 @account_status_cache[did] ||= did_obj.account_status
137 end
138
139 case status
140 when :active
141 # account is active but wasn't returned in getProfiles, probably was suspended on the AppView
142 puts "#{item.post_uri}: account #{did} exists on the PDS, account must have been taken down"
143 item.destroy
144 when nil
145 # account was deleted, so all posts were deleted too
146 puts "#{item.post_uri}: account #{did} doesn't exist on the PDS, post must have been deleted"
147 item.destroy
148 else
149 # account is inactive/suspended, but could come back, so leave it for now
150 puts "#{item.post_uri}: account #{did} is inactive: #{status}"
151 end
152 rescue StandardError => e
153 hostname = did_obj.document.pds_host rescue "???"
154 puts "#{item.post_uri}: couldn't check account status for #{did} on #{hostname}: #{e.class}: #{e}"
155
156 # delete reference if the account's PDS is the old bsky.social (so it must have been deleted pre Nov 2023)
157 item.destroy if hostname == 'bsky.social'
158 end
159 end
160
161 if !item.destroyed?
162 item.update!(queue: nil)
163 end
164 end
165 end
166end