namespace eval ::jetstream {
variable log [logger::init tclfeed::jetstream]
proc listen {host algos} {
variable log
${log}::info "listening to jetstream on wss://$host/subscribe"
set postfix [sha1::sha1 -hex -- $host]
proc ::jetstream::on_ws_${postfix}_close {} [
list ::ws::c::connect $host 443 \
/subscribe?wantedCollections=app.bsky.feed.post ::jetstream::on_ws_$postfix]
proc ::jetstream::on_ws_$postfix {sock mode data} [concat [list set postfix $postfix] \; [list set algos $algos] \; {
variable log
switch -- $mode {
close {
# cursed
::jetstream::on_ws_${postfix}_close
}
text {
set data [json::json2dict $data]
if {[dict get $data kind] != "commit"} return
set did [dict get $data did]
if [db eval {SELECT count(*) FROM blocked_repos WHERE repo = :did}] return
set uri at://[dict get $data did]/[dict get $data commit collection]/[dict get $data commit rkey]
switch -- [dict get $data commit operation] {
create {
set text [dict get $data commit record text]
foreach algo $algos {
if {[set ord [::algos::${algo}::intake $uri $text $data]] != {}} {
if ![catch {db eval "INSERT OR FAIL INTO $algo (uri, ord) VALUES (:uri, :ord);"}] {
${log}::info "new post for feed \"$algo\"! https://bsky.app/profile/[dict get $data did]/post/[dict get $data commit rkey]"
}
}
}
}
delete {
foreach algo $algos {
db eval "DELETE FROM $algo WHERE uri = :uri;"
}
}
}
}
}
}]
::ws::c::connect $host 443 /subscribe?wantedCollections=app.bsky.feed.post ::jetstream::on_ws_$postfix
}
}