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