-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
538 lines (499 loc) · 12.8 KB
/
main.go
File metadata and controls
538 lines (499 loc) · 12.8 KB
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
package main
import (
"archive/zip"
"bytes"
"database/sql"
"errors"
"fmt"
"html/template"
"image"
"image/png"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"github.com/chai2010/webp"
"github.com/gorilla/mux"
"github.com/gosimple/slug"
_ "github.com/mattn/go-sqlite3"
)
var templates *template.Template
var sqliteDatabase *sql.DB
type Comic struct {
ID string
Title string
Artist string
Book string
Timestamp int64
Library bool
}
type ComicLocalPath struct {
ID string
LocalPath string
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
pageParam := r.FormValue("page")
var page int
if len(pageParam) < 1 {
page = 0
} else {
var err error
page, err = strconv.Atoi(pageParam)
if err != nil {
log.Println(err)
}
}
limitParam := r.FormValue("limit")
var limit int
if len(limitParam) < 1 {
limit = 12
} else {
var err error
limit, err = strconv.Atoi(limitParam)
if err != nil {
log.Println(err)
}
}
libraryParam := r.FormValue("library")
keywordsParam := r.FormValue("keywords")
sortByParam := r.FormValue("sort-by")
var sortBy string
if len(sortByParam) < 1 {
sortBy = "import_timestamp"
} else {
sortBy = sortByParam
}
sortTypeParam := r.FormValue("sort-type")
var sortType string
if len(sortByParam) < 1 {
sortType = "DESC"
} else {
sortType = sortTypeParam
}
historyModeParam := r.FormValue("history-mode")
data := struct {
Previous int
Next int
Page int
Library string
Keywords string
SortBy string
SortType string
NumberOfPage int
Data []Comic
LastVisitedPage string
HistoryMode string
}{
Previous: page - 1,
Next: page + 1,
Page: page,
Library: libraryParam,
Keywords: keywordsParam,
SortBy: sortBy,
SortType: sortType,
Data: searchInDb(page, limit, libraryParam, keywordsParam, sortBy+" "+sortType),
LastVisitedPage: getAttrsValue("last_visited_page"),
HistoryMode: historyModeParam,
}
templates.ExecuteTemplate(w, "index.html", data)
if len(historyModeParam) > 0 {
incrementLastVisitedPage(page)
}
}
func libraryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
log.Println("id is missing in parameters")
}
if r.Method == "POST" {
updateLibrary(id, true)
} else if r.Method == "DELETE" {
updateLibrary(id, false)
}
}
func updateLibrary(id string, library bool) {
var update string
if library {
update = "INSERT OR IGNORE INTO library(comic_id) VALUES (?)"
} else {
update = "DELETE FROM library WHERE comic_id = ?"
}
_, err := sqliteDatabase.Exec(update, id)
if err != nil {
log.Println(err)
}
}
func searchInDb(page int, limit int, library string, keywords string, sort string) []Comic {
offset := page * limit
valid := regexp.MustCompile("^[A-Za-z0-9_ ]+$")
if !valid.MatchString(sort) {
log.Println("Invalid input")
return []Comic{}
}
row, err := sqliteDatabase.Query("SELECT c.id, c.title, c.artist, c.book, CAST(c.timestamp AS INTEGER), IIF(l.id, true, false) as onlibrary FROM comic c left join library l on c.id = l.comic_id WHERE (ifnull(?, '') = '' OR onlibrary = true) AND ((ifnull(?, '') = '' OR UPPER(c.artist) LIKE ?) OR (ifnull(?, '') = '' OR UPPER(c.title) LIKE ?) OR (ifnull(?, '') = '' OR UPPER(c.book) LIKE ?)) ORDER BY "+sort+" LIMIT ?, ?", library, keywords, "%"+keywords+"%", keywords, "%"+keywords+"%", keywords, "%"+keywords+"%", offset, limit)
var comics []Comic
if err != nil {
log.Println(err)
}
defer row.Close()
for row.Next() {
comic := Comic{}
row.Scan(&comic.ID, &comic.Title, &comic.Artist, &comic.Book, &comic.Timestamp, &comic.Library)
comics = append(comics, comic)
}
return comics
}
func getLocalPath(id string) ComicLocalPath {
row, err := sqliteDatabase.Query("SELECT id, local_path FROM comic WHERE id=?", id)
var comic ComicLocalPath
if err != nil {
log.Println(err)
}
defer row.Close()
for row.Next() {
row.Scan(&comic.ID, &comic.LocalPath)
}
return comic
}
func incrementLastVisitedPage(page int) {
val := getAttrsValue("last_visited_page")
lastVisitedPage, err := strconv.Atoi(val)
if err != nil {
log.Println(err)
}
if lastVisitedPage+1 == page {
_, err := sqliteDatabase.Exec("UPDATE attrs SET value = ? WHERE key = 'last_visited_page'", page)
if err != nil {
log.Println(err)
}
}
}
func getAttrsValue(key string) string {
row, err := sqliteDatabase.Query("SELECT value FROM attrs WHERE key=? LIMIT 1", key)
var value string
if err != nil {
log.Println(err)
}
defer row.Close()
for row.Next() {
row.Scan(&value)
}
return value
}
func readerHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
log.Println("id is missing in parameters")
}
path := getLocalPath(id)
zip, errz := zip.OpenReader(path.LocalPath)
if errz != nil {
log.Println(errz)
}
defer zip.Close()
var fileList []string
for _, f := range zip.File {
fileList = append(fileList, f.Name)
}
data := struct {
ID string
FileList []string
}{
ID: path.ID,
FileList: fileList,
}
if err := templates.ExecuteTemplate(w, "reader.html", data); err != nil {
log.Printf("Template error: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func coverHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
log.Println("id is missing in parameters")
}
w.Header().Set("Content-Type", "image/webp")
io.Copy(w, bytes.NewBuffer(getCoverFromDb(id)))
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, ok := vars["id"]
if !ok {
log.Println("id is missing in parameters")
}
page, ok := vars["page"]
if !ok {
log.Println("page is missing in parameters")
}
w.Header().Set("Content-Type", "image/png")
localPath := getLocalPath(id)
zip, errx := zip.OpenReader(localPath.LocalPath)
if errx != nil {
log.Println(errx)
}
defer zip.Close()
for _, f := range zip.File {
if f.Name != page {
continue
}
fc, err := f.Open()
if err != nil {
log.Println(err)
}
defer fc.Close()
content, err := ioutil.ReadAll(fc)
if err != nil {
log.Println(err)
}
io.Copy(w, bytes.NewBuffer(content))
}
}
func getCoverFromDb(id string) []byte {
row, err := sqliteDatabase.Query("SELECT cover FROM comic WHERE id=?", id)
if err != nil {
log.Println(err)
}
defer row.Close()
var data []byte
for row.Next() {
row.Scan(&data)
}
return data
}
func compressImage(path string) {
filepath.Walk(path, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() {
r, err := regexp.MatchString(".zip", f.Name())
if err == nil && r {
log.Printf("Processing %s", f.Name())
r, err := zip.OpenReader(path)
if err != nil {
return nil
}
defer r.Close()
archive, err := os.Create(fmt.Sprintf("Copy of -%s", f.Name()))
if err != nil {
panic(err)
}
defer archive.Close()
zipWriter := zip.NewWriter(archive)
for _, f := range r.File {
fc, err := f.Open()
if err != nil {
return nil
}
defer fc.Close()
content, err := ioutil.ReadAll(fc)
if err != nil {
return nil
}
img, _ := png.Decode(bytes.NewReader(content))
var buf bytes.Buffer
if err = webp.Encode(&buf, img, &webp.Options{Lossless: true}); err != nil {
log.Println(err)
}
w1, err := zipWriter.Create(f.Name)
if err != nil {
panic(err)
}
if _, err := io.Copy(w1, bytes.NewReader(buf.Bytes())); err != nil {
panic(err)
}
}
}
}
return nil
})
}
func reloadComicDb(path string) {
openDb()
reTitle := regexp.MustCompile(`(?s)\] (.*) \(`)
reArtist := regexp.MustCompile(`(?s)\[(.*)\]`)
reBook := regexp.MustCompile(`(?s)\((.*)\)`)
filepath.Walk(path, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() {
r, err := regexp.MatchString(".zip", f.Name())
if err == nil && r {
log.Printf("Processing %s", f.Name())
var buf bytes.Buffer
var image, err = extractCover(path)
var title string
var artist string
var book string
if len(reTitle.FindStringSubmatch(f.Name())) < 2 {
title = f.Name()
} else {
title = reTitle.FindStringSubmatch(f.Name())[1]
}
if len(reArtist.FindStringSubmatch(f.Name())) < 2 {
artist = "-"
} else {
artist = reArtist.FindStringSubmatch(f.Name())[1]
}
if len(reBook.FindStringSubmatch(f.Name())) < 2 {
book = "-"
} else {
book = reBook.FindStringSubmatch(f.Name())[1]
}
if err == nil && image != nil {
data := Comic{
Title: title,
Artist: artist,
Book: book,
Timestamp: image.ModTime.UnixMilli(),
}
if err = webp.Encode(&buf, image.Image, &webp.Options{Lossless: false}); err != nil {
log.Println(err)
}
insertComic(data, path, buf.Bytes())
} else {
log.Printf("Skipping %s: %s", path, err.Error())
}
}
}
return nil
})
log.Printf("Done importing %s", path)
}
type Cover struct {
Image image.Image
ModTime time.Time
}
func extractCover(localPath string) (*Cover, error) {
r, err := zip.OpenReader(localPath)
if err != nil {
return nil, errors.New("error opening zip file " + localPath)
}
defer r.Close()
for i, f := range r.File {
if i == 0 {
fc, err := f.Open()
if err != nil {
return nil, errors.New("error opening image file " + localPath)
}
defer fc.Close()
content, err := ioutil.ReadAll(fc)
if err != nil {
return nil, errors.New("error reading image bytes " + localPath)
}
img, err := png.Decode(bytes.NewReader(content))
if err != nil {
return nil, errors.New("error decoding image " + localPath)
}
imagewrapper := &Cover{
Image: img,
ModTime: f.Modified,
}
return imagewrapper, nil
}
}
return nil, errors.New("file not found")
}
func initDb() {
sqliteDatabase, err := sql.Open("sqlite3", "./comic.db")
if err != nil {
log.Println(err.Error())
}
createComicTableSQL := `CREATE TABLE comic (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT,
"artist" TEXT,
"book" TEXT,
"timestamp" TIMESTAMP,
"import_timestamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
"local_path" TEXT,
"cover" BLOB
);`
createStatement, err := sqliteDatabase.Prepare(createComicTableSQL)
if err != nil {
log.Println(err.Error())
}
createStatement.Exec()
log.Println("comic table created")
createLibraryTableSQL := `CREATE TABLE library (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"comic_id" TEXT NOT NULL
);`
createStatement, err = sqliteDatabase.Prepare(createLibraryTableSQL)
if err != nil {
log.Println(err.Error())
}
createStatement.Exec()
log.Println("library table created")
createLastVisitedPageTableSQL := `CREATE TABLE attrs (
"key" TEXT PRIMARY KEY,
"value" TEXT NOT NULL
);`
createStatement, err = sqliteDatabase.Prepare(createLastVisitedPageTableSQL)
if err != nil {
log.Println(err.Error())
}
createStatement.Exec()
log.Println("attrs table created")
statement, err := sqliteDatabase.Prepare(`INSERT INTO attrs(key, value) VALUES ('last_visited_page', '0')`)
if err != nil {
log.Println(err.Error())
}
_, err = statement.Exec()
if err != nil {
log.Println(err.Error())
}
log.Println("attrs data initialized")
}
func insertComic(comic Comic, localPath string, cover []byte) {
insertComicSQL := `INSERT OR IGNORE INTO comic(id, title, artist, book, timestamp, import_timestamp, local_path, cover) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, ?)`
statement, err := sqliteDatabase.Prepare(insertComicSQL)
if err != nil {
log.Println(err.Error())
}
_, err = statement.Exec(slug.Make(comic.Title), comic.Title, comic.Artist, comic.Book, comic.Timestamp, localPath, cover)
if err != nil {
log.Println(err.Error())
}
}
func openDb() {
var err error
sqliteDatabase, err = sql.Open("sqlite3", "./comic.db")
if err != nil {
log.Println(err.Error())
}
}
func startWebServer() {
openDb()
templates = template.Must(templates.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexHandler)
r.HandleFunc("/reader/{id}", readerHandler)
r.HandleFunc("/reader/{id}/{page}", pageHandler)
r.HandleFunc("/covers/{id}", coverHandler)
r.HandleFunc("/library/{id}", libraryHandler).Methods("POST")
r.HandleFunc("/library/{id}", libraryHandler).Methods("DELETE")
log.Println("Listing for requests at http://localhost:4647/")
log.Fatal(http.ListenAndServe(":4647", r))
}
func main() {
if len(os.Args) < 2 {
startWebServer()
} else {
if os.Args[1] == "init" {
initDb()
} else if os.Args[1] == "import" {
path := os.Args[2]
log.Printf("Importing %s", path)
reloadComicDb(path)
} else if os.Args[1] == "compress" {
path := os.Args[2]
log.Printf("Compressing %s", path)
compressImage(path)
}
}
}