-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcli_shared.go
More file actions
332 lines (300 loc) · 9.02 KB
/
Copy pathcli_shared.go
File metadata and controls
332 lines (300 loc) · 9.02 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
package main
import (
"embed"
"fmt"
"os"
"slices"
"strings"
"app/backend"
)
//go:embed build/windows/info.json
var versionInfo embed.FS
// getAppVersion returns version from embedded info.json
func getAppVersion() string {
return backend.GetVersion(versionInfo)
}
func isCLICommand(arg string) bool {
supportedCommands := []string{
"upload",
"credentials", "creds", // Support both full and short form
"help", "--help", "-h",
"version", "--version", "-v",
}
return slices.Contains(supportedCommands, arg)
}
func runCLI() {
if len(os.Args) < 2 {
printCLIHelp()
os.Exit(1)
return
}
command := os.Args[1]
switch command {
case "upload":
// Check for help flag first
if len(os.Args) > 2 && (os.Args[2] == "--help" || os.Args[2] == "-h") {
fmt.Printf("Usage: %s upload <filepath> [flags]\n", cliExecutableName)
fmt.Println("\nFlags:")
fmt.Println(" -r, --recursive Include subdirectories")
fmt.Println(" -t, --threads <n> Number of upload threads (default: 3)")
fmt.Println(" -f, --force Force upload even if file exists")
fmt.Println(" -d, --delete Delete from host after upload")
fmt.Println(" -df, --disable-filter Disable file type filtering")
fmt.Println(" --date-from-filename Set media date from filename (e.g. 20240709_182027.jpg)")
fmt.Println(" -e, --exclude <pattern> Exclude directories whose name matches pattern (e.g. @eaDir)")
fmt.Println(" -a, --album <name> Add uploaded files to album (creates if needed)")
fmt.Println(" Use 'AUTO' to create albums based on folder names")
fmt.Println(" -l, --log-level <level> Set log level: debug, info, warn, error (default: info)")
fmt.Println(" -c, --config <path> Path to config file")
return
}
if len(os.Args) < 3 {
fmt.Println("Error: filepath required")
fmt.Printf("Usage: %s upload <filepath> [flags]\n", cliExecutableName)
fmt.Printf("\nRun '%s upload --help' for more information\n", cliExecutableName)
os.Exit(1)
}
// Parse arguments
filePath := os.Args[2]
// Validate that filepath exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "Error: file or directory does not exist: %s\n", filePath)
os.Exit(1)
}
filePaths := []string{filePath}
config := cliConfig{
threads: 3,
logLevel: "info", // Default to info for CLI
}
// Parse flags
for i := 3; i < len(os.Args); i++ {
switch os.Args[i] {
case "--recursive", "-r":
config.recursive = true
case "--force", "-f":
config.forceUpload = true
case "--delete", "-d":
config.deleteFromHost = true
case "--disable-filter", "-df":
config.disableUnsupportedFilesFilter = true
case "--date-from-filename":
config.setDateFromFilename = true
case "--exclude", "-e":
if i+1 < len(os.Args) {
config.excludePattern = os.Args[i+1]
i++
}
case "--threads", "-t":
if i+1 < len(os.Args) {
_, _ = fmt.Sscanf(os.Args[i+1], "%d", &config.threads)
i++
}
case "--log-level", "-l":
if i+1 < len(os.Args) {
config.logLevel = os.Args[i+1]
i++
}
case "--config", "-c":
if i+1 < len(os.Args) {
config.configPath = os.Args[i+1]
i++
}
case "--album", "-a":
if i+1 < len(os.Args) {
config.albumName = os.Args[i+1]
i++
}
}
}
// Run upload
err := runCLIUpload(filePaths, config)
if err != nil {
fmt.Fprintf(os.Stderr, "Upload failed: %v\n", err)
os.Exit(1)
}
case "credentials", "creds":
if len(os.Args) < 3 {
fmt.Println("Error: subcommand required")
printCredentialsHelp()
os.Exit(1)
}
// Parse config flag before handling credentials
var configPath string
args := os.Args[2:]
for i := 0; i < len(args); i++ {
if args[i] == "--config" || args[i] == "-c" {
if i+1 < len(args) {
configPath = args[i+1]
// Remove config flag from args
args = append(args[:i], args[i+2:]...)
break
}
}
}
if configPath != "" {
backend.ConfigPath = configPath
}
handleCredentialsCommand(args)
case "help", "--help", "-h":
printCLIHelp()
case "version", "--version", "-v":
fmt.Printf("gotohp v%s\n", getAppVersion())
default:
fmt.Printf("Error: unknown command '%s'\n\n", command)
printCLIHelp()
os.Exit(1)
}
}
func containsSubstring(str, substr string) bool {
// Case-insensitive substring search
strLower := strings.ToLower(str)
substrLower := strings.ToLower(substr)
return strings.Contains(strLower, substrLower)
}
func printCLIHelp() {
fmt.Println("gotohp - Google Photos unofficial client")
fmt.Println()
fmt.Println("Usage:")
if cliHasGUI {
fmt.Printf(" %s Launch GUI application\n", cliExecutableName)
}
fmt.Printf(" %s <command> Run CLI command\n", cliExecutableName)
fmt.Println()
fmt.Println("Commands:")
fmt.Println(" upload <filepath> Upload a file to Google Photos")
fmt.Println(" creds Manage Google Photos credentials")
fmt.Println(" help Show this help message")
fmt.Println(" version Show version information")
fmt.Println()
fmt.Printf("Run '%s <command> --help' for more information on a command\n", cliExecutableName)
}
func printCredentialsHelp() {
fmt.Printf("Usage: %s creds <subcommand> [args]\n", cliExecutableName)
fmt.Println()
fmt.Println("Subcommands:")
fmt.Println(" add <auth-string> Add a new credential")
fmt.Println(" remove, rm <email> Remove a credential by email")
fmt.Println(" list, ls List all credentials")
fmt.Println(" set, select <email> Set active credential (supports partial matching)")
}
func handleCredentialsCommand(args []string) {
if len(args) == 0 {
printCredentialsHelp()
os.Exit(1)
}
// Load config
err := backend.LoadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
os.Exit(1)
}
configManager := &backend.ConfigManager{}
subcommand := args[0]
switch subcommand {
case "add":
if len(args) < 2 {
fmt.Println("Error: auth-string required")
fmt.Printf("Usage: %s credentials add <auth-string>\n", cliExecutableName)
os.Exit(1)
}
authString := args[1]
err := configManager.AddCredentials(authString)
if err != nil {
fmt.Fprintf(os.Stderr, "Error adding credentials: %v\n", err)
os.Exit(1)
}
fmt.Println("✓ Credentials added successfully")
case "remove", "rm":
if len(args) < 2 {
fmt.Println("Error: email required")
fmt.Printf("Usage: %s credentials remove <email>\n", cliExecutableName)
os.Exit(1)
}
email := args[1]
err := configManager.RemoveCredentials(email)
if err != nil {
fmt.Fprintf(os.Stderr, "Error removing credentials: %v\n", err)
os.Exit(1)
}
fmt.Printf("✓ Credentials for %s removed successfully\n", email)
case "list", "ls":
config := configManager.GetConfig()
if len(config.Credentials) == 0 {
fmt.Println("No credentials found")
return
}
fmt.Println("Credentials:")
for i, cred := range config.Credentials {
params, err := backend.ParseAuthString(cred)
if err != nil {
fmt.Printf(" %d. [Invalid credential]\n", i+1)
continue
}
email := params.Get("Email")
marker := " "
if email == config.Selected {
marker = "*"
}
fmt.Printf(" %s %s\n", marker, email)
}
if config.Selected != "" {
fmt.Printf("\n* = active\n")
}
fmt.Printf("\nUse 'gotohp creds set <email>' to change active account (supports partial matching)\n")
case "set", "select":
if len(args) < 2 {
fmt.Println("Error: email required")
fmt.Printf("Usage: %s creds set <email>\n", cliExecutableName)
os.Exit(1)
}
query := args[1]
config := configManager.GetConfig()
// Try to find exact match first
var matchedEmail string
for _, cred := range config.Credentials {
params, err := backend.ParseAuthString(cred)
if err != nil {
continue
}
email := params.Get("Email")
if email == query {
matchedEmail = email
break
}
}
// If no exact match, try fuzzy matching (substring match)
if matchedEmail == "" {
var candidates []string
for _, cred := range config.Credentials {
params, err := backend.ParseAuthString(cred)
if err != nil {
continue
}
email := params.Get("Email")
// Check if query is a substring of the email
if containsSubstring(email, query) {
candidates = append(candidates, email)
}
}
if len(candidates) == 0 {
fmt.Fprintf(os.Stderr, "Error: no credentials found matching '%s'\n", query)
os.Exit(1)
} else if len(candidates) == 1 {
matchedEmail = candidates[0]
} else {
fmt.Fprintf(os.Stderr, "Error: multiple credentials match '%s':\n", query)
for _, email := range candidates {
fmt.Fprintf(os.Stderr, " - %s\n", email)
}
fmt.Fprintf(os.Stderr, "Please be more specific\n")
os.Exit(1)
}
}
configManager.SetSelected(matchedEmail)
fmt.Printf("✓ Active credential set to %s\n", matchedEmail)
default:
fmt.Printf("Error: unknown subcommand '%s'\n\n", subcommand)
printCredentialsHelp()
os.Exit(1)
}
}