Class: Nostrb::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/nostrb/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relay_url, sid: nil) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
# File 'lib/nostrb/client.rb', line 11

def initialize(relay_url, sid: nil)
  @url = relay_url
  @endpoint = Async::HTTP::Endpoint.parse(@url)
  @sid = sid.nil? ? Source.random_sid : sid
end

Instance Attribute Details

#endpointObject (readonly)

Returns the value of attribute endpoint.



9
10
11
# File 'lib/nostrb/client.rb', line 9

def endpoint
  @endpoint
end

#sidObject (readonly)

Returns the value of attribute sid.



9
10
11
# File 'lib/nostrb/client.rb', line 9

def sid
  @sid
end

#urlObject (readonly)

Returns the value of attribute url.



9
10
11
# File 'lib/nostrb/client.rb', line 9

def url
  @url
end

Instance Method Details

#closeObject



66
67
68
69
70
71
72
73
# File 'lib/nostrb/client.rb', line 66

def close
  case single(Nostrb::Source.close(@sid))
  in ['CLOSED', String => sid, String => msg]
    log "sid mismatch: #{sid}" unless sid == @sid
    log msg unless msg.empty?
    true
  end
end

#log(msg) ⇒ Object



17
18
19
# File 'lib/nostrb/client.rb', line 17

def log msg
  warn msg
end

#publish(signed_event) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/nostrb/client.rb', line 34

def publish(signed_event)
  case single(Nostrb::Source.publish(signed_event))
  in ['OK', String => event_id, ok, String => msg]
    log "id mismatch: #{event_id}" unless event_id == signed_event.id
    log msg unless ok
    ok
  in ['NOTICE', String => msg]
    log msg
  end
end

#single(req) ⇒ Object

open, send req, get response, return response



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/nostrb/client.rb', line 22

def single(req)
  Sync do
    Async::WebSocket::Client.connect(@endpoint) do |conn|
      conn.write(Nostrb.json(req))
      conn.flush
      resp = conn.read
      conn.shutdown
      Nostrb.parse(resp.buffer)
    end
  end
end

#subscribe(*filters, &blk) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/nostrb/client.rb', line 45

def subscribe(*filters, &blk)
  Sync do
    Async::WebSocket::Client.connect(@endpoint) do |conn|
      conn.write(Nostrb.json(Nostrb::Source.subscribe(@sid, *filters)))
      conn.flush
      eose = false
      while !eose and resp = conn.read
        case Nostrb.parse(resp.buffer)
        in ['EVENT', String => sid, Hash => event]
          log "sid mismatch: #{sid}" unless sid == @sid
          yield event
        in ['EOSE', String => sid]
          log "sid mismatch: #{sid}" unless sid == @sid
          eose = true
        end
      end
      conn.shutdown
    end
  end
end