repos / hub.go.git


Evgenii Akentev  ·  2024-09-02

hub.go

 1package main
 2
 3import (
 4  "slices"
 5  "cmp"
 6  "log"
 7)
 8
 9type Hub struct {
10	clients map[*Client]bool
11  
12  copyrights map[Address]*Copyright
13  clientQuery chan ClientQuery   
14
15  subs *Subscriptions
16  subscribe chan SubMessage
17  unsubscribe chan SubMessage 
18
19  messages chan string
20	register chan *Client
21	unregister chan *Client
22}
23
24func newHub() *Hub {
25	return &Hub{
26  	clients:    make(map[*Client]bool),
27    copyrights: make(map[Address]*Copyright),
28    clientQuery: make(chan ClientQuery),
29
30    subs:    newSubscriptions(),
31    subscribe: make(chan SubMessage),
32    unsubscribe: make(chan SubMessage),
33
34		register:   make(chan *Client),
35		unregister: make(chan *Client),	
36	}
37}
38
39func (h *Hub) run() {
40	for {
41		select {
42    case cq := <-h.clientQuery:
43      switch q := cq.query.(type) {
44      case GetCopyrightsQuery:
45        var copyrights []*Copyright
46        for _, addr := range q {
47          if c, ok := h.copyrights[addr]; ok {
48            copyrights = append(copyrights, c)
49          }
50        }
51        cq.client.hubResponse <- CopyrightsHubResponse(copyrights)
52      case GetCopyrightsByWalletsQuery: 
53        var copyrights []*Copyright
54        for _, cp := range h.copyrights {
55          if (slices.Contains(q, cp.author) || slices.Contains(q, cp.owner) || slices.Contains(q, cp.claim.author)) {
56           copyrights = append(copyrights, cp)
57          }
58        }
59        slices.SortFunc(copyrights, func(a, b *Copyright) int { return cmp.Compare(a.initTxLt, b.initTxLt)})
60        cq.client.hubResponse <- CopyrightsHubResponse(copyrights)
61    case GetCopyrightStatesQuery:
62      var copyrightStates = make(map[Address]*CopyrightState)
63      for _, addr := range q {
64        if cp, ok := h.copyrights[addr]; ok {
65          copyrightStates[addr] = cp.mkState()
66        }
67      }
68      cq.client.hubResponse <- CopyrightStatesHubResponse(copyrightStates)
69    }
70    case s := <-h.subscribe:
71      log.Println("%V", h.subs)
72      h.subs.subscribe(s.addressType, s.address, s.client)
73      log.Println("%V", h.subs)
74    case s := <-h.unsubscribe:
75      h.subs.unsubscribe(s.addressType, s.address, s.client)
76		case client := <-h.register:
77			h.clients[client] = true
78		case client := <-h.unregister:
79			if _, ok := h.clients[client]; ok {
80				delete(h.clients, client)
81			}
82		}
83	}
84}