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