-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (88 loc) · 1.67 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"log"
"os"
"os/signal"
"os/user"
"path/filepath"
"sync"
"time"
"github.com/motemen/go-pocket/api"
)
var configDir string
var k2pdfopt string
func init() {
usr, err := user.Current()
if err != nil {
panic(err)
}
configDir = filepath.Join(usr.HomeDir, ".config", "if-pocket-then-kindle")
err = os.MkdirAll(configDir, 0777)
if err != nil {
panic(err)
}
k2pdfopt = "k2pdfopt"
}
func main() {
bot := newBot()
bot.run()
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
<-ch
bot.shutdown()
}
type Bot struct {
waitGroup sync.WaitGroup
stop chan struct{}
}
func newBot() *Bot {
return &Bot{
stop: make(chan struct{}),
}
}
func (bot *Bot) run() {
log.Println("Running...")
consumerKey := getConsumerKey()
accessToken, err := restoreAccessToken(consumerKey)
if err != nil {
panic(err)
}
client := api.NewClient(consumerKey, accessToken.AccessToken)
mail, err := restoreMailSettings()
if err != nil {
panic(err)
}
since := time.Now().Unix()
timeout := time.Duration(time.Second * 10)
for {
select {
case <-bot.stop:
return
case <-time.After(timeout):
if items, err := commandList(client, since); err != nil {
log.Println(err)
} else {
bot.waitGroup.Add(1)
go func() {
defer bot.waitGroup.Done()
bot.handle(items, mail)
}()
}
since = time.Now().Unix()
}
}
}
func (bot *Bot) handle(items []api.Item, mail *Mail) {
for _, item := range items {
fp := mkdir(item)
download(fp, item)
converted := convert(fp, item)
if err := sendToKindle(mail, converted); err != nil {
log.Println(err)
}
}
}
func (bot *Bot) shutdown() {
close(bot.stop)
bot.waitGroup.Wait()
}