aboutsummaryrefslogtreecommitdiff
path: root/keep.go
blob: 109ff5d8d500f69da84c02acb891a942bb440dda (plain)
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main

import (
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"os/user"
	"path"
	"strings"
	"syscall"
	"time"

	"github.com/bwmarrin/discordgo"
	"golang.org/x/net/publicsuffix"
	"keep/normalize"
)

type Config struct {
	Token   string   `json:"token"`
	Verbose bool     `json:"verbose"`
	Ignore  []string `json:"ignore"`
	Host    string   `json:"host"`
	Port    string   `json:"port"`
}

type Message struct {
	URL     string
	Author  string
	Guild   string
	Channel string
}

type SqliteDB struct {
	db *sql.DB
}

var (
	messageChan chan *Message
	config      Config
)

func main() {

	// Directory (default ~/.keep) containing configuration and DB cache
	user, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	var keepDir string
	flag.StringVar(&keepDir, "path", path.Join(user.HomeDir, ".keep"),
		"path to data directory")
	flag.Parse()

	// See ./keep.json for set of supported parameters/values
	configPath := path.Join(keepDir, "keep.json")
	conf, err := ioutil.ReadFile(configPath)
	if err != nil {
		log.Fatal(err)
	}
	err = json.Unmarshal([]byte(conf), &config)
	if err != nil {
		log.Fatal(err)
	}

	// Create and initialize URL cache database
	sqlSqliteDB := initDB(path.Join(keepDir, "keep.db"))
	db := &SqliteDB{db: sqlSqliteDB}

	// Channel for passing URLs to the archive goroutine for archival
	messageChan = make(chan *Message, 25)
	go archiver(db)

	// Start HTTP server
	http.HandleFunc("/", db.IndexHandler)
	log.Printf("Listening on %v port %v (http://%v:%v/)\n", config.Host,
		config.Port, config.Host, config.Port)
	go http.ListenAndServe(fmt.Sprintf("%s:%s", config.Host, config.Port), nil)

	// Create a new Discord session using provided credentials
	dg, err := discordgo.New(config.Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	// Make our client look like Firefox since we're authenticating with
	// user/pass credentials (self bot)
	dg.UserAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0 "

	// Register the messageCreate func as a callback for MessageCreate events
	dg.AddHandler(messageCreate)

	// We only care about receiving message events
	dg.Identify.Intents = discordgo.IntentsGuildMessages

	// Open a websocket connection to Discord and begin listening
	err = dg.Open()
	if err != nil {
		fmt.Println("error opening connection,", err)
		return
	}

	// Wait here until CTRL-C or other term signal is received
	sc := make(chan os.Signal, 1)
	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
	<-sc

	// Cleanly close down the Discord session
	dg.Close()
}

// archiver is intended to be run in its own goroutine, receiving URLs from main
// over a shared channel for processing
func archiver(db *SqliteDB) {

	// Each iteration removes and processes one url from the channel
	for {

		// Blocks until URL is received
		message := <-messageChan

		// Skip if we've already seen URL (cached)
		cached, status_code := db.IsCached(message.URL)
		if cached {
			log.Println("SEEN", status_code, message.URL)
			continue
		}

		// Skip if the Internet Archive already has a copy available
		archived, status_code := isArchived(message.URL)
		if archived && status_code == http.StatusOK {
			db.AddArchived(message, status_code)
			log.Println("SKIP", status_code, message.URL)
			continue
		}

		// Archive, URL is not present in cache or IA
		status_code = archive(message.URL)
		db.AddArchived(message, status_code)
		log.Println("SAVE", status_code, message.URL)

		// Limit requests to Wayback API to 15-second intervals
		time.Sleep(15 * time.Second)
	}
}

// messageCreate be called (due to AddHandler above) every time a new message is
// created on any channel that the authenticated bot has access to
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {

	// https://github.com/bwmarrin/discordgo/issues/961
	if m.Content == "" {
		chanMsgs, err := s.ChannelMessages(m.ChannelID, 1, "", "", m.ID)
		if err != nil {
			log.Println("Unable to get messages:", err)
			return
		}
		if len(chanMsgs) > 0 {
			m.Content = chanMsgs[0].Content
			m.Attachments = chanMsgs[0].Attachments
		}
	}

	// Log all messages if verbose set to true
	if config.Verbose {
		log.Println(m.Content)
	}

	// Split message by spaces into individual fields
	for _, w := range strings.Fields(m.Content) {

		// Assess whether message part looks like a valid URL
		u, err := url.Parse(w)
		if err != nil || !u.IsAbs() || strings.IndexByte(u.Host, '.') <= 0 {
			continue
		}

		// Ensure domain TLD is ICANN-managed
		if _, icann := publicsuffix.PublicSuffix(u.Host); !icann {
			continue
		}

		// Normalize URL (RFC 3986)
		uStr := normalize.NormalizeURL(u,
			normalize.FlagsSafe|normalize.FlagRemoveDotSegments|
				normalize.FlagRemoveDuplicateSlashes|
				normalize.FlagRemoveFragment|
				normalize.FlagSortQuery)

		log.Println(uStr)

		// Ensure host is not present in ignoreList set
		if isIgnored(config.Ignore, uStr) {
			continue
		}

		// Send message attributes/URL over the channel
		message := Message{
			URL:     uStr,
			Author:  m.Author.ID,
			Guild:   m.GuildID,
			Channel: m.ChannelID,
		}
		messageChan <- &message
	}
}