all repos — navani @ 30df9bfd236b6663e10ef9feaf0a38355e7b896b

forlater's primary mail processing service

main.go (view raw)

 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"log"
 7	"net/http"
 8	"net/url"
 9
10	"git.icyphox.sh/forlater/navani/mail"
11	"git.icyphox.sh/forlater/navani/reader"
12)
13
14func main() {
15	http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
16		m := mail.Mail{}
17		json.NewDecoder(r.Body).Decode(&m)
18		body, err := mail.MailBody(m.Parts)
19		log.Printf("recieved webhook: %v\n", m)
20		if err != nil {
21			log.Println(err)
22		}
23
24		for _, u := range distinct(mail.ExtractURLs(body)) {
25			parsedURL, err := url.Parse(u)
26			if err != nil {
27				log.Printf("url parse: %s\n", err)
28			}
29
30			f, err := reader.Fetch(parsedURL.String())
31			if err != nil {
32				log.Printf("reader fetch: %s\n", err)
33			}
34
35			article, err := reader.Readable(f, parsedURL)
36			if err == nil {
37				fmt.Println("here")
38				err = mail.SendArticle(&article, m.From, true)
39				if err != nil {
40					log.Printf("error sending mail to: %s: %v\n", m.From, err)
41				} else {
42					log.Printf("sent mail to %s: %s\n", m.From, article.Title)
43				}
44			} else {
45				log.Printf("not readable: %s\n", err)
46				err := mail.SendArticle(&article, m.From, false)
47				if err != nil {
48					log.Printf("error sending mail to: %s: %v\n", m.From, err)
49				}
50			}
51		}
52		w.WriteHeader(204)
53	})
54
55	http.ListenAndServe(":8001", nil)
56}