File: cli.go

package info (click to toggle)
miniflux 2.2.16-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,188 kB
  • sloc: xml: 4,853; javascript: 1,158; sh: 257; makefile: 161
file content (274 lines) | stat: -rw-r--r-- 8,364 bytes parent folder | download
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
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package cli // import "miniflux.app/v2/internal/cli"

import (
	"errors"
	"flag"
	"fmt"
	"io"
	"log/slog"
	"os"

	"miniflux.app/v2/internal/config"
	"miniflux.app/v2/internal/database"
	"miniflux.app/v2/internal/proxyrotator"
	"miniflux.app/v2/internal/storage"
	"miniflux.app/v2/internal/ui/static"
	"miniflux.app/v2/internal/version"
)

const (
	flagInfoHelp             = "Show build information"
	flagVersionHelp          = "Show application version"
	flagMigrateHelp          = "Run SQL migrations"
	flagFlushSessionsHelp    = "Flush all sessions (disconnect users)"
	flagCreateAdminHelp      = "Create an admin user from an interactive terminal"
	flagResetPasswordHelp    = "Reset user password"
	flagResetFeedErrorsHelp  = "Clear all feed errors for all users"
	flagDebugModeHelp        = "Show debug logs"
	flagConfigFileHelp       = "Load configuration file"
	flagConfigDumpHelp       = "Print parsed configuration values"
	flagHealthCheckHelp      = `Perform a health check on the given endpoint (the value "auto" tries to guess the health check endpoint).`
	flagRefreshFeedsHelp     = "Refresh a batch of feeds and exit"
	flagRunCleanupTasksHelp  = "Run cleanup tasks (delete old sessions and archive old entries)"
	flagExportUserFeedsHelp  = "Export user feeds (provide the username as argument)"
	flagResetNextCheckAtHelp = "Reset the next check time for all feeds"
)

// Parse parses command line arguments.
func Parse() {
	var (
		err                      error
		flagInfo                 bool
		flagVersion              bool
		flagMigrate              bool
		flagFlushSessions        bool
		flagCreateAdmin          bool
		flagResetPassword        bool
		flagResetFeedErrors      bool
		flagResetFeedNextCheckAt bool
		flagDebugMode            bool
		flagConfigFile           string
		flagConfigDump           bool
		flagHealthCheck          string
		flagRefreshFeeds         bool
		flagRunCleanupTasks      bool
		flagExportUserFeeds      string
	)

	flag.BoolVar(&flagInfo, "info", false, flagInfoHelp)
	flag.BoolVar(&flagInfo, "i", false, flagInfoHelp)
	flag.BoolVar(&flagVersion, "version", false, flagVersionHelp)
	flag.BoolVar(&flagVersion, "v", false, flagVersionHelp)
	flag.BoolVar(&flagMigrate, "migrate", false, flagMigrateHelp)
	flag.BoolVar(&flagFlushSessions, "flush-sessions", false, flagFlushSessionsHelp)
	flag.BoolVar(&flagCreateAdmin, "create-admin", false, flagCreateAdminHelp)
	flag.BoolVar(&flagResetPassword, "reset-password", false, flagResetPasswordHelp)
	flag.BoolVar(&flagResetFeedErrors, "reset-feed-errors", false, flagResetFeedErrorsHelp)
	flag.BoolVar(&flagResetFeedNextCheckAt, "reset-feed-next-check-at", false, flagResetNextCheckAtHelp)
	flag.BoolVar(&flagDebugMode, "debug", false, flagDebugModeHelp)
	flag.StringVar(&flagConfigFile, "config-file", "", flagConfigFileHelp)
	flag.StringVar(&flagConfigFile, "c", "", flagConfigFileHelp)
	flag.BoolVar(&flagConfigDump, "config-dump", false, flagConfigDumpHelp)
	flag.StringVar(&flagHealthCheck, "healthcheck", "", flagHealthCheckHelp)
	flag.BoolVar(&flagRefreshFeeds, "refresh-feeds", false, flagRefreshFeedsHelp)
	flag.BoolVar(&flagRunCleanupTasks, "run-cleanup-tasks", false, flagRunCleanupTasksHelp)
	flag.StringVar(&flagExportUserFeeds, "export-user-feeds", "", flagExportUserFeedsHelp)
	flag.Parse()

	cfg := config.NewConfigParser()

	if flagConfigFile != "" {
		config.Opts, err = cfg.ParseFile(flagConfigFile)
		if err != nil {
			printErrorAndExit(err)
		}
	}

	config.Opts, err = cfg.ParseEnvironmentVariables()
	if err != nil {
		printErrorAndExit(err)
	}

	if oauth2Provider := config.Opts.OAuth2Provider(); oauth2Provider != "" {
		if oauth2Provider != "oidc" && oauth2Provider != "google" {
			printErrorAndExit(fmt.Errorf(`unsupported OAuth2 provider: %q (Possible values are "google" or "oidc")`, oauth2Provider))
		}
	}

	if config.Opts.DisableLocalAuth() {
		switch {
		case config.Opts.OAuth2Provider() == "" && config.Opts.AuthProxyHeader() == "":
			printErrorAndExit(errors.New("DISABLE_LOCAL_AUTH is enabled but neither OAUTH2_PROVIDER nor AUTH_PROXY_HEADER is not set. Please enable at least one authentication source"))
		case config.Opts.OAuth2Provider() != "" && !config.Opts.IsOAuth2UserCreationAllowed():
			printErrorAndExit(errors.New("DISABLE_LOCAL_AUTH is enabled and an OAUTH2_PROVIDER is configured, but OAUTH2_USER_CREATION is not enabled"))
		case config.Opts.AuthProxyHeader() != "" && !config.Opts.IsAuthProxyUserCreationAllowed():
			printErrorAndExit(errors.New("DISABLE_LOCAL_AUTH is enabled and an AUTH_PROXY_HEADER is configured, but AUTH_PROXY_USER_CREATION is not enabled"))
		}
	}

	if config.Opts.AuthProxyHeader() != "" {
		if len(config.Opts.TrustedReverseProxyNetworks()) == 0 {
			printErrorAndExit(errors.New("TRUSTED_REVERSE_PROXY_NETWORKS must be configured when AUTH_PROXY_HEADER is used"))
		}
	}

	if flagConfigDump {
		fmt.Print(config.Opts)
		return
	}

	if flagDebugMode {
		config.Opts.SetLogLevel("debug")
	}

	logFile := config.Opts.LogFile()
	var logFileHandler io.Writer
	switch logFile {
	case "stdout":
		logFileHandler = os.Stdout
	case "stderr":
		logFileHandler = os.Stderr
	default:
		logFileHandler, err = os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
		if err != nil {
			printErrorAndExit(fmt.Errorf("unable to open log file: %v", err))
		}
		defer logFileHandler.(*os.File).Close()
	}

	if err := InitializeDefaultLogger(config.Opts.LogLevel(), logFileHandler, config.Opts.LogFormat(), config.Opts.LogDateTime()); err != nil {
		printErrorAndExit(err)
	}

	if flagHealthCheck != "" {
		doHealthCheck(flagHealthCheck)
		return
	}

	if flagInfo {
		info()
		return
	}

	if flagVersion {
		fmt.Println(version.Version)
		return
	}

	if config.Opts.IsDefaultDatabaseURL() {
		slog.Info("The default value for DATABASE_URL is used")
	}

	if err := static.GenerateBinaryBundles(); err != nil {
		printErrorAndExit(fmt.Errorf("unable to generate binary files bundle: %v", err))
	}

	if err := static.GenerateStylesheetsBundles(); err != nil {
		printErrorAndExit(fmt.Errorf("unable to generate stylesheets bundle: %v", err))
	}

	if err := static.GenerateJavascriptBundles(config.Opts.WebAuthn()); err != nil {
		printErrorAndExit(fmt.Errorf("unable to generate javascript bundle: %v", err))
	}

	db, err := database.NewConnectionPool(
		config.Opts.DatabaseURL(),
		config.Opts.DatabaseMinConns(),
		config.Opts.DatabaseMaxConns(),
		config.Opts.DatabaseConnectionLifetime(),
	)
	if err != nil {
		printErrorAndExit(fmt.Errorf("unable to connect to database: %v", err))
	}
	defer db.Close()

	store := storage.NewStorage(db)

	if err := store.Ping(); err != nil {
		printErrorAndExit(err)
	}

	if flagMigrate {
		if err := database.Migrate(db); err != nil {
			printErrorAndExit(err)
		}
		return
	}

	if flagResetFeedErrors {
		if err := store.ResetFeedErrors(); err != nil {
			printErrorAndExit(err)
		}
		return
	}

	if flagResetFeedNextCheckAt {
		if err := store.ResetNextCheckAt(); err != nil {
			printErrorAndExit(err)
		}
		return
	}

	if flagExportUserFeeds != "" {
		exportUserFeeds(store, flagExportUserFeeds)
		return
	}

	if flagFlushSessions {
		flushSessions(store)
		return
	}

	if flagCreateAdmin {
		createAdminUserFromInteractiveTerminal(store)
		return
	}

	if flagResetPassword {
		resetPassword(store)
		return
	}

	// Run migrations and start the daemon.
	if config.Opts.RunMigrations() {
		if err := database.Migrate(db); err != nil {
			printErrorAndExit(err)
		}
	}

	if err := database.IsSchemaUpToDate(db); err != nil {
		printErrorAndExit(err)
	}

	if config.Opts.CreateAdmin() {
		createAdminUserFromEnvironmentVariables(store)
	}

	if config.Opts.HasHTTPClientProxiesConfigured() {
		slog.Info("Initializing proxy rotation", slog.Int("proxies_count", len(config.Opts.HTTPClientProxies())))
		proxyrotator.ProxyRotatorInstance, err = proxyrotator.NewProxyRotator(config.Opts.HTTPClientProxies())
		if err != nil {
			printErrorAndExit(fmt.Errorf("unable to initialize proxy rotator: %v", err))
		}
	}

	if flagRefreshFeeds {
		refreshFeeds(store)
		return
	}

	if flagRunCleanupTasks {
		runCleanupTasks(store)
		return
	}

	startDaemon(store)
}

func printErrorAndExit(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}