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 = 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 if resp.MIMEType != "text/html" {
41 err = mail.SendAttachment(resp, m.From, u)
42 if err != nil {
43 log.Printf("error sending attachment to: %s: %v\n", m.From, err)
44 } else {
45 log.Printf("sent attachment to %s: %s\n", m.From, resp.MIMEType)
46 }
47 break
48 }
49
50 article, err := reader.Readable(resp.Body, parsedURL)
51 if err == nil {
52 err = mail.SendArticle(&article, m.From, true)
53 if err != nil {
54 log.Printf("error sending mail to: %s: %v\n", m.From, err)
55 } else {
56 log.Printf("sent mail to %s: %s\n", m.From, article.Title)
57 }
58 } else {
59 log.Printf("not readable: %s\n", err)
60 err := mail.SendArticle(&article, m.From, false)
61 if err != nil {
62 log.Printf("error sending mail to: %s: %v\n", m.From, err)
63 }
64 }
65 }
66 w.WriteHeader(204)
67 })
68
69 http.ListenAndServe(":8001", nil)
70}