Skip to content

plc_stream.rb

Example: stream all new operations from the plc.directory's websocket.

An operation is someone making a change to their DID document - it's generally either a change to assigned handle, or change to assigned PDS hostname. This kind of information is useful if you want to track the handle or PDS info of all accounts on the network for some statistical purposes.

rb
require 'didkit'
require 'json'
require 'skyfall'

class PLCStream < Skyfall::Stream
  def initialize
    super('plc.directory')
  end

  def handle_message(msg)
    if @handlers[:message]
      op = parse_operation(msg.data)
      @handlers[:message].call(op)
    end
  end

  def parse_operation(data)
    json = JSON.parse(data)
    return nil if json['type'] != 'sequenced_op'

    DIDKit::PLCOperation.new(json)
  end

  def build_websocket_url
    @root_url + "/export/stream"
  end
end

plc = PLCStream.new
plc.on_connecting { |u| puts "Connecting to #{u}..." }
plc.on_connect { puts "Connected ✓" }
plc.on_disconnect { puts "Disconnected." }
plc.on_error { |e| puts "Error: #{e.class} #{e.message}" }

plc.on_message do |op|
  puts "#{op.seq} [#{op.created_at}]: #{op.did} -> #{op.handles.first} (@ #{op.pds_host})"
end

# close the connection cleanly on Ctrl+C
trap("SIGINT") { puts; plc.disconnect }

plc.connect