You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.4 KiB

  1. package net
  2. import (
  3. "os"
  4. "fmt"
  5. "encoding/json"
  6. shell "github.com/ipfs/go-ipfs-api"
  7. "github.com/vocdoni/go-dvote/batch"
  8. "github.com/vocdoni/go-dvote/types"
  9. )
  10. type PubSubHandle struct {
  11. topic string
  12. subscription *shell.PubSubSubscription
  13. }
  14. func PsSubscribe(topic string) *shell.PubSubSubscription {
  15. sh := shell.NewShell("localhost:5001")
  16. sub, err := sh.PubSubSubscribe(topic)
  17. if err != nil {
  18. fmt.Fprintf(os.Stderr, "error: %s", err)
  19. os.Exit(1)
  20. }
  21. return sub
  22. }
  23. func PsPublish(topic, data string) error {
  24. sh := shell.NewShell("localhost:5001")
  25. err := sh.PubSubPublish(topic, data)
  26. if err != nil {
  27. return err
  28. }
  29. return nil
  30. }
  31. func (p *PubSubHandle) Init(topic string) error {
  32. p.topic = topic
  33. p.subscription = PsSubscribe(p.topic)
  34. return nil
  35. }
  36. func (p *PubSubHandle) Listen() error {
  37. var msg *shell.Message
  38. var err error
  39. for {
  40. msg, err = p.subscription.Next()
  41. if err != nil {
  42. fmt.Fprintf(os.Stderr, "recieve error: %s", err)
  43. return err
  44. }
  45. payload := msg.Data
  46. var e types.Envelope
  47. var b types.Ballot
  48. err = json.Unmarshal(payload, &e)
  49. if err != nil {
  50. return err
  51. }
  52. err = json.Unmarshal(e.Ballot, &b)
  53. if err != nil {
  54. return err
  55. }
  56. err = batch.Add(b)
  57. if err != nil {
  58. return err
  59. }
  60. fmt.Println("Got > " + string(payload))
  61. }
  62. }
  63. func (p *PubSubHandle) Send(data string) error {
  64. return PsPublish(p.topic, data)
  65. }