all repos — navani @ 0d5afcf4ad87e61c3c01306a2f7a802a31a8d1a4

forlater's primary mail processing service

main.go (view raw)

 1package main
 2
 3import (
 4	"encoding/json"
 5	"log"
 6	"net/http"
 7	"net/url"
 8	"os"
 9	"strings"
10
11	"git.icyphox.sh/forlater/navani/mail"
12	"git.icyphox.sh/forlater/navani/reader"
13	"git.icyphox.sh/forlater/navani/reader/twitter"
14	_ "github.com/joho/godotenv"
15)
16
17func main() {
18	http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
19		m := mail.Mail{}
20		json.NewDecoder(r.Body).Decode(&m)
21		body, err := mail.MailBody(m.Parts)
22		log.Printf("recieved webhook: %v\n", m.From)
23		if err != nil {
24			log.Printf("using body as is: %v\n", err)
25			body = mail.StripSignature(m.Body)
26		}
27
28		urls := mail.ExtractURLs(body)
29		if len(urls) == 0 {
30			log.Printf("no urls found")
31		}
32		for _, u := range distinct(urls) {
33			log.Printf("url: %s\n", u)
34			parsedURL, err := url.Parse(u)
35			if err != nil {
36				log.Printf("url parse: %v\n", err)
37			}
38			host := parsedURL.Host
39			switch {
40			case strings.Contains(host, "twitter.com"):
41				creds := twitter.Creds{
42					AccessToken:       os.Getenv("TWITTER_ACCESS_TOKEN"),
43					AccessTokenSecret: os.Getenv("TWITTER_ACCESS_SECRET"),
44					APIKey:            os.Getenv("TWITTER_API_KEY"),
45					APISecret:         os.Getenv("TWITTER_API_SECRET"),
46				}
47
48				client := twitter.GetClient(&creds)
49				tweet, err := twitter.GetTweet(client, u)
50				if err != nil {
51					log.Printf("error getting tweet: %v\n", err)
52				}
53				article := twitter.MakeTweetArticle(tweet, parsedURL)
54				err = mail.SendArticle(article, m.From, true)
55				if err != nil {
56					log.Printf("error sending mail to: %s: %v\n", m.From, err)
57				} else {
58					log.Printf("sent mail to %s: %s\n", m.From, article.Title)
59				}
60			default:
61				resp, err := reader.Fetch(parsedURL.String())
62				if err != nil {
63					log.Printf("reader fetch: %v\n", err)
64				}
65
66				article, err := reader.Readable(resp.Body, parsedURL)
67				if (err == nil) && (resp.MIMEType == "text/html") {
68					err = mail.SendArticle(&article, m.From, true)
69					if err != nil {
70						log.Printf("error sending mail to: %s: %v\n", m.From, err)
71					} else {
72						log.Printf("sent mail to %s: %s\n", m.From, article.Title)
73					}
74				} else {
75					log.Printf("not readable: %s: %s\n", article.URL.String(), resp.MIMEType)
76					err := mail.SendArticle(&article, m.From, false)
77					if err != nil {
78						log.Printf("error sending mail to: %s: %v\n", m.From, err)
79					}
80				}
81			}
82		}
83		w.WriteHeader(204)
84	})
85
86	http.ListenAndServe(":8001", nil)
87}