-
Notifications
You must be signed in to change notification settings - Fork 1
/
import.go
319 lines (273 loc) · 7.97 KB
/
import.go
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package main
import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"io"
"log"
"os"
"strings"
"time"
"fmt"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
)
type Browsers []Browser
type Browser struct {
Name string `json:"Name"`
Type string `json:"Type"`
HistoryDBPath string `json:"HistoryDBPath"`
Query string `json:"Query"`
TimestampConverter func(int64) int64 `json:"TimestampConverter"`
}
func updateBrowsersMetadata(b Browsers) Browsers {
for i := range b {
switch strings.ToLower(b[i].Type) {
case "chrome":
b[i].Query = "SELECT url, title, visit_count, last_visit_time FROM urls ORDER BY last_visit_time DESC"
b[i].TimestampConverter = convertChromeTimestamp
case "firefox":
b[i].Query = "SELECT url, COALESCE(title,'') AS title, visit_count, COALESCE(last_visit_date,0) AS last_visit_date FROM moz_places ORDER BY last_visit_date DESC"
b[i].TimestampConverter = convertFirefoxTimestamp
default:
log.Printf("Browser not supported: %s", b[i].Name)
}
}
return b
}
func (b Browser) copyDBPath(tmpDir string) string {
return filepath.Join(tmpDir, b.Name+".db")
}
type BrowserHistoryEntry struct {
URL string
Title string
VisitCount int
LastVisitTime int64
}
func (browsers Browsers) processHistory(db *sql.DB, tmpDir, instanceID string) error {
log.Println("Processing browser history")
err := createTempDir(tmpDir)
if err != nil {
return err
}
err = createTables(db)
if err != nil {
return err
}
for _, b := range browsers {
if b.Query == "" {
continue
}
err := processBrowserHistory(db, tmpDir, b, instanceID)
if err != nil {
return err
}
}
err = updateUrlsCache(db)
if err != nil {
return err
}
err = cleanTempDir(tmpDir)
if err != nil {
return err
}
log.Println("Finished processing browser history")
return nil
}
func createTempDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.Mkdir(dir, 0755)
if err != nil {
return err
}
}
return nil
}
func cleanTempDir(dir string) error {
err := os.RemoveAll(dir)
if err != nil {
return err
}
return nil
}
func copyDatabase(originalPath, copyPath string) error {
input, err := os.Open(originalPath)
if err != nil {
return err
}
defer input.Close()
output, err := os.Create(copyPath)
if err != nil {
return err
}
defer output.Close()
_, err = io.Copy(output, input)
return err
}
func convertChromeTimestamp(chromeTimestamp int64) int64 {
return (chromeTimestamp - 11644473600000000) / 1000000
}
func convertFirefoxTimestamp(firefoxTimestamp int64) int64 {
return firefoxTimestamp / 1000000
}
func hashURL(url string) string {
hasher := sha256.New()
hasher.Write([]byte(url))
return hex.EncodeToString(hasher.Sum(nil))
}
func createTables(db *sql.DB) error {
statements := []string{
`CREATE TABLE IF NOT EXISTS urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
title TEXT,
visit_count INTEGER,
last_visit_time INTEGER,
browser TEXT,
instance_id TEXT,
url_hash TEXT TEXT,
UNIQUE(url_hash, browser, instance_id)
);
CREATE INDEX IF NOT EXISTS idx_urls_url_last_visit_time ON urls(url, last_visit_time);
CREATE INDEX IF NOT EXISTS idx_urls_url ON urls(url);
REINDEX urls;`,
`CREATE TABLE IF NOT EXISTS urls_cache (
id INTEGER,
url TEXT,
url_lower TEXT,
url_https TEXT,
url_https_lower TEXT,
title TEXT,
title_lower TEXT,
visit_count INTEGER,
last_visit_time INTEGER,
browser TEXT,
instance_id TEXT,
url_hash TEXT TEXT
);
CREATE INDEX IF NOT EXISTS idx_urls_title ON urls_cache (title_lower);
CREATE INDEX IF NOT EXISTS idx_urls_url ON urls_cache (url_lower);
CREATE INDEX IF NOT EXISTS idx_urls_https_url ON urls_cache (url_https_lower);`,
`CREATE TABLE IF NOT EXISTS last_run (
instance TEXT,
browser TEXT,
timestamp INTEGER
);`,
}
for _, s := range statements {
_, err := db.Exec(s)
if err != nil {
return fmt.Errorf("error executing statement %q: %w", s, err)
}
}
return nil
}
func fetchEntries(db *sql.DB, query string, convertTimestamp func(int64) int64) ([]BrowserHistoryEntry, error) {
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var entries []BrowserHistoryEntry
for rows.Next() {
var e BrowserHistoryEntry
if err := rows.Scan(&e.URL, &e.Title, &e.VisitCount, &e.LastVisitTime); err != nil {
return nil, err
}
e.LastVisitTime = convertTimestamp(e.LastVisitTime)
entries = append(entries, e)
}
return entries, nil
}
func upsertEntriesToDB(db *sql.DB, entries []BrowserHistoryEntry, browser, instanceID string) error {
log.Printf("Starting merge for browser: %s", browser)
upsertQuery := `INSERT INTO urls
(url, title, visit_count, last_visit_time, browser, instance_id, url_hash)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(url_hash, browser, instance_id) DO UPDATE SET
title=excluded.title,
visit_count=excluded.visit_count,
last_visit_time=excluded.last_visit_time;`
tx, err := db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare(upsertQuery)
if err != nil {
return err
}
defer stmt.Close()
for _, e := range entries {
urlHash := hashURL(e.URL)
_, err := stmt.Exec(e.URL, e.Title, e.VisitCount, e.LastVisitTime, browser, instanceID, urlHash)
if err != nil {
tx.Rollback()
return err
}
}
err = tx.Commit()
if err != nil {
return err
}
log.Printf("Done merging for browser: %s", browser)
return nil
}
func updateUrlsCache(db *sql.DB) error{
updateQuery := `
DELETE FROM urls_cache;
INSERT INTO urls_cache (id, url, url_lower, url_https, url_https_lower, title, title_lower, visit_count, last_visit_time, browser, instance_id, url_hash)
/* Some times the title changes for the url, so here the latest title is selected for each url. */
WITH latest_titles AS (
SELECT url, title, ROW_NUMBER() OVER (PARTITION BY url ORDER BY last_visit_time DESC) AS rownumber
FROM urls
)
SELECT id, u.url, LOWER(u.url) as url_lower, u.url,LOWER(u.url),lt.title, LOWER(lt.title) as title_lower,
visit_count, last_visit_time, browser, instance_id, url_hash
FROM urls u
JOIN latest_titles lt ON u.url = lt.url AND lt.rownumber = 1
WHERE u.url LIKE 'https://%'
UNION
SELECT id, u.url, LOWER(u.url) as url_lower, coalesce(u2.url,u.url) as url_https, LOWER(coalesce(u2.url,u.url)) AS url_https_lower,
lt.title, LOWER(lt.title) as title_lower,
visit_count, last_visit_time, browser, instance_id, url_hash
FROM urls u
JOIN latest_titles lt ON u.url = lt.url AND lt.rownumber = 1
LEFT JOIN (SELECT DISTINCT url FROM urls) u2 ON REPLACE(u.url, 'http://', 'https://')=u2.url
WHERE u.url LIKE 'http://%';
REINDEX urls_cache;
`
_, err := db.Exec(updateQuery)
return err
}
func insertLastRun(db *sql.DB, browser, instanceID string) error {
insertQuery := "INSERT INTO last_run (instance, browser, timestamp) VALUES (?, ?, ?)"
_, err := db.Exec(insertQuery, instanceID, browser, time.Now().Unix())
return err
}
func processBrowserHistory(db *sql.DB, tmpDir string, b Browser, instanceID string) error {
copyDBPath := b.copyDBPath(tmpDir)
log.Printf("Processing browser %s on path %s \n", b.Name, copyDBPath)
err := copyDatabase(b.HistoryDBPath, copyDBPath)
if err != nil {
return err
}
historyDB, err := sql.Open("sqlite3", copyDBPath)
if err != nil {
return err
}
defer historyDB.Close()
entries, err := fetchEntries(historyDB, b.Query, b.TimestampConverter)
if err != nil {
return err
}
log.Printf("Found %d entries for browser %s \n", len(entries), b.Name)
err = upsertEntriesToDB(db, entries, b.Name, instanceID)
if err != nil {
return err
}
err = insertLastRun(db, b.Name, instanceID)
if err != nil {
return err
}
return nil
}