-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (98 loc) · 2.52 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
// main.go
//
// Copyright (c) 2023 Junpei Kawamoto
//
// This software is released under the MIT License.
//
// http://opensource.org/licenses/mit-license.php
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/blevesearch/bleve/v2"
"github.com/jkawamoto/sd-image-viewer/server"
)
const AppName = "sd-image-viewer"
const Version = "v0.2.2"
func main() {
logger := log.Default()
bleve.SetLog(logger)
cacheDir, err := os.UserCacheDir()
if err != nil {
logger.Printf("Failed to get the cache directory: %v", err)
}
host := flag.String("host", "localhost", "the IP to listen on")
port := flag.Int("port", 0, "the port to listen on for insecure connections, defaults to a random value")
indexPath := flag.String("index", filepath.Join(cacheDir, AppName), "path to the index")
duration := flag.Duration("index-duration", time.Hour, "duration of indexing")
force := flag.Bool("force", false, "force reindexing all images")
prune := flag.Bool("prune", false, "remove non exiting images from the index")
version := flag.Bool("v", false, "prints current version")
flag.Parse()
if *version {
fmt.Printf("%v %v\n", AppName, Version)
os.Exit(0)
}
if flag.NArg() == 0 {
logger.Fatalln("One directory path is required")
}
dir := flag.Arg(0)
index, created, err := newIndex(*indexPath)
if err != nil {
logger.Fatalf("Failed to create an index: %v", err)
}
if created {
// if a new index is created, force reindexing all images.
*force = true
}
defer func() {
logger.Printf("Closing the index")
if err = index.Close(); err != nil {
logger.Printf("Failed to close the index: %v", err)
}
}()
var wg sync.WaitGroup
defer wg.Wait()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg.Add(1)
go func() {
defer wg.Done()
if *prune {
err := pruneIndex(ctx, index, logger)
if errors.Is(err, context.Canceled) {
return
} else if err != nil {
logger.Printf("Failed to prune index: %v", err)
}
}
for {
err := indexDir(ctx, dir, index, *force, logger)
if errors.Is(err, context.Canceled) {
break
} else if err != nil {
logger.Printf("Failed to index files in %v: %v", dir, err)
}
*force = false
select {
case <-ctx.Done():
break
case <-time.After(*duration):
}
}
}()
s, err := server.NewServer(*host, *port, index, dir, logger)
if err != nil {
logger.Fatalf("Failed to create a server: %v", err)
}
if err = s.Serve(); err != nil {
logger.Fatalf("Failed to serve: %v", err)
}
}