Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ var (
errFileTooLarge = errors.New("File is too large.")
)

// OnPrinterUpdate, if set, is called after a successful connect so the caller
// can persist the printer's (refreshed) token to disk. Set by main().
var OnPrinterUpdate func(*Printer)

type Payload struct {
File io.Reader
Name string
Expand Down Expand Up @@ -126,6 +130,12 @@ func (c *connector) Upload(printer *Printer, payload *Payload) error {
}
defer h.Disconnect()

// Persist the (possibly refreshed) token so it survives restarts,
// including an unclean exit that skips the shutdown defer.
if OnPrinterUpdate != nil {
OnPrinterUpdate(printer)
}

if payload.Size > FILE_SIZE_MAX {
return errFileTooLarge
}
Expand Down
15 changes: 13 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ func main() {

var printer *Printer
ls := NewLocalStorage(KnownHosts)
// Persist the token to known hosts as soon as it is (re)obtained on connect,
// so it survives restarts even on an unclean exit (the shutdown defer below
// only runs on a graceful exit).
OnPrinterUpdate = func(p *Printer) {
if p == nil {
return
}
ls.Add(p)
_ = ls.Save()
}
defer func() {
if printer != nil {
// update printer's token
Expand Down Expand Up @@ -140,8 +150,9 @@ func main() {
printer = printers[0]
}
} else {
// directly to printer using ip/hostname
printer = &Printer{IP: Host}
// directly to printer using ip/hostname; keep an ID so the token gets
// persisted (ls.Add skips ID-less printers)
printer = &Printer{IP: Host, ID: Host}
}
}

Expand Down