-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2118 lines (1828 loc) · 65.9 KB
/
Copy pathmain.go
File metadata and controls
2118 lines (1828 loc) · 65.9 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"image"
_ "image/gif" // Import GIF decode
"image/jpeg"
_ "image/jpeg" // Import JPEG decoder
"image/png"
_ "image/png" // Import PNG decoder
"io"
"log"
"math"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/andybalholm/brotli"
"github.com/charmbracelet/lipgloss"
"github.com/gen2brain/jpegli"
"github.com/go-pdf/fpdf"
fzf "github.com/koki-develop/go-fzf"
"github.com/schollz/progressbar/v3"
"golang.org/x/image/webp"
"golang.org/x/net/proxy"
"golang.org/x/sync/semaphore"
"golang.org/x/time/rate"
)
const (
version = "0.1.47"
historyFile = "goreadmanga_history.json"
)
type MangaResult struct {
Title string
URL string
}
type Chapter struct {
Number int
URL string
}
type BrowseRecord struct {
MangaTitle string `json:"manga_title"`
ChapterNumber int `json:"chapter_number"`
ChapterPage string `json:"chapter_page"`
ChapterTitle string `json:"chapter_title"`
Timestamp time.Time `json:"timestamp"`
}
type MangaStatistics struct {
TotalChapters int
ReadChapters int
LastReadChapter BrowseRecord
OldestTimestamp time.Time
NewestTimestamp time.Time
ReadingDates []time.Time
ChaptersNotRead int
UniqueChaptersRead map[int]bool // Track unique chapter numbers read
MostReadCount int
}
type model struct {
records []BrowseRecord
cursor int
}
var (
cacheDir string // Directory to hold files, preferably temp
currentManga string
servers = []string{"server2", "server1"} // Switch between content servers serving media
contentServer string
isJPMode bool // check whether user wants jpegli enabled
isWideSplitMode bool // check whether user wants to split wide images or scale to A4
isCCacheMode bool // This check is done so we don't print storage size when inside program since it is called in inputControls()
useFancyDecoding = false // Flag for toggling decoding method
jpegliQuality int = 85 // Default quality for jpegli encoding
socksProxyMode bool
socksProxy string
lightMagentaStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FF79C6"))
lightMagentaWithBg = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FF79C6")).Background(lipgloss.Color("#00194f"))
lightCyanStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#8BE9FD"))
textStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#F8F8F2"))
redStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000"))
magentaStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF00FF"))
yellowStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ebeb00"))
greenStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#50FA7B"))
cyanColor = lipgloss.NewStyle().Foreground(lipgloss.Color("#00FFFF"))
inputStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FFB86C"))
versionStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#FFB86C")).Background(lipgloss.Color("#282A36")).Padding(0, 2) // Adds horizontal padding to the version text
headerStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#8BE9FD")).Background(lipgloss.Color("#282A36")).Padding(0, 2)
resultStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#50FA7B")).Padding(0, 2)
indexStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF79C6")).PaddingRight(1)
bracketStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF79C6"))
chapterStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#95fb17"))
chapterStyleWithBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#95fb17")).Background(lipgloss.Color("#282A36"))
yellowFGbrownBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#95fb17")).Background(lipgloss.Color("#282A36"))
redFGblackBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#ff5f56")).Background(lipgloss.Color("#1e1e1e"))
// blueFGpurpleBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#005f87")).Background(lipgloss.Color("#4B0082"))
blueFGpurpleBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#ffff00")).Background(lipgloss.Color("#00194f"))
greenFGwhiteBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#00ff00")).Background(lipgloss.Color("#ffffff"))
cyanFGdarkBlueBG = lipgloss.NewStyle().Foreground(lipgloss.Color("#00ffff")).Background(lipgloss.Color("#000080"))
resetStyle = lipgloss.NewStyle()
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
debug.SetMaxStack(1000000000)
checkJPFlag()
checkWideSplitFlag()
checkDecodeFlag()
checkProxyFlag()
checkCCacheFlag()
checkCacheDir()
}
func main() {
setupSignalHandling()
if len(os.Args) > 1 {
handleArguments(os.Args[1:])
} else {
searchAndReadManga()
}
}
func setupSignalHandling() {
// If user interrupts program quit like a graceful swan maybe
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\n\nProgram Interrupted.")
/////////////////////////////////////////
// Enable to clear cache on interrupt
/////////////////////////////////////////
// os.RemoveAll(filepath.Join(cacheDir, getModMangaTitle(currentManga)))
// fmt.Println("\n💥💥 " + cyanColor.Render("Nuking cache...") + " 💥💥")
/////////////////////////////////////////
os.Exit(0)
}()
}
func handleArguments(args []string) {
switch args[0] {
case "-h", "--help":
showHelp()
case "-v", "--version":
showVersion()
case "-ws", "--wide-split":
isWideSplitMode = true
// case "-dj", "--decode-jpegli": // Checked via init()
// useFancyDecoding = true
case "-H", "--history":
showHistory()
case "-bh", "--browse-history":
showHistoryWithFzf()
case "-r", "--resume":
openLastSession(historyFile)
case "-od", "--opendir":
checkCacheDir()
err := openDirectory(cacheDir)
if err != nil {
fmt.Println("Error opening directory:", err)
}
case "-st", "--stats":
fetchStatistics()
case "-c", "--cache-size":
showCacheSize()
case "-C", "--clear-cache":
clearCache()
case "-f", "--fix":
removeEmptyEntries(historyFile)
default:
searchAndReadManga()
}
}
func fetchStatistics() {
var records []BrowseRecord
fileData, err := os.ReadFile(historyFile)
if err != nil {
return
}
if err := json.Unmarshal(fileData, &records); err != nil {
fmt.Printf("error unmarshaling data from historyFile: %v\n", err)
}
// Process records from additional JSON files
globPattern := "goreadmanga_history_*.json"
matches, err := filepath.Glob(globPattern)
if err != nil {
fmt.Printf("error finding additional history files: %v\n", err)
}
for _, filePath := range matches {
fileData, err := os.ReadFile(filePath)
if err != nil {
fmt.Printf("Error reading file %s: %v\n", filePath, err)
continue // skip to next file if reading fails
}
var additionalEntries []BrowseRecord
if err := json.Unmarshal(fileData, &additionalEntries); err != nil {
fmt.Printf("Error unmarshaling data from %s: %v\n", filePath, err)
continue // skip to next file if unmarshalling fails
}
records = append(records, additionalEntries...)
}
calculateStatistics(records)
}
func showHelp() {
title := lightMagentaStyle.Render("goreadmanga " + version + " (github.com/stl3/GoReadManga)")
subtitle := lightCyanStyle.Render("App for finding manga via the terminal")
usage := greenStyle.Render("Usage:")
options := greenStyle.Render("Options:")
optionText := textStyle.Render(`
-h, --help Print this help page
-v, --version Print version number
-jp, --jpegli Use jpegli to re-encode jpegs
-q, --quality Set quality to use with jpegli encoding (default: 85)
-ws, --wide-split Split images that are too wide and maximize vertically
-ph, --proxy-host Socks5 proxy support [server:port]
-H, --history Show last viewed manga entry in history
-bh, --browse-history Browse history file, select and read
-st, --stats Show history statistics
-r, --resume Continue from last session
-od, --opendir Open pdf dir
-c, --cache-size Print cache size (` + cacheDir + `)
-C, --clear-cache Purge cache dir (` + cacheDir + `)
-f, --fix Remove json entries causing problems (empty chapter_page/chapter_title during network issues)
`)
fmt.Printf(`
%s
%s
%s
GoReadManga [Option]
%s
%s
`, title, subtitle, usage, options, optionText)
}
func showVersion() {
versionText := versionStyle.Render("Version: " + version)
fmt.Println(versionText)
}
func showCacheSize() {
size, err := getDirSize(cacheDir)
if err != nil {
// fmt.Printf("Error or cache already empty: %v\n", err)
return
}
fmt.Printf("Cache size: %s (%s)\n", formatSize(size), cacheDir)
}
func clearCache() {
if !isCCacheMode { // Unlikely case, but if -C or --clear-cache ran with program we prevent it from showing duplicate cache size in menu
showCacheSize()
}
if promptYesNo("Proceed with clearing the cache?") {
err := os.RemoveAll(cacheDir)
if err != nil {
fmt.Printf("Error or cache already empty: %v\n", err)
} else {
fmt.Println("💥💥 " + cyanColor.Render("Cache successfully cleared") + " 💥💥")
}
}
}
// Update the searchAndReadManga function to set the currentManga
func searchAndReadManga() {
mangaTitleInput := promptUser("Search manga:")
fmt.Printf("Searching for '%s'...\n", mangaTitleInput)
searchResults := scrapeMangaList(mangaTitleInput)
if len(searchResults) == 0 {
fmt.Println("No search results found")
searchAndReadManga()
return
}
displaySearchResults(searchResults)
selectedManga := selectManga(searchResults)
currentManga = selectedManga.Title
chapters := scrapeChapterList(selectedManga.URL)
if len(chapters) == 0 {
fmt.Println("No chapters found. Exiting...")
os.Exit(1)
}
selectedChapter := selectChapter(chapters)
openChapter(selectedManga, selectedChapter)
inputControls(selectedManga, chapters, selectedChapter)
}
func scrapeMangaList(query string) []MangaResult {
baseURL := fmt.Sprintf("https://manganato.com/search/story/%s", strings.ReplaceAll(query, " ", "_"))
doc, err := fetchDocument(baseURL)
if err != nil {
fmt.Printf("Error fetching search results: %v\n", err)
return nil
}
// Find total number of pages
lastPage := 1
doc.Find(".panel-page-number .page-last").Each(func(i int, s *goquery.Selection) {
href, exists := s.Attr("href")
if exists {
// Extract the page number from the href
var num int
fmt.Sscanf(href, baseURL+"?page=%d", &num)
if num > lastPage {
lastPage = num
}
}
})
// Limit to maximum 5 pages
// Not sure if what you're actually searching is beyond 1st 5 pages...
maxPages := 5
if lastPage < maxPages {
maxPages = lastPage
}
var results []MangaResult
// Create a rate limiter that allows 1 request per second
limiter := rate.NewLimiter(1, 1)
// Scrape results from the first page up to maxPages
for page := 1; page <= maxPages; page++ {
// Wait for the next available slot
limiter.Wait(context.Background())
url := baseURL
if page > 1 {
url = fmt.Sprintf("%s?page=%d", baseURL, page)
}
doc, err := fetchDocument(url)
if err != nil {
fmt.Printf("Error fetching page %d: %v\n", page, err)
continue
}
doc.Find(".panel-search-story .item-right").Each(func(i int, s *goquery.Selection) {
title := s.Find("h3 a").Text()
href, _ := s.Find("h3 a").Attr("href")
results = append(results, MangaResult{Title: title, URL: href})
})
}
return results
}
func displaySearchResults(results []MangaResult) {
header := headerStyle.Render(fmt.Sprintf("Found %d result(s):", len(results)))
fmt.Println(header)
for i, result := range results {
index := indexStyle.Render(fmt.Sprintf("[%d]", i+1))
resultText := resultStyle.Render(result.Title)
fmt.Printf("%s %s\n", index, resultText)
}
fmt.Println()
}
func selectManga(results []MangaResult) MangaResult {
if len(results) == 1 {
fmt.Printf("Selected '%s'\n", results[0].Title)
return results[0]
}
for {
selection := promptUser(fmt.Sprintf("Select manga [1-%d]:", len(results)))
index, err := strconv.Atoi(selection)
if err != nil || index < 1 || index > len(results) {
fmt.Println("Invalid selection")
continue
}
return results[index-1]
}
}
func scrapeChapterList(mangaURL string) []Chapter {
doc, err := fetchDocument(mangaURL)
if err != nil {
fmt.Printf("Error fetching chapter list: %v\n", err)
return nil
}
var chapters []Chapter
doc.Find(".row-content-chapter li").Each(func(i int, s *goquery.Selection) {
href, _ := s.Find("a").Attr("href")
// Append chapters normally
chapters = append(chapters, Chapter{URL: href})
})
// Reverse the order of chapters
for i := len(chapters)/2 - 1; i >= 0; i-- {
opp := len(chapters) - 1 - i
chapters[i], chapters[opp] = chapters[opp], chapters[i]
}
// Assign numbers after reversing
for i := range chapters {
chapters[i].Number = i + 1 // Set correct numbering after reversing
}
return chapters
}
func selectChapter(chapters []Chapter) Chapter {
if len(chapters) == 1 {
fmt.Println("Selected first chapter")
return chapters[0]
}
for {
selection := promptUser(fmt.Sprintf("Select chapter [1-%d]:", len(chapters)))
index, err := strconv.Atoi(selection)
if err != nil || index < 1 || index > len(chapters) {
fmt.Println("Invalid selection")
continue
}
return chapters[index-1]
}
}
func openChapter(manga MangaResult, chapter Chapter) {
images, chapterTitle := scrapeChapterImages(chapter.URL)
pdfPath := downloadAndConvertToPDF(manga, chapter, images, chapterTitle)
openPDF(pdfPath)
}
func sanitizeFilename(name string) string {
// Replace illegal characters with an underscore
// Windows illegal characters: \ / : * ? " < > |
illegalChars := regexp.MustCompile(`[<>:"/\\|?*]`)
return illegalChars.ReplaceAllString(name, "_")
}
func scrapeChapterImages(chapterURL string) ([]string, string) {
var images []string
var currentServer string
var doc *goquery.Document
var err error
for _, server := range servers {
////////// Debug Message //////////
// fmt.Printf("Trying server: %s\n", server)
///////////////////////////////////
currentServer = getImageServer(server, chapterURL)
if currentServer == "" {
fmt.Printf("Failed to get image server for %s\n", server)
continue
}
doc, err = fetchDocument(chapterURL)
if err != nil {
fmt.Printf("Error fetching chapter images: %v\n", err)
continue
}
images = []string{}
doc.Find(".container-chapter-reader img").Each(func(i int, s *goquery.Selection) {
src, exists := s.Attr("src")
if exists {
parsedURL, err := url.Parse(src)
if err == nil {
parsedURL.Host = currentServer
images = append(images, parsedURL.String())
}
}
})
if len(images) > 0 {
break
}
}
if len(images) == 0 {
fmt.Println("Failed to find any images")
return nil, ""
}
chapterTitle := doc.Find(".panel-chapter-info-top h1").Text()
chapterTitle = sanitizeFilename(chapterTitle)
fmt.Printf("Found %d image URLs\n", len(images))
return images, chapterTitle
}
func downloadAndConvertToPDF(manga MangaResult, chapter Chapter, imageURLs []string, chapterTitle string) string {
// totalChapters := len(chapters) // Add a record for total chapters so we can generate statistics
// Create a record for the current manga and chapter
record := BrowseRecord{
MangaTitle: manga.Title,
ChapterNumber: chapter.Number,
ChapterTitle: chapterTitle,
ChapterPage: chapter.URL,
// TotalChapters: totalChapters,
}
// Record the browsing history
if err := recordBrowseHistory(historyFile, record); err != nil {
fmt.Printf("Error recording history: %v\n", err)
}
mangaDir := filepath.Join(cacheDir, getModMangaTitle(manga.Title))
////////// Debug Message //////////
// fmt.Printf("manga title: %s\n", manga.Title)
///////////////////////////////////
// Format the PDF filename with the chapter number and title
// chapterTitle contains title/chapter number/chapter title
pdfFilename := fmt.Sprintf("%s.pdf", chapterTitle)
pdfPath := filepath.Join(mangaDir, pdfFilename)
// Return if PDF already exists
if _, err := os.Stat(pdfPath); err == nil {
return pdfPath
}
// Create directories for chapter and images
chapterDir := filepath.Join(mangaDir, fmt.Sprintf("chapter_%d", chapter.Number))
os.MkdirAll(chapterDir, os.ModePerm)
fmt.Println("Downloading images...")
// Preallocate a slice to store the image paths in order
imagePaths := make([]string, len(imageURLs))
var wg sync.WaitGroup
var mu sync.Mutex
// Semaphore to limit concurrent downloads, default 5
// Seems to crash now when higher than 1
// 1 for jpegli
// // maxConcurrentDownloads := int64(1)
maxConcurrentDownloads := int64(1)
/////////////////////////
// Enable for testing [no bueno right now, it crashes almost always and it seems fast enough by default]
// Adjust time.sleep below instead
// if isJPMode {
// maxConcurrentDownloads = int64(2)
// }
/////////////////////////
sem := semaphore.NewWeighted(maxConcurrentDownloads)
bar := progressbar.New(len(imageURLs)) // Initialize the progress bar
for i, url := range imageURLs {
wg.Add(1)
// Start go routine for each download
go func(i int, url string) {
defer wg.Done()
if err := sem.Acquire(context.Background(), 1); err != nil {
fmt.Printf("Failed to acquire semaphore: %v\n", err)
return
}
defer sem.Release(1)
// This part only added for prevention of being rate limited
// but still testing
// < 100 fast > 500 slow
time.Sleep(100 * time.Millisecond)
////////// Debug Message //////////
// print(url)
///////////////////////////////////
imagePath := filepath.Join(chapterDir, fmt.Sprintf("%d.jpg", i+1))
if !isJPMode {
fmt.Printf("\rDownloading image %d from: %s\r\n", i+1, url)
bar.Add(1)
}
err := downloadFile(url, imagePath)
if err != nil {
fmt.Printf("Error downloading image %d: %v\n", i+1, err)
return
}
if verifyImage(imagePath) {
mu.Lock()
imagePaths[i] = imagePath
mu.Unlock()
} else {
fmt.Printf("Invalid image file: %s\n", imagePath)
// Not sure if this is needed
// os.Remove(imagePath)
}
if isJPMode {
bar.Add(1)
}
}(i, url)
///////////////////////////////////////////////////////////////////////////////
////////// Debug Message //////////
// Monitor number of active goroutines
// fmt.Printf("Active goroutines: %d\n", runtime.NumGoroutine())
///////////////////////////////////
}
// Wait for all downloads to finish
wg.Wait()
// Let's go crazy with garbage collection
runtime.GC()
// Release semaphore, if you wantses it
// sem.Release(1)
// This may not be needed, maybe. Just keep it for now.
// Remove any empty entries in imagePaths (if some downloads failed)
finalImagePaths := []string{}
for _, path := range imagePaths {
if path != "" {
finalImagePaths = append(finalImagePaths, path)
}
}
// If no valid images were downloaded, return empty result
if len(finalImagePaths) == 0 {
fmt.Println("No valid images downloaded. Unable to create PDF.")
return ""
}
fmt.Println("\nConverting images to PDF...")
err := createPDFFromImages(finalImagePaths, pdfPath)
if err != nil {
fmt.Printf("Error creating PDF: %v\n", err)
return ""
}
runtime.GC()
// Clean up the chapter directory after PDF creation
os.RemoveAll(chapterDir)
runtime.GC()
return pdfPath
}
func createPDFFromImages(imagePaths []string, outputPath string) error {
pdf := fpdf.New("P", "mm", "A4", "")
pageWidth, pageHeight := pdf.GetPageSize()
for _, imagePath := range imagePaths {
file, err := os.Open(imagePath)
if err != nil {
return fmt.Errorf("error opening image %s: %v", imagePath, err)
}
imgConfig, _, err := image.DecodeConfig(file)
file.Close()
if err != nil {
return fmt.Errorf("error decoding image %s: %v", imagePath, err)
}
// Calculate aspect ratios
imageRatio := float64(imgConfig.Height) / float64(imgConfig.Width)
pageRatio := pageHeight / pageWidth
// Check if image is very tall
if imageRatio > (2 * pageRatio) {
// Handle tall image (existing code)
scale := pageWidth / float64(imgConfig.Width)
scaledWidth := float64(imgConfig.Width) * scale
scaledHeight := float64(imgConfig.Height) * scale
numPages := int(math.Ceil(scaledHeight / pageHeight))
for page := 0; page < numPages; page++ {
pdf.AddPage()
pdf.SetFillColor(0, 0, 0)
pdf.Rect(0, 0, pageWidth, pageHeight, "F")
yOffset := float64(page) * pageHeight
x := (pageWidth - scaledWidth) / 2
pdf.Image(imagePath, x, -yOffset, scaledWidth, scaledHeight, false, "", 0, "")
}
} else if isWideSplitMode { // Perform only if wide split mode specified
if float64(imgConfig.Width)/pageWidth > 1.5 {
// Handling horizontally wider image by splitting it horizontally
scale := pageHeight / float64(imgConfig.Height)
scaledWidth := float64(imgConfig.Width) * scale
scaledHeight := float64(imgConfig.Height) * scale
// Determine number of splits needed based on scaled width
numSplits := int(math.Ceil(scaledWidth / pageWidth))
// Calculate the exact width each slice should cover
sliceWidth := scaledWidth / float64(numSplits)
// Image options
var opt fpdf.ImageOptions
opt.AllowNegativePosition = true
// Calculate vertical centering once
yPosition := (pageHeight - scaledHeight) / 2
// Handle each split
for split := 0; split < numSplits; split++ {
pdf.AddPage()
// Set background [black]
pdf.SetFillColor(0, 0, 0)
pdf.Rect(0, 0, pageWidth, pageHeight, "F")
// Calculate horizontal position for current split
// Use sliceWidth instead of pageWidth for more precise splitting
xOffset := float64(split) * sliceWidth
// Add image with proper positioning
pdf.ImageOptions(
imagePath,
-xOffset,
yPosition,
scaledWidth,
scaledHeight,
false,
opt,
0,
"")
}
}
} else {
// Handle normal images
pdf.AddPage()
pdf.SetFillColor(0, 0, 0)
pdf.Rect(0, 0, pageWidth, pageHeight, "F")
scaleX := pageWidth / float64(imgConfig.Width)
scaleY := pageHeight / float64(imgConfig.Height)
scale := math.Min(scaleX, scaleY)
width := float64(imgConfig.Width) * scale
height := float64(imgConfig.Height) * scale
x := (pageWidth - width) / 2
y := (pageHeight - height) / 2
pdf.Image(imagePath, x, y, width, height, false, "", 0, "")
}
}
return pdf.OutputFileAndClose(outputPath)
}
func openPDF(pdfPath string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "android":
// Use an Intent to open the PDF file in Termux
// Needs fixing, doesn't open file browser
cmd = exec.Command("termux-open", pdfPath)
case "darwin": // macOS
cmd = exec.Command("open", pdfPath)
case "windows":
// Check if SumatraPDF is available, just for me
if _, err := exec.LookPath("SumatraPDF.exe"); err == nil {
cmd = exec.Command("SumatraPDF.exe", "-view", "continuous single page", "-zoom", "fit width", pdfPath)
} else {
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", pdfPath) // Default PDF reader on Windows
}
case "linux":
// Use xdg-open to open the PDF with the default viewer on Linux
cmd = exec.Command("xdg-open", pdfPath)
default:
fmt.Println("Unsupported OS")
return
}
err := cmd.Start()
if err != nil {
fmt.Printf("Error opening PDF: %v\n", err)
}
}
func inputControls(manga MangaResult, chapters []Chapter, currentChapter Chapter) {
// Function to fetch and update the chapter title
updateChapterInfo := func(currentChapter Chapter) (string, string) {
re := regexp.MustCompile(`(chapter-)\d+$`)
newChapterNumber := strconv.Itoa(currentChapter.Number)
newCurrentChapterURL := re.ReplaceAllString(currentChapter.URL, "${1}"+newChapterNumber)
doc, err := fetchDocument(newCurrentChapterURL)
if err != nil {
fmt.Printf("Error fetching chapter images: %v\n", err)
return "", ""
}
chapterTitle := doc.Find(".panel-chapter-info-top h1").Text()
return newCurrentChapterURL, chapterTitle
}
// Function to display chapter menu
displayMenu := func(chapterTitle string, currentChapterNumber int, totalChapters int) {
fmt.Println(
bracketStyle.Render("[") +
greenStyle.Render("Chapter ") +
chapterStyleWithBG.Render(fmt.Sprintf("%d/%d", currentChapterNumber, totalChapters)) +
bracketStyle.Render("] ") +
lightMagentaWithBg.Render("▄︻デ══━一 🌟💥 ", chapterTitle, " 💥🌟"),
)
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("N") + bracketStyle.Render("]") + textStyle.Render(" Next chapter"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("P") + bracketStyle.Render("]") + textStyle.Render(" Previous chapter"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("S") + bracketStyle.Render("]") + textStyle.Render(" Select chapter"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("R") + bracketStyle.Render("]") + textStyle.Render(" Reopen current chapter"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("A") + bracketStyle.Render("]") + textStyle.Render(" Search another manga"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("BH") + bracketStyle.Render("]") + textStyle.Render(" Browse history, select to read"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("ST") + bracketStyle.Render("]") + textStyle.Render(" See stats"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("OD") + bracketStyle.Render("]") + textStyle.Render(" Open PDF dir"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("CS") + bracketStyle.Render("]") + textStyle.Render(" Toggle between content server1/2"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("D") + bracketStyle.Render("]") + textStyle.Render(" Toggle image decoding method [jpegli/normal]"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("M") + bracketStyle.Render("]") + textStyle.Render(" Toggle jpegli encoding mode [jpegli/normal]"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("WS") + bracketStyle.Render("]") + textStyle.Render(" Toggle splitting images wider than page"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("C") + bracketStyle.Render("]") + textStyle.Render(" Clear cache"))
fmt.Println(bracketStyle.Render("[") + greenStyle.Render("Q") + bracketStyle.Render("]") + textStyle.Render(" Exit"))
showCacheSize()
var jpConfig, decodeConfig, jpegliQualityConfig, widesplitConfig string
if isJPMode {
jpConfig = "Jpegli"
} else {
jpConfig = "Standard"
}
if useFancyDecoding {
decodeConfig = "Jpegli"
} else {
decodeConfig = "Standard"
}
if isWideSplitMode {
widesplitConfig = "ON"
} else {
widesplitConfig = "OFF"
}
serverConfig := servers[0]
jpegliQualityConfig = fmt.Sprintf("%d", jpegliQuality)
currentOptions := cyanColor.Render("Current options: ") +
greenStyle.Render("Server") + bracketStyle.Render("[") + chapterStyleWithBG.Render(serverConfig) + bracketStyle.Render("] ") +
greenStyle.Render("Decoding") + bracketStyle.Render("[") + chapterStyleWithBG.Render(decodeConfig) + bracketStyle.Render("] ") +
greenStyle.Render("Encode") + bracketStyle.Render("[") + chapterStyleWithBG.Render(jpConfig) + bracketStyle.Render("] ")
if isJPMode { // Only show quality options when jpegli is used
currentOptions += greenStyle.Render("Quality") + bracketStyle.Render("[") + chapterStyleWithBG.Render(jpegliQualityConfig) + bracketStyle.Render("] ")
}
currentOptions += greenStyle.Render("Wide-split") + bracketStyle.Render("[") + chapterStyleWithBG.Render(widesplitConfig) + bracketStyle.Render("] ")
fmt.Println(currentOptions)
}
// Function to handle chapter navigation
handleChapterNavigation := func(choice string, currentChapter *Chapter, chapterTitle *string) {
switch choice {
case "n":
if currentChapter.Number < len(chapters) {
*currentChapter = chapters[currentChapter.Number]
currentChapter.URL, *chapterTitle = updateChapterInfo(*currentChapter)
checkIfPDFExist(manga, *chapterTitle, cacheDir, *currentChapter)
}
case "p":
if currentChapter.Number > 1 {
*currentChapter = chapters[currentChapter.Number-2]
currentChapter.URL, *chapterTitle = updateChapterInfo(*currentChapter)
checkIfPDFExist(manga, *chapterTitle, cacheDir, *currentChapter)
}
case "s":
*currentChapter = selectChapter(chapters)
currentChapter.URL, *chapterTitle = updateChapterInfo(*currentChapter)
checkIfPDFExist(manga, *chapterTitle, cacheDir, *currentChapter)
case "r":
checkIfPDFExist(manga, *chapterTitle, cacheDir, *currentChapter)
case "a":
searchAndReadManga()
return
case "bh":
showHistoryWithFzf()
case "st":
fetchStatistics()
case "od":
checkCacheDir()
err := openDirectory(cacheDir)
if err != nil {
fmt.Println("Error opening directory:", err)
}
case "cs":
changeServerOrder()
case "d":
toggleDecodingMethod()
case "m":
isJPMode = !isJPMode
displayEncodingStatus()
case "ws":
isWideSplitMode = !isWideSplitMode
displayWideSplitStatus()
// Better to just clear cache manually from here
// rather than implementing bizarro code in clearCache()
err := os.RemoveAll(cacheDir)
if err != nil {
fmt.Printf("Error clearing cache: %v\n", err)
} else {
fmt.Println("💥💥 Cache cleared due to mode change 💥💥")
}
case "c":
clearCache()
case "q":
os.Exit(0)
default:
fmt.Println(lightCyanStyle.Render("Invalid input, please try again."))
}
}
newURL, chapterTitle := updateChapterInfo(currentChapter)
currentChapter.URL = newURL
for {
displayMenu(chapterTitle, currentChapter.Number, len(chapters))
choice := strings.ToLower(promptUser(textStyle.Render("Enter input:")))
handleChapterNavigation(choice, ¤tChapter, &chapterTitle)
}
}
// Function to display jpegli mode
func displayEncodingStatus() {
if isJPMode {
fmt.Println("✔️✔️ ⚡⚡ " + indexStyle.Render("jpegli encoding active") + " ⚡⚡ ✔️✔️")
} else {
fmt.Println("❌❌ " + indexStyle.Render("jpegli encoding deactivated") + " ❌❌")
}
}
// Function to display wide-split mode
func displayWideSplitStatus() {
if isWideSplitMode {
fmt.Println("✔️✔️ ⚡⚡ " + indexStyle.Render("Wide-split mode active") + " ⚡⚡ ✔️✔️")
} else {
fmt.Println("❌❌ " + indexStyle.Render("Wide-split mode deactivated") + " ❌❌")
}
}
func checkIfPDFExist(manga MangaResult, chapterTitle string, cacheDir string, currentChapter Chapter) {
mangaDir := filepath.Join(cacheDir, getModMangaTitle(manga.Title))
chapterTitle = sanitizeFilename(chapterTitle)
pdfFilename := fmt.Sprintf("%s.pdf", chapterTitle)
pdfPath := filepath.Join(mangaDir, pdfFilename)
// Return if PDF already exists
if _, err := os.Stat(pdfPath); err == nil {
fmt.Printf(yellowStyle.Render("PDF already exists: %s\n"), pdfPath)
openPDF(pdfPath)
} else {
// fmt.Printf(infoStyle.Render("PDF doesn't exist: %s\n", pdfPath))
openChapter(manga, currentChapter)
}
}
// Function to toggle the decoding method
func toggleDecodingMethod() {
useFancyDecoding = !useFancyDecoding // Toggle the flag
if useFancyDecoding {
fmt.Println(yellowStyle.Render("Using fancy decoding options."))
} else {
fmt.Println(yellowStyle.Render("Using standard decoding."))
}
}
// Function to change the server order based on a switch case
func changeServerOrder() {
if servers[0] == "server1" {