forked from virtualzone/onedrive-uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
287 lines (267 loc) · 7.93 KB
/
commands.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
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
package main
import (
"encoding/json"
"fmt"
"io/fs"
"io/ioutil"
"os"
"strconv"
"time"
"github.com/virtualzone/onedrive-uploader/sdk"
)
type CommandFunction func(client *sdk.Client, renderer *OutputRenderer, args []string)
type CommandFunctionDefinition struct {
Fn CommandFunction
MinArgs int
InitSecretStore bool
RequireConfig bool
}
var (
commands = map[string]*CommandFunctionDefinition{
"config": {Fn: cmdConfig, MinArgs: 0, InitSecretStore: false, RequireConfig: false},
"login": {Fn: cmdLogin, MinArgs: 0, InitSecretStore: false, RequireConfig: true},
"mkdir": {Fn: cmdCreateDir, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"upload": {Fn: cmdUpload, MinArgs: 2, InitSecretStore: true, RequireConfig: true},
"download": {Fn: cmdDownload, MinArgs: 2, InitSecretStore: true, RequireConfig: true},
"rm": {Fn: cmdDelete, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"ls": {Fn: cmdList, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"info": {Fn: cmdInfo, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"sha1": {Fn: cmdSHA1, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"sha256": {Fn: cmdSHA256, MinArgs: 1, InitSecretStore: true, RequireConfig: true},
"migrate": {Fn: cmdMigrateConfig, MinArgs: 1, InitSecretStore: false, RequireConfig: false},
"version": {Fn: cmdVersion, MinArgs: 0, InitSecretStore: false, RequireConfig: false},
}
)
func cmdConfig(client *sdk.Client, renderer *OutputRenderer, args []string) {
targetPath, err := findConfigFilePath()
if err != nil {
logError("Could not init config path: " + err.Error())
return
}
interactiveConfig := &InteractiveConfig{
TargetPath: targetPath,
}
interactiveConfig.Run()
}
func cmdMigrateConfig(client *sdk.Client, renderer *OutputRenderer, args []string) {
type secretStore struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Expiry time.Time `json:"expiry"`
}
readSecretJson := func(filename string) (*secretStore, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var config secretStore
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
return &config, nil
}
sourceConfig, err := sdk.ReadConfig(args[0])
if err != nil {
logError("Could not read source config: " + err.Error())
return
}
sourceSecret, err := readSecretJson(sourceConfig.SecretStore)
if err != nil {
logError("Could not read source secret: " + err.Error())
return
}
targetPath, err := findConfigFilePath()
if err != nil {
logError("Could not init target config: " + err.Error())
return
}
targetConfig := &sdk.Config{
ConfigFilePath: targetPath,
ClientID: sourceConfig.ClientID,
ClientSecret: sourceConfig.ClientSecret,
Scopes: sourceConfig.Scopes,
RedirectURL: sourceConfig.RedirectURL,
Root: sourceConfig.Root,
AccessToken: sourceSecret.AccessToken,
RefreshToken: sourceSecret.RefreshToken,
Expiry: sourceSecret.Expiry,
}
if err := targetConfig.Write(); err != nil {
logError("Could not write target config: " + err.Error())
return
}
log("Configuration migrated.")
}
func cmdLogin(client *sdk.Client, renderer *OutputRenderer, args []string) {
log("------------------------------------")
log("Open a browser and go to:")
print(client.GetLoginURL())
log("------------------------------------")
renderer.initSpinner("Waiting for code...")
err := client.Login()
renderer.stopSpinner()
if err != nil {
logError("Could not log in: " + err.Error())
return
}
log("Login successful.")
}
func cmdCreateDir(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Creating directory...")
err := client.CreateDir(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not create folder: " + err.Error())
return
}
log("Folder created.")
}
func cmdUpload(client *sdk.Client, renderer *OutputRenderer, args []string) {
targetFolder := args[len(args)-1]
sourceFiles := args[:len(args)-1]
numFiles := 0
for _, sourceFile := range sourceFiles {
fileStat, err := os.Stat(sourceFile)
if err != nil {
logError("Could not get stats for local file: " + err.Error())
return
}
// Skip directories
if fileStat.IsDir() {
continue
}
// Upload file
numFiles++
client.ResetChannels()
done := false
go func() {
fileStat := <-client.ChannelTransferStart
renderer.initProgressBar(fileStat.Size(), "Uploading "+fmt.Sprintf("%-20s", cutString(fileStat.Name(), 17)+"..."))
}()
go func() {
for !done {
bytes := <-client.ChannelTransferProgress
renderer.updateProgressBar(bytes)
}
}()
go func() {
done = <-client.ChannelTransferFinish
}()
err = client.Upload(sourceFile, targetFolder)
if err != nil {
logError("Could not upload file: " + err.Error())
return
}
}
if numFiles == 0 {
logError("No files for uploading specified (uploading directories is not supported)")
}
}
func cmdDownload(client *sdk.Client, renderer *OutputRenderer, args []string) {
done := false
go func() {
var fileStat fs.FileInfo = nil
for fileStat == nil {
fileStat := <-client.ChannelTransferStart
if fileStat == nil {
renderer.initSpinner("Retrieving information...")
} else {
renderer.stopSpinner()
renderer.initProgressBar(fileStat.Size(), "Downloading "+fileStat.Name()+"...")
}
}
}()
go func() {
for !done {
bytes := <-client.ChannelTransferProgress
renderer.updateProgressBar(bytes)
}
}()
go func() {
done = <-client.ChannelTransferFinish
}()
err := client.Download(args[0], args[1])
if err != nil {
logError("Could not download file: " + err.Error())
return
}
log("File downloaded.")
}
func cmdDelete(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Deleting...")
err := client.Delete(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not delete: " + err.Error())
return
}
log("Deleted.")
}
func cmdList(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Retrieving directory listing...")
list, err := client.List(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not list: " + err.Error())
return
}
for _, item := range list {
itemType := "d"
if item.File.MimeType != "" {
itemType = "f"
}
print(itemType + " " + item.Name)
}
}
func cmdInfo(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Retrieving information...")
item, err := client.Info(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not get info: " + err.Error())
return
}
itemType := "folder"
if item.Type == sdk.DriveItemTypeFile {
itemType = "file"
}
print("Type: " + itemType)
print("Size: " + strconv.FormatInt(item.SizeBytes, 10) + " bytes")
if itemType == "folder" {
print("Child Count: " + strconv.Itoa(item.Folder.ChildCount))
} else {
print("MIME Type: " + item.File.MimeType)
print("SHA1 Hash: " + item.File.Hashes.SHA1)
print("SHA256 Hash: " + item.File.Hashes.SHA256)
print("Quick XOR Hash: " + item.File.Hashes.QuickXOR)
}
}
func cmdSHA1(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Retrieving SHA1 hash...")
item, err := client.Info(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not get info: " + err.Error())
return
}
print(item.File.Hashes.SHA1)
}
func cmdSHA256(client *sdk.Client, renderer *OutputRenderer, args []string) {
renderer.initSpinner("Retrieving SHA256 hash...")
item, err := client.Info(args[0])
renderer.stopSpinner()
if err != nil {
logError("Could not get info: " + err.Error())
return
}
print(item.File.Hashes.SHA256)
}
func cmdVersion(client *sdk.Client, renderer *OutputRenderer, args []string) {
print(AppVersion)
}
func cutString(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen]
}