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