test up in subscribe

mostly working
This commit is contained in:
Karmanyaah Malhotra 2021-12-30 00:51:04 -06:00
parent 85126a4403
commit 10e0b23a51
4 changed files with 84 additions and 89 deletions

View file

@ -4,9 +4,9 @@ import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"github.com/urfave/cli/v2"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"heckel.io/ntfy/client"
@ -16,11 +16,11 @@ import (
"unifiedpush.org/go/np2p_dbus/utils"
)
type store struct {
storage.Storage
type Store struct {
*storage.Storage
}
func (s store) GetAllPubTokens() string {
func (s Store) GetAllPubTokens() string {
var conns []storage.Connection
result := s.DB().Find(&conns)
if result.Error != nil {
@ -47,71 +47,22 @@ func (kv KVStore) Set(db *gorm.DB) error {
return db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&kv).Error
}
func (s store) SetLastMessage(id string) error {
return KVStore{"device-id", id}.Set(s.DB())
func (s Store) SetLastMessage(id int64) error {
return KVStore{"device-id", fmt.Sprintf("%d", id)}.Set(s.DB())
}
func (s store) GetLastMessage() string {
func (s Store) GetLastMessage() int64 {
answer := KVStore{Key: "device-id"}
if err := answer.Get(s.DB()); err != nil {
//log or fatal??
return "100"
return 100
}
return answer.Value
}
var cmdDistribute = &cli.Command{
Name: "distribute",
Aliases: []string{"dist"},
Usage: "Start the UnifiedPush distributor",
UsageText: "ntfy distribute",
Action: execDistribute,
Flags: []cli.Flag{
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Usage: "client config file"},
&cli.BoolFlag{Name: "verbose", Aliases: []string{"v"}, Usage: "print verbose output"},
},
Description: `TODO`,
}
func execDistribute(c *cli.Context) error {
// this channel will resubscribe to the server whenever an app is added or removed
resubscribe := make(chan struct{})
// Read config
conf, err := loadConfig(c)
if err != nil {
return err
}
distrib := newDistributor(conf, resubscribe)
cl := client.New(conf)
go distrib.handleEndpointSettingsChanges()
go distrib.handleDistribution(cl)
var sub string
// everytime resubscribe is triggered, this loop will unsubscribe from the old subscription
// and resubscribe to one with the new list of topics/applications
// On the first run, 'sub' is empty but cl.Unsubscribe doesn't care.
// the first message to resubscribe (trigerring the first loop run) is sent by handleEndpointSettingsChanges
for _ = range resubscribe {
cl.Unsubscribe(sub)
fmt.Println("Subscribing...")
subscribeTopics := distrib.st.GetAllPubTokens()
if subscribeTopics == "" {
continue
}
sub = cl.Subscribe(subscribeTopics, client.WithSince(distrib.st.GetLastMessage()))
}
return nil
time, _ := strconv.Atoi(answer.Value)
return int64(time)
}
// creates a new distributor object with an initialized storage and dbus
func newDistributor(conf *client.Config, resub chan struct{}) (d distributor) {
func newDistributor(conf *client.Config) (d *distributor) {
st, err := storage.InitStorage(utils.StoragePath("ntfy.db"))
st.DB().AutoMigrate(KVStore{}) //todo move to proper function
if err != nil {
@ -119,7 +70,7 @@ func newDistributor(conf *client.Config, resub chan struct{}) (d distributor) {
}
dbus := distributor_tools.NewDBus("org.unifiedpush.Distributor.ntfy")
d = distributor{dbus, store{*st}, conf, resub}
d = &distributor{dbus, Store{st}, conf, make(chan struct{})}
err = dbus.StartHandling(d)
fmt.Println("DBUS HANDLING")
if err != nil {
@ -131,7 +82,7 @@ func newDistributor(conf *client.Config, resub chan struct{}) (d distributor) {
type distributor struct {
dbus *distributor_tools.DBus
st store
st Store
conf *client.Config
resub chan struct{}
}
@ -154,17 +105,6 @@ func (d distributor) handleEndpointSettingsChanges() {
d.resub <- struct{}{}
}
// handleDistribution listens to the nfty client and forwards messages to the right dbus app based on the db.
func (d distributor) handleDistribution(cl *client.Client) {
for i := range cl.Messages {
conn := d.st.GetConnectionbyPublic(i.Topic)
if conn != nil {
_ = d.dbus.NewConnector(conn.AppID).Message(conn.AppToken, i.Message, "")
}
d.st.SetLastMessage(fmt.Sprintf("%d", i.Time))
}
}
// Register handles an app's call to register for a new connection
// this creates a new connection in the db and triggers a resubscribe with that id
// then it returns the endpoint with that new token to dbus
@ -173,7 +113,9 @@ func (d distributor) Register(appName, token string) (string, string, error) {
conn := d.st.NewConnection(appName, token, d.fillInURL("<token>"))
fmt.Println("registered", conn)
if conn != nil {
fmt.Println("F1")
d.resub <- struct{}{}
fmt.Println("F2")
return d.fillInURL(conn.PublicToken), "", nil
}
//np2p doesn't have a situation for refuse
@ -188,6 +130,7 @@ func (d distributor) Unregister(token string) {
if err != nil {
//?????
return
}
_ = d.dbus.NewConnector(deletedConn.AppID).Unregistered(deletedConn.AppToken)