~gjabell/mfn

ref: fd0ff9537d1966e674a35e898687396355ca8be1 mfn/main.go -rw-r--r-- 4.1 KiB
fd0ff953Galen Abell Rename to mfn and refactor config 1 year, 7 months ago
                                                                                
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"git.sr.ht/~sircmpwn/getopt"

	mf "miniflux.app/client"
)

var version = "0.1.0"
var webhookTemplate *template.Template

func loadLastEntry(filepath string) (int64, error) {
	bytes, err := ioutil.ReadFile(filepath)
	if err != nil {
		if os.IsNotExist(err) {
			// no last entry
			return -1, nil
		}
		return -1, err
	}

	str := strings.TrimSpace(string(bytes))
	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return -1, err
	}

	return id, nil
}

func saveLastEntry(filepath string, id int64) error {
	return ioutil.WriteFile(filepath, []byte(strconv.FormatInt(id, 10)), 0644)
}

func sendWebhook(entry *mf.Entry, webhookURL string) error {
	var text bytes.Buffer
	if err := webhookTemplate.Execute(&text, entry); err != nil {
		return err
	}

	body := map[string]string{"text": text.String(), "format": "html", "displayName": "Miniflux", "avatarUrl": "https://miniflux.app/favicon.ico"}
	jsonVal, err := json.Marshal(body)
	if err != nil {
		return err
	}

	res, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonVal))
	if err != nil {
		return err
	}
	resBytes, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil
	}
	log.Printf("Webhook response: %s", string(resBytes))

	return nil
}

func testWebhook(webhookURL string) error {
	e := &mf.Entry{
		ID:         0,
		UserID:     0,
		FeedID:     0,
		Status:     "unread",
		Hash:       "deadbeef",
		Title:      "Test Entry",
		URL:        "https://miniflux.app",
		Date:       time.Now(),
		Content:    "This is a test miniflux entry",
		Author:     "Author",
		Starred:    false,
		Enclosures: make([]*mf.Enclosure, 0),
		Feed:       nil,
	}

	return sendWebhook(e, webhookURL)
}

func main() {
	showHelp := getopt.Bool("h", false, "show usage")
	webhookTest := getopt.Bool("t", false, "test the webhook endpoint")
	showVersion := getopt.Bool("v", false, "show version")
	var configPath string
	getopt.StringVar(&configPath, "c", "", "configuration file path")

	err := getopt.Parse()
	if err != nil {
		log.Fatalf("Failed to parse args: %s", err)
	}

	if *showHelp {
		fmt.Println("Usage: mfn [-v] [-t] -c config")
		os.Exit(0)
	}

	if *showVersion {
		fmt.Printf("mfn %s\n", version)
		os.Exit(0)
	}

	if configPath == "" {
		log.Fatal("You must specify a config location")
	}

	conf, err := loadConfig(configPath)
	if err != nil {
		log.Fatalf("Failed to load config: %s\n", err)
	}
	webhookTemplate = conf.WebhookTemplate

	if *webhookTest {
		log.Println("Sending test webhook...")
		if err := testWebhook(conf.WebhookURL); err != nil {
			log.Fatalf("Test webhook failed: %s\n", err)
		}
		os.Exit(0)
	}

	if err := execNotifications(conf); err != nil {
		log.Fatal(err)
	}
}

func execNotifications(conf *config) error {
	client := mf.New(conf.Server, conf.Username, conf.Password)

	lastEntry, err := loadLastEntry(conf.DbPath)
	if err != nil {
		return fmt.Errorf("failed to load last entry: %s", err)
	}

	var notify bool
	filter := &mf.Filter{Order: "id"}
	if lastEntry == -1 {
		// this is the first run, since we don't have a last entry
		// in this case, just request the single most recent entry
		// this will be the entry with the largest ID
		filter.Limit = 1
		filter.Direction = "desc"
		// don't send notifications on the first run
		notify = false
	} else {
		// if we already have entries, request all entries since the
		// last entry ID
		filter.Limit = 0
		filter.Direction = "asc"
		filter.AfterEntryID = lastEntry
		notify = true
	}

	newEntriesSet, err := client.Entries(filter)
	if err != nil {
		return fmt.Errorf("failed to fetch entries: %s", err)
	}

	newEntries := newEntriesSet.Entries
	for _, e := range newEntries {
		log.Printf("New entry: %d\n", e.ID)

		if e.ID > lastEntry {
			lastEntry = e.ID
		}

		if !notify {
			continue
		}

		if err := sendWebhook(e, conf.WebhookURL); err != nil {
			log.Printf("Failed to send webhook: %s\n", err)
		}
	}
	log.Printf("Saving new last entry: %d\n", lastEntry)
	if err := saveLastEntry(conf.DbPath, lastEntry); err != nil {
		return fmt.Errorf("failed to save new entries: %s", err)
	}

	return nil
}