~aleteoryx/tclfeed-bsky

ref: f453a88bcab5e6cac39a021958aa6f819a78dd1b tclfeed-bsky/jetstream.tcl -rw-r--r-- 1.7 KiB
f453a88bAleteoryx regex tweaks 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] \; [list set postfix $postfix] \; {
      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 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 -- {\s[Tt]cl(/[Tt]k)?(\.|,|\s)|^[Tt]cl(/[Tt]k)?(,|\s)|\s[Tt]cl(/[Tt]k)?$|\sTk(\.|,|\s)|^Tk(,|\s)|\sTk$|\.tcl|tclsh|tcl-lang|tcltk|tcllib|tklib|tcl\.tk|#tcllang} $text]} {
                set ts [dict get $data commit record createdAt]
                if ![catch {$db eval {INSERT OR FAIL INTO posts (uri, ts) VALUES ($uri, $ts);}}] {
                  ${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
  }
}