-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
473 lines (408 loc) · 11.8 KB
/
main.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package main
import (
"encoding/hex"
"html/template"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/Wessie/appdirs"
"github.com/dustin/go-humanize"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/jessevdk/go-flags"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/izolight/magnetico/pkg/persistence"
)
const N_TORRENTS = 20
var templates map[string]*template.Template
var database persistence.Database
type cmdFlags struct {
DatabaseURL string `long:"database" description:"URL of the database."`
BindAddr string `short:"b" long:"bind" description:"Address that the WebUI should listen on." env:"BIND_ADDR" env-delim:"," default:"0.0.0.0:8080"`
Verbose []bool `short:"v" long:"verbose" description:"Increases verbosity."`
}
type opFlags struct {
DatabaseURL *url.URL
BindAddr string
Verbosity int
}
// ========= TD: TemplateData =========
type HomepageTD struct {
Count uint
Size uint64
}
type TorrentsTD struct {
Search string
SubscriptionURL string
Torrents []persistence.TorrentMetadata
Epoch int64
OrderBy string
Ascending bool
Limit uint
FirstOrderedValue interface{}
LastOrderedValue interface{}
StartID uint64
FirstID uint64
LastID uint64
IsFirstPage bool
NextPageExists bool
}
type TorrentTD struct {
Torrent persistence.TorrentMetadata
Files []persistence.File
}
type FeedTD struct {
}
type StatisticsTD struct {
Stats persistence.Statistics
Dates []string
}
func main() {
loggerLevel := zap.NewAtomicLevel()
// Logging levels: ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").
logger := zap.New(zapcore.NewCore(
zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()),
zapcore.Lock(os.Stderr),
loggerLevel,
))
defer logger.Sync()
zap.ReplaceGlobals(logger)
opFlags, err := parseFlags()
if err != nil {
return
}
zap.L().Info("magneticow v0.7.0 has been started.")
zap.L().Info("Copyright (C) 2017 Mert Bora ALPER <bora@boramalper.org>.")
zap.L().Info("Dedicated to Cemile Binay, in whose hands I thrived.")
switch opFlags.Verbosity {
case 0:
loggerLevel.SetLevel(zap.WarnLevel)
case 1:
loggerLevel.SetLevel(zap.InfoLevel)
default: // Default: i.e. in case of 2 or more.
// TODO: print the caller (function)'s name and line number!
loggerLevel.SetLevel(zap.DebugLevel)
}
zap.ReplaceGlobals(logger)
router := mux.NewRouter()
router.HandleFunc("/", rootHandler)
router.HandleFunc("/torrents", torrentsHandler)
router.HandleFunc("/torrents/{infohash:[a-z0-9]{40}}", torrentsInfohashHandler)
router.HandleFunc("/statistics", statisticsHandler)
router.HandleFunc("/feed", feedHandler)
router.PathPrefix("/static").HandlerFunc(staticHandler)
templateFunctions := template.FuncMap{
"add": func(augend int, addends int) int {
return augend + addends
},
"subtract": func(minuend int, subtrahend int) int {
return minuend - subtrahend
},
"bytesToHex": func(bytes []byte) string {
return hex.EncodeToString(bytes)
},
"unixTimeToYearMonthDay": func(s int64) string {
tm := time.Unix(s, 0)
// > Format and Parse use example-based layouts. Usually you’ll use a constant from time
// > for these layouts, but you can also supply custom layouts. Layouts must use the
// > reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to
// > format/parse a given time/string. The example time must be exactly as shown: the
// > year 2006, 15 for the hour, Monday for the day of the week, etc.
// https://gobyexample.com/time-formatting-parsing
// Why you gotta be so weird Go?
return tm.Format("2006-01-02 15:04")
},
"humanizeSize": func(s uint64) string {
return humanize.IBytes(s)
},
}
templates = make(map[string]*template.Template)
templates["feed"] = template.Must(template.New("feed").Parse(string(mustAsset("templates/feed.xml"))))
templates["homepage"] = template.Must(template.New("homepage").Funcs(templateFunctions).Parse(string(mustAsset("templates/homepage.html"))))
templates["statistics"] = template.Must(template.New("statistics").Parse(string(mustAsset("templates/statistics.html"))))
templates["torrent"] = template.Must(template.New("torrent").Funcs(templateFunctions).Parse(string(mustAsset("templates/torrent.html"))))
templates["torrents"] = template.Must(template.New("torrents").Funcs(templateFunctions).Parse(string(mustAsset("templates/torrents.html"))))
database, err = persistence.MakeDatabase(opFlags.DatabaseURL, logger)
if err != nil {
panic(err.Error())
}
zap.L().Info("magneticow is ready to serve!")
http.ListenAndServe(opFlags.BindAddr, handlers.CombinedLoggingHandler(os.Stdout, router))
}
// DONE
func rootHandler(w http.ResponseWriter, r *http.Request) {
count, err := database.GetNumberOfTorrents()
if err != nil {
zap.L().Error("Couldn't get number of torrents",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
size, err := database.GetTotalSizeOfTorrents()
if err != nil {
zap.L().Error("Couldn't get size of torrents",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
templates["homepage"].Execute(w, HomepageTD{
Count: count,
Size: size,
})
}
func torrentsHandler(w http.ResponseWriter, r *http.Request) {
queryValues := r.URL.Query()
search := queryValues.Get("search")
epoch := time.Now()
orderBy := persistence.ByRelevance
ascending := false
backward := false
limit := uint(N_TORRENTS)
var lastOrderedValue uint64
var startID, firstID, lastID uint64
var err error
qOrderBy := queryValues.Get("orderBy")
switch qOrderBy {
case "size":
orderBy = persistence.BySize
case "discovered":
orderBy = persistence.ByDiscoveredOn
case "files":
orderBy = persistence.ByNFiles
case "seeders":
orderBy = persistence.ByNSeeders
case "leechers":
orderBy = persistence.ByNLeechers
default:
if search == "" {
orderBy = persistence.ByDiscoveredOn
}
}
if queryValues.Get("ascending") != "" {
ascending = true
}
if queryValues.Get("backward") != "" {
backward = true
}
qLimit := queryValues.Get("limit")
if qLimit != "" {
l, err := strconv.ParseUint(qLimit, 10, 64)
if err != nil {
zap.L().Error("Couldn't parse limit",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
limit = uint(l)
}
if queryValues.Get("epoch") != "" {
qEpoch, err := strconv.ParseInt(queryValues.Get("epoch"), 10, 64)
if err != nil {
zap.L().Error("Couldn't parse epoch",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
epoch = time.Unix(qEpoch, 0)
qLastOrderedValue := queryValues.Get("lastOrderedValue")
qLastID := queryValues.Get("lastID")
if qLastOrderedValue != "" && qLastID != "" {
lastOrderedValue, err = strconv.ParseUint(qLastOrderedValue, 10, 64)
if err != nil {
zap.L().Error("Couldn't parse lastOrderedValue",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
lastID, err = strconv.ParseUint(qLastID, 10, 64)
if err != nil {
zap.L().Error("Couldn't parse lastID",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("when specifying epoch, need to supply lastOrderedValue and lastID as well"))
}
}
var torrents []persistence.TorrentMetadata
torrents, err = database.QueryTorrents(
search,
epoch.Unix(),
orderBy,
ascending,
limit,
lastOrderedValue,
lastID,
backward,
)
if err != nil {
zap.L().Error("Couldn't get torrents from database",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
if queryValues.Get("startID") != "" {
startID, err = strconv.ParseUint(queryValues.Get("startID"), 10, 64)
} else if len(torrents) != 0 {
startID = uint64(torrents[0].ID)
}
var firstOrdered, lastOrdered interface{}
var isFirstPage bool
if len(torrents) != 0 {
firstOrdered = torrents[0].DiscoveredOn
lastOrdered = torrents[len(torrents)-1].DiscoveredOn
firstID = uint64(torrents[0].ID)
lastID = uint64(torrents[len(torrents)-1].ID)
isFirstPage = startID == uint64(torrents[0].ID) || startID == uint64(torrents[len(torrents)-1].ID)
}
// TODO: for testing, REMOVE
//torrents[2].HasReadme = true
templates["torrents"].Execute(w, TorrentsTD{
Search: search,
SubscriptionURL: "borabora",
Torrents: torrents,
Epoch: epoch.Unix(),
OrderBy: qOrderBy,
Ascending: ascending,
Limit: limit,
FirstOrderedValue: firstOrdered,
LastOrderedValue: lastOrdered,
StartID: startID,
FirstID: firstID,
LastID: lastID,
NextPageExists: len(torrents) >= 20,
IsFirstPage: isFirstPage,
})
}
func torrentsInfohashHandler(w http.ResponseWriter, r *http.Request) {
// show torrents/{infohash}
infoHash, err := hex.DecodeString(mux.Vars(r)["infohash"])
if err != nil {
zap.L().Error("Couldn't decode infohash",
zap.Error(err),
)
w.WriteHeader(http.StatusBadRequest)
return
}
torrent, err := database.GetTorrent(infoHash)
if err != nil {
zap.L().Error("Couldn't get torrent from database",
zap.Error(err),
zap.String("infohash", string(infoHash)),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
if torrent == nil {
http.NotFound(w, r)
return
}
files, err := database.GetFiles(infoHash)
if err != nil {
zap.L().Error("Couldn't get files from database",
zap.Error(err),
zap.String("infohash", string(infoHash)),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
templates["torrent"].Execute(w, TorrentTD{
Torrent: *torrent,
Files: files,
})
}
func statisticsHandler(w http.ResponseWriter, r *http.Request) {
interval, err := time.ParseDuration("24h")
if err != nil {
zap.L().Error("Couldn't parse Interval",
zap.Error(err),
)
w.WriteHeader(http.StatusInternalServerError)
return
}
from := time.Now().Add(-30 * interval)
stats, err := database.GetStatistics(30, from.Format("2006-01-02"))
if err != nil {
zap.L().Error("Couldn't get parse dateformat",
zap.Error(err),
zap.Time("date", from),
)
w.WriteHeader(http.StatusBadRequest)
return
}
var dates []string
for i := 0; i < 30; i++ {
from = from.Add(interval)
dates = append(dates, from.Format("2006-01-02"))
}
templates["statistics"].Execute(w, StatisticsTD{
Stats: *stats,
Dates: dates,
})
}
func feedHandler(w http.ResponseWriter, r *http.Request) {
}
func staticHandler(w http.ResponseWriter, r *http.Request) {
data, err := Asset(r.URL.Path[1:])
if err != nil {
http.NotFound(w, r)
return
}
var contentType string
if strings.HasSuffix(r.URL.Path, ".css") {
contentType = "text/css; charset=utf-8"
} else { // fallback option
contentType = http.DetectContentType(data)
}
w.Header().Set("Cache-Control", "max-age=86400")
w.Header().Set("Content-Type", contentType)
w.Write(data)
}
func mustAsset(name string) []byte {
data, err := Asset(name)
if err != nil {
log.Panicf("Could NOT access the requested resource `%s`: %s (please inform us, this is a BUG!)", name, err.Error())
}
return data
}
func parseFlags() (*opFlags, error) {
opF := new(opFlags)
cmdF := new(cmdFlags)
_, err := flags.Parse(cmdF)
if err != nil {
return nil, err
}
if cmdF.DatabaseURL == "" {
cmdF.DatabaseURL = "sqlite3://" + path.Join(
appdirs.UserDataDir("magneticod", "", "", false),
"database.sqlite3",
)
}
opF.DatabaseURL, err = url.Parse(cmdF.DatabaseURL)
if err != nil {
zap.L().Fatal("Failed to parse DB URL", zap.Error(err))
}
_, err = net.ResolveTCPAddr("tcp", cmdF.BindAddr)
if err != nil {
zap.L().Fatal("Failed to parse Address", zap.Error(err))
}
opF.BindAddr = cmdF.BindAddr
opF.Verbosity = len(cmdF.Verbose)
return opF, nil
}