2021-11-01 10:01:21 +01:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"ewintr.nl/gte/cmd/cli/format"
|
|
|
|
"ewintr.nl/gte/internal/configuration"
|
|
|
|
"ewintr.nl/gte/internal/process"
|
|
|
|
"ewintr.nl/gte/internal/storage"
|
|
|
|
"ewintr.nl/gte/pkg/msend"
|
|
|
|
"ewintr.nl/gte/pkg/mstore"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Sync struct {
|
|
|
|
fetcher *process.Fetch
|
|
|
|
sender *process.Send
|
|
|
|
fetchInterval time.Duration
|
|
|
|
fetchLatest time.Time
|
2022-10-25 15:59:09 +02:00
|
|
|
dispInterval time.Duration
|
|
|
|
dispLatest time.Time
|
2021-11-01 10:01:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewSync(conf *configuration.Configuration) (*Sync, error) {
|
|
|
|
local, err := storage.NewSqlite(conf.Sqlite())
|
|
|
|
if err != nil {
|
|
|
|
return &Sync{}, err
|
|
|
|
}
|
|
|
|
remote := storage.NewRemoteRepository(mstore.NewIMAP(conf.IMAP()))
|
|
|
|
disp := storage.NewDispatcher(msend.NewSSLSMTP(conf.SMTP()))
|
|
|
|
|
2022-10-25 15:59:09 +02:00
|
|
|
fetchLatest, dispLatest, err := local.LatestSyncs()
|
2021-11-01 10:01:21 +01:00
|
|
|
if err != nil {
|
|
|
|
return &Sync{}, err
|
|
|
|
}
|
|
|
|
fetchInterval := 15 * time.Minute // not yet configurable
|
2022-10-25 15:59:09 +02:00
|
|
|
dispInterval := 2 * time.Minute
|
2021-11-01 10:01:21 +01:00
|
|
|
|
|
|
|
return &Sync{
|
|
|
|
fetcher: process.NewFetch(remote, local),
|
|
|
|
sender: process.NewSend(local, disp),
|
|
|
|
fetchInterval: fetchInterval,
|
|
|
|
fetchLatest: fetchLatest,
|
2022-10-25 15:59:09 +02:00
|
|
|
dispInterval: dispInterval,
|
|
|
|
dispLatest: dispLatest,
|
2021-11-01 10:01:21 +01:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Sync) Do() string {
|
|
|
|
countSend, err := s.sender.Process()
|
|
|
|
if err != nil {
|
|
|
|
return format.FormatError(err)
|
|
|
|
}
|
2022-10-25 15:59:09 +02:00
|
|
|
if countSend > 0 {
|
|
|
|
return fmt.Sprintf("sent %d tasks, not fetching yet\n", countSend)
|
|
|
|
}
|
|
|
|
|
|
|
|
if time.Now().Before(s.dispLatest.Add(s.dispInterval)) {
|
|
|
|
return "sent 0 tasks, send interval has not passed yet\n"
|
|
|
|
}
|
2021-11-01 10:01:21 +01:00
|
|
|
|
|
|
|
if time.Now().Before(s.fetchLatest.Add(s.fetchInterval)) {
|
2022-10-25 15:59:09 +02:00
|
|
|
return "sent 0 tasks, fetch interval has not passed yet\n"
|
2021-11-01 10:01:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fResult, err := s.fetcher.Process()
|
|
|
|
if err != nil {
|
|
|
|
return format.FormatError(err)
|
|
|
|
}
|
|
|
|
|
2022-10-25 15:59:09 +02:00
|
|
|
return fmt.Sprintf("fetched %d tasks\n", fResult.Count)
|
2021-11-01 10:01:21 +01:00
|
|
|
}
|