~aleteoryx/tclfeed-bsky

ref: 6cb8a96336f904d4e0cadb74b2b597e0b55c535f tclfeed-bsky/src/jetstream.tcl -rw-r--r-- 1.8 KiB
6cb8a963Aleteoryx marginally better moderation tooling 29 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
  }
}