-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
247 lines (203 loc) · 6.45 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
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
netHTTP "net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/autobrr/omegabrr/internal/apitoken"
"github.com/autobrr/omegabrr/internal/domain"
"github.com/autobrr/omegabrr/internal/http"
"github.com/autobrr/omegabrr/internal/processor"
"github.com/autobrr/omegabrr/internal/scheduler"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog/pkgerrors"
"github.com/spf13/pflag"
)
var (
version = "dev"
commit = ""
)
const usage = `omegabrr - Automagically turn your monitored titles from your arrs and lists into autobrr filters.
Usage:
omegabrr [command] [flags]
Commands:
arr Run omegabrr arr once
lists Run omegabrr lists once
run Run omegabrr service on schedule
generate-token Generate an API Token (optionally call with --length <number>)
version Print version info
help Show this help message
Flags:
-c, --config <path> Path to configuration file (default is $OMEGABRR_CONFIG, or config.yaml in the default user config directory)
--dry-run Dry-run without inserting filters (default false)
--length <number> Length of the generated API token (default 16)
Provide a configuration file using one of the following methods:
1. Use the --config <path> or -c <path> flag.
2. Place a config.yaml file in the default user configuration directory (e.g., ~/.config/omegabrr/).
3. Set the OMEGABRR_CONFIG environment variable.
For more information and examples, visit https://github.com/autobrr/omegabrr
` + "\n"
func init() {
pflag.Usage = func() {
fmt.Fprint(flag.CommandLine.Output(), usage)
}
}
func main() {
var configPath string
var dryRun bool
pflag.StringVarP(&configPath, "config", "c", "", "path to configuration file")
pflag.BoolVar(&dryRun, "dry-run", false, "dry-run without inserting filters")
// Define and parse flags using pflag
length := pflag.Int("length", 16, "length of the generated API token")
pflag.Parse()
if configPath == "" {
configPath = os.Getenv("OMEGABRR_CONFIG")
if configPath == "" {
userConfigDir, err := os.UserConfigDir()
if err != nil {
log.Fatal().Err(err).Msg("failed to get user config directory")
}
defaultConfigPath := filepath.Join(userConfigDir, "omegabrr", "config.yaml")
if _, err := os.Stat(defaultConfigPath); err == nil {
configPath = defaultConfigPath
}
}
}
zerolog.TimeFieldFormat = time.RFC3339
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339})
switch cmd := pflag.Arg(0); cmd {
case "version":
fmt.Printf("Version: %v\nCommit: %v\n", version, commit)
// get the latest release tag from brr-api
client := &netHTTP.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get("https://api.autobrr.com/repos/autobrr/omegabrr/releases/latest")
if err != nil {
if errors.Is(err, netHTTP.ErrHandlerTimeout) {
fmt.Println("Server timed out while fetching latest release from api")
} else {
fmt.Printf("Failed to fetch latest release from api: %v\n", err)
}
os.Exit(1)
}
defer resp.Body.Close()
// brr-api returns 500 instead of 404 here
if resp.StatusCode == netHTTP.StatusNotFound || resp.StatusCode == netHTTP.StatusInternalServerError {
fmt.Print("No release found")
os.Exit(1)
}
var rel struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
fmt.Printf("Failed to decode response from api: %v\n", err)
os.Exit(1)
}
fmt.Printf("Latest release: %v\n", rel.TagName)
case "generate-token":
key, err := apitoken.GenerateToken(*length)
if err != nil {
fmt.Fprintf(os.Stderr, "error generating API token: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "API Token: %v\nCopy and paste into your config file config.yaml\n", key)
case "arr":
cfg := domain.NewConfig(configPath)
p := processor.NewService(cfg)
ctx := context.Background()
errors := p.ProcessArrs(ctx, dryRun)
if len(errors) == 0 {
log.Info().Msg("Run complete.")
} else {
log.Warn().Msg("Run complete, with errors.")
log.Warn().Msg("Errors encountered during processing:")
for _, err := range errors {
log.Warn().Msg(err)
}
os.Exit(1)
}
case "lists":
cfg := domain.NewConfig(configPath)
p := processor.NewService(cfg)
ctx := context.Background()
errors := p.ProcessLists(ctx, dryRun)
if len(errors) == 0 {
log.Info().Msg("Run complete.")
} else {
log.Warn().Msg("Run complete, with errors.")
log.Warn().Msg("Errors encountered during processing:")
for _, err := range errors {
log.Warn().Msg(err)
}
os.Exit(1)
}
case "run":
cfg := domain.NewConfig(configPath)
log.Info().Msgf("starting omegabrr: %s", version)
log.Info().Msgf("running on schedule: %v", cfg.Schedule)
p := processor.NewService(cfg)
schedulerService := scheduler.NewService(cfg, p)
srv := http.NewServer(cfg, p)
errorChannel := make(chan error)
go func() {
errorChannel <- srv.Open()
}()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM)
schedulerService.Start()
go func() {
log.Debug().Msgf("sleeping 15 seconds before running...")
time.Sleep(15 * time.Second)
ctx := context.Background()
// Store processing errors for ProcessArrs and ProcessLists
var processingErrors []string
arrsErrors := p.ProcessArrs(ctx, false)
if len(arrsErrors) > 0 {
processingErrors = append(processingErrors, arrsErrors...)
}
listsErrors := p.ProcessLists(ctx, false)
if len(listsErrors) > 0 {
processingErrors = append(processingErrors, listsErrors...)
}
// Print the summary of potential errors
if len(processingErrors) == 0 {
log.Info().Msg("Run complete.")
} else {
log.Warn().Msg("Run complete, with errors.")
log.Warn().Msg("Errors encountered during processing:")
for _, errMsg := range processingErrors {
log.Warn().Msg(errMsg)
}
}
}()
for sig := range sigCh {
switch sig {
case syscall.SIGHUP:
log.Log().Msg("shutting down server sighup")
schedulerService.Stop()
os.Exit(0)
case syscall.SIGINT, syscall.SIGQUIT:
schedulerService.Stop()
os.Exit(0)
case syscall.SIGKILL, syscall.SIGTERM:
schedulerService.Stop()
os.Exit(0)
}
}
default:
pflag.Usage()
if cmd != "help" {
os.Exit(0)
}
}
}