~aleteoryx/tclfeed-bsky

ref: 0ad9282cf54a813e893af8092815302543ec55cc tclfeed-bsky/jetstream.tcl -rw-r--r-- 1.7 KiB
0ad9282cAleteoryx a lot. chiefly httpd 30 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
namespace eval ::jetstream {
  variable log [logger::init tclfeed::jetstream]
  proc listen {host db} {
    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 on_ws_$postfix]

    proc ::jetstream::on_ws_$postfix {sock mode data} [concat [list set db $db] \; {
      variable log
      switch -- $mode {
        close {
          # cursed
          [dict get [info frame [info frame]] cmd proc]_close
        }

        text {
          set data [json::json2dict $data]
          if {[dict get $data kind] != "commit"} 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]
              if [regexp -nocase -- {\stcl(/tk)?(,|\s)|^tcl(/tk)?(,|\s)|\stcl(/tk)?$|\stk(,|\s)|^tk(,|\s)|\stk$|\.tcl|tclsh} $text] {
                set ts [dict get $data commit record createdAt]
                if ![catch {$db eval {INSERT INTO posts (uri, ts) VALUES ($uri, $ts) ON CONFLICT FAIL;}}] {
                  ${log}::info "new tclpost! https://bsky.app/profile/[dict get $data did]/post/[dict get $data commit rkey]"
                }
              }
            }
            delete {
              $db eval {DELETE FROM posts WHERE uri = $uri;}
            }
          }
        }
      }
    }]

    ::ws::c::connect $host 443 /subscribe?wantedCollections=app.bsky.feed.post ::jetstream::on_ws_$postfix
  }
}