From 365a7579bf833161526635acf7fd075045d88ea0 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Sat, 14 Nov 2015 20:16:30 -0800 Subject: [PATCH] share rewrite --- main.go | 2 +- share-db-v1.go | 133 ++++++++++++++++++++ share-download-main.go | 184 +++++++++++++++------------ share-list-main.go | 101 +++++++++++++++ share-list.go | 118 ----------------- share-main.go | 117 +++-------------- share-upload-main.go | 188 +++++++++++++++++----------- share-v1.go | 65 ---------- share-v2.go | 78 ------------ share-v3.go | 78 ------------ share.go | 278 +++++++++++++++++------------------------ share_test.go | 24 ++-- verify-runtime.go | 11 +- 13 files changed, 601 insertions(+), 776 deletions(-) create mode 100644 share-db-v1.go create mode 100644 share-list-main.go delete mode 100644 share-list.go delete mode 100644 share-v1.go delete mode 100644 share-v2.go delete mode 100644 share-v3.go diff --git a/main.go b/main.go index 3bd4ff38..c7d88db9 100644 --- a/main.go +++ b/main.go @@ -77,7 +77,7 @@ func migrate() { // Migrate session files if any. migrateSession() // Migrate shared urls if any. - migrateSharedURLs() + migrateShare() } // Get os/arch/platform specific information. diff --git a/share-db-v1.go b/share-db-v1.go new file mode 100644 index 00000000..7df1fd66 --- /dev/null +++ b/share-db-v1.go @@ -0,0 +1,133 @@ +/* + * Minio Client (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "os" + "sync" + "time" + + "github.com/minio/minio-xl/pkg/probe" + "github.com/minio/minio-xl/pkg/quick" +) + +type shareEntryV1 struct { + URL string `json:"share"` // Object URL. + Date time.Time `json:"date"` + Expiry time.Duration `json:"expiry"` + ContentType string `json:"contentType,omitempty"` // Only used by upload cmd. +} + +// JSON file to persist previously shared uploads. +type shareDBV1 struct { + Version string `json:"version"` + mutex *sync.Mutex + + // key is unique share URL. + Shares map[string]shareEntryV1 `json:"shares"` +} + +// Instantiate a new uploads structure for persistence. +func newShareDBV1() *shareDBV1 { + s := &shareDBV1{ + Version: "1", + } + s.Shares = make(map[string]shareEntryV1) + s.mutex = &sync.Mutex{} + return s +} + +// Set upload info for each share. +func (s *shareDBV1) Set(objectURL string, shareURL string, expiry time.Duration, contentType string) { + s.mutex.Lock() + defer s.mutex.Unlock() + + s.Shares[shareURL] = shareEntryV1{ + URL: objectURL, + Date: time.Now().UTC(), + Expiry: expiry, + ContentType: contentType, + } +} + +// Delete upload info if it exists. +func (s *shareDBV1) Delete(objectURL string) { + s.mutex.Lock() + defer s.mutex.Unlock() + + delete(s.Shares, objectURL) +} + +// Delete all expired uploads. +func (s *shareDBV1) deleteAllExpired() { + for shareURL, share := range s.Shares { + if (share.Expiry - time.Since(share.Date)) <= 0 { + // Expired entry. Safe to drop. + delete(s.Shares, shareURL) + } + } +} + +// Load shareDB entries from disk. Any entries held in memory are reset. +func (s *shareDBV1) Load(filename string) *probe.Error { + s.mutex.Lock() + defer s.mutex.Unlock() + + // Check if the db file exist. + if _, err := os.Stat(filename); err != nil { + return probe.NewError(err) + } + + // Initialize and load using quick package. + qs, err := quick.New(newShareDBV1()) + if err != nil { + return err.Trace() + } + err = qs.Load(filename) + if err != nil { + return err.Trace(filename) + } + + // Copy map over. + for k, v := range qs.Data().(*shareDBV1).Shares { + s.Shares[k] = v + } + + // Filter out expired entries and save changes back to disk. + s.deleteAllExpired() + s.save(filename) + + return nil +} + +// Persist share uploads to disk. +func (s shareDBV1) save(filename string) *probe.Error { + // Initialize a new quick file. + qs, err := quick.New(s) + if err != nil { + return err.Trace() + } + return qs.Save(filename).Trace(filename) +} + +// Persist share uploads to disk. +func (s shareDBV1) Save(filename string) *probe.Error { + s.mutex.Lock() + defer s.mutex.Unlock() + + return s.save(filename) +} diff --git a/share-download-main.go b/share-download-main.go index a0c2276a..a09a62f3 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -17,57 +17,125 @@ package main import ( - "errors" + "fmt" + "strings" "time" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/minio-xl/pkg/probe" ) // Share documents via URL. var shareDownload = cli.Command{ Name: "download", - Usage: "Generate URL to download documents.", + Usage: "Generate URLs for download access.", Action: mainShareDownload, + Flags: []cli.Flag{shareFlagExpire}, CustomHelpTemplate: `NAME: mc share {{.Name}} - {{.Usage}} USAGE: - mc share {{.Name}} download TARGET [DURATION] - - DURATION = NN[h|m|s] [DEFAULT=168h] + mc share {{.Name}} [OPTIONS] TARGET + OPTIONS: + {{range .Flags}}{{.}} + {{end}} EXAMPLES: 1. Generate URL for sharing, with a default expiry of 7 days. $ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz 2. Generate URL for sharing, with an expiry of 10 minutes. - $ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz 10m - - 3. Generate list of URLs for sharing a folder recursively, with expiration of 5 days each. - $ mc share {{.Name}} https://s3.amazonaws.com/backup... 120h - - 4. Generate URL with space characters for sharing, with an expiry of 5 seconds. - $ mc share {{.Name}} s3/miniocloud/nothing-like-anything 5s + $ mc share {{.Name}} --expire=10m https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz + 3. Generate list of URLs for sharing a folder recursively, with an expiry of 5 days each. + $ mc share {{.Name}} --expire=120h https://s3.amazonaws.com/backup... `, } +// checkShareDownloadSyntax - validate command-line args. func checkShareDownloadSyntax(ctx *cli.Context) { args := ctx.Args() - if !args.Present() || args.First() == "help" { - cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code + if !args.Present() { + cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code. } - if len(args) > 2 { - cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code + + if !isURLRecursive(args.First()) { + url := stripRecursiveURL(args.First()) + if strings.HasSuffix(url, "/") { + fatalIf(errDummy().Trace(), fmt.Sprintf("To grant access to an entire folder, you may use ‘%s’.", url+recursiveSeparator)) + } } + + // Parse expiry. + expiry := shareDefaultExpiry + expireArg := ctx.String("expire") + if expireArg != "" { + var e error + expiry, e = time.ParseDuration(expireArg) + fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") + } + + // Validate expiry. + if expiry.Seconds() < 1 { + fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") + } + if expiry.Seconds() > 604800 { + fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") + } +} + +// doShareURL share files from target +func doShareDownloadURL(targetURL string, recursive bool, expiry time.Duration) *probe.Error { + clnt, err := url2Client(targetURL) + if err != nil { + return err.Trace() + } + + // Load previously saved upload-shares. Add new entries and write it back. + shareDB := newShareDBV1() + err = shareDB.Load(getShareDownloadsFile()) + if err != nil { + return err.Trace() + } + + // Generate share URL for each target. + incomplete := false + for content := range clnt.List(recursive, incomplete) { + if content.Err != nil { + return content.Err.Trace() + } + + objectURL := content.Content.URL.String() + newClnt, err := url2Client(objectURL) + if err != nil { + return err.Trace() + } + + // Generate share URL. + shareURL, err := newClnt.ShareDownload(expiry) + if err != nil { + return err.Trace() + } + + // Make new entries to shareDB. + contentType := "" // Not useful for download shares. + shareDB.Set(objectURL, shareURL, expiry, contentType) + printMsg(shareMesssage{ + ObjectURL: objectURL, + ShareURL: shareURL, + TimeLeft: expiry, + ContentType: contentType, + }) + } + + // Save downloads and return. + return shareDB.Save(getShareDownloadsFile()) } // main for share download. func mainShareDownload(ctx *cli.Context) { - // setup share data folder and file. - shareDataSetup() + // Initialize share config folder. + initShareConfig() // Additional command speific theme customization. shareSetColor() @@ -75,72 +143,22 @@ func mainShareDownload(ctx *cli.Context) { // check input arguments. checkShareDownloadSyntax(ctx) - args := ctx.Args() + // Extract arguments. config := mustGetMcConfig() - url := args.Get(0) - // default expiration is 7days - expires := time.Duration(604800) * time.Second - if len(args) == 2 { - var err error - expires, err = time.ParseDuration(args.Get(1)) - fatalIf(probe.NewError(err), "Unable to parse time argument.") + args := ctx.Args() + url := stripRecursiveURL(args.First()) + isRecursive := isURLRecursive(args.First()) + expiry := shareDefaultExpiry + expireArg := ctx.String("expire") + if expireArg != "" { + var e error + expiry, e = time.ParseDuration(expireArg) + fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") } - targetURL := getAliasURL(url, config.Aliases) + targetURL := getAliasURL(stripRecursiveURL(url), config.Aliases) // Expand alias. + // if recursive strip off the "..." - err := doShareDownloadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires) - fatalIf(err.Trace(targetURL), "Unable to generate URL for download.") - return -} - -// doShareURL share files from target -func doShareDownloadURL(targetURL string, recursive bool, expires time.Duration) *probe.Error { - shareDate := time.Now().UTC() - sURLs, err := loadSharedURLsV3() - if err != nil { - return err.Trace() - } - var clnt client.Client - clnt, err = url2Client(targetURL) - if err != nil { - return err.Trace() - } - if expires.Seconds() < 1 { - return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second.")) - } - if expires.Seconds() > 604800 { - return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days.")) - } - for contentCh := range clnt.List(recursive, false) { - if contentCh.Err != nil { - return contentCh.Err.Trace() - } - var newClnt client.Client - newClnt, err = url2Client(contentCh.Content.URL.String()) - if err != nil { - return err.Trace() - } - var sharedURL string - sharedURL, err = newClnt.ShareDownload(expires) - if err != nil { - return err.Trace() - } - var shareMsg interface{} - shareMsg = shareMessage{ - Expiry: expires, - DownloadURL: sharedURL, - Key: newClnt.GetURL().String(), - } - shareMsgV3 := shareMessageV3(shareMsg.(shareMessage)) - sURLs.URLs = append(sURLs.URLs, struct { - Date time.Time - Message shareMessageV3 - }{ - Date: shareDate, - Message: shareMsgV3, - }) - printMsg(shareMsg.(shareMessage)) - } - saveSharedURLsV3(sURLs) - return nil + err := doShareDownloadURL(stripRecursiveURL(targetURL), isRecursive, expiry) + fatalIf(err.Trace(targetURL), "Unable to share target ‘"+args.First()+"’.") } diff --git a/share-list-main.go b/share-list-main.go new file mode 100644 index 00000000..6387f7c2 --- /dev/null +++ b/share-list-main.go @@ -0,0 +1,101 @@ +/* + * Minio Client (C) 2014, 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + "fmt" + "time" + + "github.com/minio/cli" + "github.com/minio/minio-xl/pkg/probe" +) + +// Share documents via URL. +var shareList = cli.Command{ + Name: "list", + Usage: "List previously shared objects and folders.", + Action: mainShareList, + CustomHelpTemplate: `NAME: + mc share {{.Name}} COMMAND - {{.Usage}} +COMMAND: + upload: list previously shared access to uploads. + download: list previously shared access to downloads. + +USAGE: + mc share {{.Name}} + +EXAMPLES: + 1. List previously shared downloads, that haven't expired yet. + $ mc share {{.Name}} download + 2. List previously shared uploads, that haven't expired yet. + $ mc share {{.Name}} upload +`, +} + +// validate command-line args. +func checkShareListSyntax(ctx *cli.Context) { + args := ctx.Args() + if !args.Present() || (args.First() != "upload" && args.First() != "download") { + cli.ShowCommandHelpAndExit(ctx, "list", 1) // last argument is exit code. + } +} + +// doShareList list shared url's. +func doShareList(cmd string) *probe.Error { + // Load previously saved upload-shares. + shareDB := newShareDBV1() + switch cmd { + case "upload": + err := shareDB.Load(getShareUploadsFile()) + if err != nil { + return err.Trace(getShareUploadsFile()) + } + case "download": + err := shareDB.Load(getShareDownloadsFile()) + if err != nil { + return err.Trace(getShareDownloadsFile()) + } + default: + return probe.NewError(fmt.Errorf("Unknown argument ‘%s’ passed.", cmd)) + } + + // Print previously shared entries. + for shareURL, share := range shareDB.Shares { + printMsg(shareMesssage{ + ObjectURL: share.URL, + ShareURL: shareURL, + TimeLeft: share.Expiry - time.Since(share.Date), + ContentType: share.ContentType, + }) + } + return nil +} + +// main entry point for share list. +func mainShareList(ctx *cli.Context) { + // validate command-line args. + checkShareListSyntax(ctx) + + // Additional command speific theme customization. + shareSetColor() + + // Initialize share config folder. + initShareConfig() + + // List shares. + fatalIf(doShareList(ctx.Args().First()).Trace(), "Unable to list previously shared URLs.") +} diff --git a/share-list.go b/share-list.go deleted file mode 100644 index 497ec762..00000000 --- a/share-list.go +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Minio Client (C) 2014, 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "encoding/json" - "time" - - "github.com/minio/cli" - "github.com/minio/mc/pkg/console" - "github.com/minio/minio-xl/pkg/probe" -) - -// Share documents via URL. -var shareList = cli.Command{ - Name: "list", - Usage: "List the shared URLs", - Action: mainShareList, - CustomHelpTemplate: `NAME: - mc share {{.Name}} - {{.Usage}} - -USAGE: - mc share {{.Name}} - -EXAMPLES: - $ mc share {{.Name}} - -`, -} - -// doShareList list shared url's. -func doShareList() *probe.Error { - sURLs, err := loadSharedURLsV3() - if err != nil { - return err.Trace() - } - saveList := newSharedURLsV3() - for _, data := range sURLs.URLs { - if time.Since(data.Date) > data.Message.Expiry { - continue - } - saveList.URLs = append(saveList.URLs, data) - expiry := data.Message.Expiry - time.Since(data.Date) - if !globalJSONFlag { - var kind string - if len(data.Message.DownloadURL) > 0 { - kind = "Download" - } else { - kind = "Upload" - } - msg := console.Colorize("Share", "Name: ") - msg += console.Colorize("URL", data.Message.Key+" ("+kind+")\n") - msg += console.Colorize("Share", "Expiry: ") - msg += console.Colorize("Expires", timeDurationToHumanizedTime(expiry)) - msg += "\n" - console.Println(msg) - continue - } - var shareMessageBytes []byte - var err error - s := data.Message - if len(s.DownloadURL) > 0 { - shareMessageBytes, err = json.Marshal(struct { - Expiry humanizedTime `json:"expiry"` - DownloadURL string `json:"downloadUrl"` - Key string `json:"keyName"` - }{ - Expiry: timeDurationToHumanizedTime(s.Expiry), - DownloadURL: s.DownloadURL, - Key: s.Key, - }) - } else { - shareMessageBytes, err = json.Marshal(struct { - Expiry humanizedTime `json:"expiry"` - UploadInfo map[string]string `json:"uploadInfo"` - Key string `json:"keyName"` - }{ - Expiry: timeDurationToHumanizedTime(s.Expiry), - UploadInfo: s.UploadInfo, - Key: s.Key, - }) - } - if err != nil { - return probe.NewError(err) - } - console.Println(string(shareMessageBytes)) - } - if err := saveSharedURLsV3(saveList); err != nil { - return err.Trace() - } - return nil -} - -// main for share list. -func mainShareList(ctx *cli.Context) { - // setup share data folder and file. - shareDataSetup() - - // Additional command speific theme customization. - shareSetColor() - - err := doShareList() - fatalIf(err.Trace(), "Unable to list shared URLs.") -} diff --git a/share-main.go b/share-main.go index 7a75dedf..c95185c0 100644 --- a/share-main.go +++ b/share-main.go @@ -17,14 +17,10 @@ package main import ( - "bytes" - "encoding/json" - "fmt" - "strings" - "time" + "os" + "path/filepath" "github.com/minio/cli" - "github.com/minio/mc/pkg/client" "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" ) @@ -32,7 +28,7 @@ import ( // Share documents via URL. var shareCmd = cli.Command{ Name: "share", - Usage: "Download and upload documents.", + Usage: "Generate URL for sharing.", Action: mainShare, Subcommands: []cli.Command{ shareDownload, @@ -51,104 +47,21 @@ COMMANDS: `, } -// structured share command messages version '1' -type shareMessageV1 struct { - Expiry time.Duration `json:"expiry"` - URL string `json:"url"` - Key string `json:"keyName"` -} +// migrateShare migrate to newest version sequentially +func migrateShare() { -// structured share command messages version '2' -type shareMessageV2 shareMessageV1 - -// structured share command messages version '3' -type shareMessageV3 struct { - Expiry time.Duration `json:"expiry"` - DownloadURL string `json:"downloadUrl,omitempty"` - UploadInfo map[string]string `json:"uploadInfo,omitempty"` - Key string `json:"keyName"` -} - -// shareMessage this points to latest share command message structure. -type shareMessage shareMessageV3 - -// String - regular colorized message -func (s shareMessage) String() string { - if len(s.DownloadURL) > 0 { - return console.Colorize("Share", fmt.Sprintf("%s", s.DownloadURL)) - } - var key string - URL := client.NewURL(s.Key) - postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) - if !isBucketVirtualStyle(URL.Host) { - postURL = postURL + s.UploadInfo["bucket"] - } - postURL = postURL + " " - curlCommand := "curl " + postURL - for k, v := range s.UploadInfo { - if k == "key" { - key = v - continue - } - curlCommand = curlCommand + fmt.Sprintf("-F %s=%s ", k, v) - } - curlCommand = curlCommand + fmt.Sprintf("-F key=%s ", key) + "-F file=@ " - emphasize := console.Colorize("File", "") - curlCommand = strings.Replace(curlCommand, "", emphasize, -1) - return console.Colorize("Share", fmt.Sprintf("%s", curlCommand)) -} - -// JSON json message for share command -func (s shareMessage) JSON() string { - var shareMessageBytes []byte - var err error - if len(s.DownloadURL) > 0 { - shareMessageBytes, err = json.Marshal(struct { - Expiry humanizedTime `json:"expiry"` - DownloadURL string `json:"downloadUrl"` - Key string `json:"keyName"` - }{ - Expiry: timeDurationToHumanizedTime(s.Expiry), - DownloadURL: s.DownloadURL, - Key: s.Key, - }) - } else { - var key string - URL := client.NewURL(s.Key) - postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) - if !isBucketVirtualStyle(URL.Host) { - postURL = postURL + s.UploadInfo["bucket"] - } - postURL = postURL + " " - curlCommand := "curl " + postURL - for k, v := range s.UploadInfo { - if k == "key" { - key = v - continue - } - curlCommand = curlCommand + fmt.Sprintf("-F %s=%s ", k, v) - } - curlCommand = curlCommand + fmt.Sprintf("-F key=%s ", key) + "-F file=@ " - - shareMessageBytes, err = json.Marshal(struct { - Expiry humanizedTime `json:"expiry"` - UploadCommand string `json:"uploadCommand"` - Key string `json:"keyName"` - }{ - Expiry: timeDurationToHumanizedTime(s.Expiry), - UploadCommand: curlCommand, - Key: s.Key, - }) + if !isShareDirExists() { + return } - fatalIf(probe.NewError(err), "Failed to marshal into JSON.") - - // json encoding escapes ampersand into its unicode character which is not usable directly for share - // and fails with cloud storage. convert them back so that they are usable - shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1) - shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1) - shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1) - return string(shareMessageBytes) + // Shared URLs are now managed by sub-commands. So delete any old URLs file if found. + oldShareFile := filepath.Join(mustGetShareDir(), "urls.json") + if _, e := os.Stat(oldShareFile); e == nil { + // Old file exits. + e := os.Remove(oldShareFile) + fatalIf(probe.NewError(e), "Unable to delete old ‘"+oldShareFile+"’.") + console.Infof("Removed older version of share ‘%s’ file.\n", oldShareFile) + } } // mainShare - main handler for mc share command diff --git a/share-upload-main.go b/share-upload-main.go index 631df60f..7b9dc07e 100644 --- a/share-upload-main.go +++ b/share-upload-main.go @@ -22,57 +22,137 @@ import ( "time" "github.com/minio/cli" + "github.com/minio/mc/pkg/client" + "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" ) // Share documents via URL. var shareUpload = cli.Command{ Name: "upload", - Usage: "Generate ‘curl’ command to upload files.", + Usage: "Generate ‘curl’ command to upload objects without requiring access/secret keys.", Action: mainShareUpload, + Flags: []cli.Flag{shareFlagExpire, shareFlagContentType}, CustomHelpTemplate: `NAME: mc share {{.Name}} - {{.Usage}} USAGE: - mc share {{.Name}} TARGET [DURATION] [Content-Type] - - DURATION = NN[h|m|s] [DEFAULT=168h] + mc share {{.Name}} [OPTIONS] TARGET +OPTIONS: + {{range .Flags}}{{.}} + {{end}} EXAMPLES: - 1. Generate Curl upload command, with a default expiry of 7 days. + 1. Generate a curl command to allow upload access for a single object. Command expires after 7 days (default). $ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz - 2. Generate Curl upload command to upload files to a folder, with expiry of 120 hours - $ mc share {{.Name}} https://s3.amazonaws.com/backup/2007-Mar-2/... 120h - - 3. Generate Curl upload command to upload with expiry of 2 hours with content-type image/png - $ mc share {{.Name}} https://s3.amazonaws.com/backup/2007-Mar-2/... 2h image/png + 2. Generate a curl command to allow upload access to a folder. Command expires in 120 hours. + $ mc share {{.Name}} --expire=120h https://s3.amazonaws.com/backup/2007-Mar-2/... + 3. Generate a curl command to allow upload access of only '.png' images to a folder. Command expires in 2 hours. + $ mc share {{.Name}} --expire=2h --content-type=image/png https://s3.amazonaws.com/backup/2007-Mar-2/... `, } -// checkShareUploadSyntaxt - check share upload command arguments +// checkShareUploadSyntax - validate command-line args. func checkShareUploadSyntax(ctx *cli.Context) { args := ctx.Args() - if !args.Present() || args.First() == "help" { - cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code + if !args.Present() { + cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code. } - if len(args) > 3 { - cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code + + if !isURLRecursive(args.First()) { + url := stripRecursiveURL(args.First()) + if strings.HasSuffix(url, "/") { + fatalIf(errDummy().Trace(), fmt.Sprintf("To grant access to an entire folder, you may use ‘%s’.", url+recursiveSeparator)) + } } - url := stripRecursiveURL(strings.TrimSpace(args.Get(0))) - if !isObjectKeyPresent(url) { - fatalIf(errDummy().Trace(), fmt.Sprintf("Upload location needs object key ‘%s’.", strings.TrimSpace(args.Get(0)))) + + // Parse expiry. + expireArg := ctx.String("expire") + expiry := shareDefaultExpiry + if expireArg != "" { + var e error + expiry, e = time.ParseDuration(expireArg) + fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") } - if strings.HasSuffix(strings.TrimSpace(args.Get(0)), "/") { - fatalIf(errDummy().Trace(), fmt.Sprintf("Upload location cannot end with ‘/’. Did you mean ‘%s’.", url+recursiveSeparator)) + + // Validate expiry. + if expiry.Seconds() < 1 { + fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be lesser than 1 second.") } + if expiry.Seconds() > 604800 { + fatalIf(errDummy().Trace(expiry.String()), "Expiry cannot be larger than 7 days.") + } +} + +// makeCurlCmd constructs curl command-line. +func makeCurlCmd(key string, uploadInfo map[string]string) string { + URL := client.NewURL(key) + postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) + if !isBucketVirtualStyle(URL.Host) { + postURL = postURL + uploadInfo["bucket"] + } + postURL = postURL + " " + curlCommand := "curl " + postURL + for k, v := range uploadInfo { + if k == "key" { + key = v + continue + } + curlCommand = curlCommand + fmt.Sprintf("-F %s=%s ", k, v) + } + curlCommand = curlCommand + fmt.Sprintf("-F key=%s ", key) + "-F file=@ " + emphasize := console.Colorize("File", "") + return strings.Replace(curlCommand, "", emphasize, -1) +} + +// save shared URL to disk. +func saveSharedURL(objectURL string, shareURL string, expiry time.Duration, contentType string) *probe.Error { + // Load previously saved upload-shares. + shareDB := newShareDBV1() + if err := shareDB.Load(getShareUploadsFile()); err != nil { + return err.Trace(getShareUploadsFile()) + } + + // Make new entries to uploadsDB. + shareDB.Set(objectURL, shareURL, expiry, contentType) + shareDB.Save(getShareUploadsFile()) + + return nil +} + +// doShareUploadURL uploads files to the target. +func doShareUploadURL(objectURL string, recursive bool, expiry time.Duration, contentType string) *probe.Error { + clnt, err := url2Client(objectURL) + if err != nil { + return err.Trace() + } + + // Generate pre-signed access info. + uploadInfo, err := clnt.ShareUpload(recursive, expiry, contentType) + if err != nil { + return err.Trace() + } + + // Generate curl command. + curlCmd := makeCurlCmd(objectURL, uploadInfo) + + printMsg(shareMesssage{ + ObjectURL: objectURL, + ShareURL: curlCmd, + TimeLeft: expiry, + ContentType: contentType, + }) + + // save shared URL to disk. + return saveSharedURL(objectURL, curlCmd, expiry, contentType) } // main for share upload command. func mainShareUpload(ctx *cli.Context) { - // setup share data folder and file. - shareDataSetup() + // Initialize share config folder. + initShareConfig() // Additional command speific theme customization. shareSetColor() @@ -80,61 +160,21 @@ func mainShareUpload(ctx *cli.Context) { // check input arguments. checkShareUploadSyntax(ctx) - var expires time.Duration - var err error args := ctx.Args() config := mustGetMcConfig() - if strings.TrimSpace(args.Get(1)) == "" { - expires = time.Duration(604800) * time.Second - } else { - expires, err = time.ParseDuration(strings.TrimSpace(args.Get(1))) - if err != nil { - fatalIf(probe.NewError(err), "Unable to parse time argument.") - } - } - contentType := strings.TrimSpace(args.Get(2)) - targetURL := getAliasURL(strings.TrimSpace(args.Get(0)), config.Aliases) + url := stripRecursiveURL(args.First()) + isRecursive := isURLRecursive(args.First()) + expireArg := ctx.String("expire") + expiry := shareDefaultExpiry + contentType := ctx.String("content-type") - e := doShareUploadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires, contentType) - fatalIf(e.Trace(targetURL), "Unable to generate URL for upload.") -} - -// doShareUploadURL uploads files to the target. -func doShareUploadURL(targetURL string, recursive bool, expires time.Duration, contentType string) *probe.Error { - shareDate := time.Now().UTC() - sURLs, err := loadSharedURLsV3() - if err != nil { - return err.Trace() + if expireArg != "" { + var e error + expiry, e = time.ParseDuration(expireArg) + fatalIf(probe.NewError(e), "Unable to parse expire=‘"+expireArg+"’.") } - clnt, err := url2Client(targetURL) - if err != nil { - return err.Trace() - } - m, err := clnt.ShareUpload(recursive, expires, contentType) - if err != nil { - return err.Trace() - } - Key := targetURL - if recursive { - Key = Key + recursiveSeparator - m["key"] = m["key"] + "" - } - var shareMsg interface{} - shareMsg = shareMessage{ - Expiry: expires, - UploadInfo: m, - Key: Key, - } - shareMsgV3 := shareMessageV3(shareMsg.(shareMessage)) - sURLs.URLs = append(sURLs.URLs, struct { - Date time.Time - Message shareMessageV3 - }{ - Date: shareDate, - Message: shareMsgV3, - }) - printMsg(shareMsg.(shareMessage)) - saveSharedURLsV3(sURLs) - return nil + targetURL := getAliasURL(url, config.Aliases) + err := doShareUploadURL(targetURL, isRecursive, expiry, contentType) + fatalIf(err.Trace(targetURL), "Unable to generate curl command for upload.") } diff --git a/share-v1.go b/share-v1.go deleted file mode 100644 index d8c1b101..00000000 --- a/share-v1.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Minio Client (C) 2014, 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "os" - "time" - - "github.com/minio/minio-xl/pkg/probe" - "github.com/minio/minio-xl/pkg/quick" -) - -type sharedURLsV1 struct { - Version string - URLs map[string]struct { - Date time.Time - Message shareMessageV1 - } -} - -func loadSharedURLsV1() (*sharedURLsV1, *probe.Error) { - sharedURLsDataFile, err := getSharedURLsDataFile() - if err != nil { - return nil, err.Trace() - } - if _, err := os.Stat(sharedURLsDataFile); err != nil { - return nil, probe.NewError(err) - } - - qs, err := quick.New(newSharedURLsV1()) - if err != nil { - return nil, err.Trace() - } - err = qs.Load(sharedURLsDataFile) - if err != nil { - return nil, err.Trace(sharedURLsDataFile) - } - s := qs.Data().(*sharedURLsV1) - return s, nil -} - -func newSharedURLsV1() *sharedURLsV1 { - s := &sharedURLsV1{ - Version: "1.0.0", - URLs: make(map[string]struct { - Date time.Time - Message shareMessageV1 - }), - } - return s -} diff --git a/share-v2.go b/share-v2.go deleted file mode 100644 index 59fe3646..00000000 --- a/share-v2.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Minio Client (C) 2014, 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "os" - "time" - - "github.com/minio/minio-xl/pkg/probe" - "github.com/minio/minio-xl/pkg/quick" -) - -type sharedURLsV2 struct { - Version string - URLs []struct { - Date time.Time - Message shareMessageV2 - } -} - -func loadSharedURLsV2() (*sharedURLsV2, *probe.Error) { - sharedURLsDataFile, err := getSharedURLsDataFile() - if err != nil { - return nil, err.Trace() - } - if _, err := os.Stat(sharedURLsDataFile); err != nil { - return nil, probe.NewError(err) - } - - qs, err := quick.New(newSharedURLsV2()) - if err != nil { - return nil, err.Trace() - } - err = qs.Load(sharedURLsDataFile) - if err != nil { - return nil, err.Trace(sharedURLsDataFile) - } - s := qs.Data().(*sharedURLsV2) - return s, nil -} - -func saveSharedURLsV2(s *sharedURLsV2) *probe.Error { - qs, err := quick.New(s) - if err != nil { - return err.Trace() - } - sharedURLsDataFile, err := getSharedURLsDataFile() - if err != nil { - return err.Trace() - } - return qs.Save(sharedURLsDataFile).Trace(sharedURLsDataFile) -} - -func newSharedURLsV2() *sharedURLsV2 { - var urls []struct { - Date time.Time - Message shareMessageV2 - } - s := &sharedURLsV2{ - Version: "1.1.0", - URLs: urls, - } - return s -} diff --git a/share-v3.go b/share-v3.go deleted file mode 100644 index a086e653..00000000 --- a/share-v3.go +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Minio Client (C) 2014, 2015 Minio, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package main - -import ( - "os" - "time" - - "github.com/minio/minio-xl/pkg/probe" - "github.com/minio/minio-xl/pkg/quick" -) - -type sharedURLsV3 struct { - Version string - URLs []struct { - Date time.Time - Message shareMessageV3 - } -} - -func loadSharedURLsV3() (*sharedURLsV3, *probe.Error) { - sharedURLsDataFile, err := getSharedURLsDataFile() - if err != nil { - return nil, err.Trace() - } - if _, err := os.Stat(sharedURLsDataFile); err != nil { - return nil, probe.NewError(err) - } - - qs, err := quick.New(newSharedURLsV3()) - if err != nil { - return nil, err.Trace() - } - err = qs.Load(sharedURLsDataFile) - if err != nil { - return nil, err.Trace(sharedURLsDataFile) - } - s := qs.Data().(*sharedURLsV3) - return s, nil -} - -func saveSharedURLsV3(s *sharedURLsV3) *probe.Error { - qs, err := quick.New(s) - if err != nil { - return err.Trace() - } - sharedURLsDataFile, err := getSharedURLsDataFile() - if err != nil { - return err.Trace() - } - return qs.Save(sharedURLsDataFile).Trace(sharedURLsDataFile) -} - -func newSharedURLsV3() *sharedURLsV3 { - var urls []struct { - Date time.Time - Message shareMessageV3 - } - s := &sharedURLsV3{ - Version: "3", - URLs: urls, - } - return s -} diff --git a/share.go b/share.go index 2ef6a9c1..063e2f59 100644 --- a/share.go +++ b/share.go @@ -17,133 +17,86 @@ package main import ( + "bytes" "encoding/json" + "fmt" "os" "path/filepath" - "strings" "time" "github.com/fatih/color" - "github.com/minio/mc/pkg/client" + "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" - "github.com/minio/minio-xl/pkg/quick" ) +const ( + // Default expiry is 7 days (168h) + shareDefaultExpiry = time.Duration(604800) * time.Second +) + +// Upload specific flags. +var ( + shareFlagContentType = cli.StringFlag{ + Name: "content-type, T", + Usage: "Speific content-type to allow.", + } + + shareFlagExpire = cli.StringFlag{ + Name: "expire, E", + Value: "168h", + Usage: "Set expiry in NN[h|m|s].", + } +) + +// Structured share command message. +type shareMesssage struct { + ObjectURL string `json:"url"` + ShareURL string `json:"share"` + TimeLeft time.Duration `json:"timeLeft"` + ContentType string `json:"contentType,omitempty"` // Only used by upload cmd. +} + +// String - Themefied string message for console printing. +func (s shareMesssage) String() string { + msg := console.Colorize("URL", fmt.Sprintf("URL: %s\n", s.ObjectURL)) + msg += console.Colorize("Expire", fmt.Sprintf("Expire: %s\n", timeDurationToHumanizedTime(s.TimeLeft))) + if s.ContentType != "" { + msg += console.Colorize("Content-type", fmt.Sprintf("Content-Type: %s\n", s.ContentType)) + } + msg += console.Colorize("Share", fmt.Sprintf("Share: %s\n", s.ShareURL)) + + return msg // + "\n" // Separate each entry with a new-line. +} + +// JSON - JSONified message for scripting. +func (s shareMesssage) JSON() string { + shareMessageBytes, e := json.Marshal(s) + fatalIf(probe.NewError(e), "Failed to marshal into JSON.") + + /*JSON encoding escapes ampersand into its unicode character + which is not usable directly for share and fails with cloud + storage. convert them back so that they are usable. */ + shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u0026"), []byte("&"), -1) + shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003c"), []byte("<"), -1) + shareMessageBytes = bytes.Replace(shareMessageBytes, []byte("\\u003e"), []byte(">"), -1) + + return string(shareMessageBytes) +} + // shareSetColor sets colors share sub-commands. func shareSetColor() { // Additional command speific theme customization. - console.SetColor("Share", color.New(color.FgGreen, color.Bold)) - console.SetColor("Expires", color.New(color.FgRed, color.Bold)) - console.SetColor("URL", color.New(color.FgCyan, color.Bold)) + console.SetColor("URL", color.New(color.FgWhite, color.Bold)) + console.SetColor("Expire", color.New(color.FgCyan)) + console.SetColor("Content-type", color.New(color.FgBlue)) + console.SetColor("Share", color.New(color.FgGreen)) console.SetColor("File", color.New(color.FgRed, color.Bold)) + } -// create shared data folder and file if they doesn't exist. -func shareDataSetup() { - if !isSharedURLsDataDirExists() { - shareDir, err := getSharedURLsDataDir() - fatalIf(err.Trace(), "Unable to get shared URL data folder.") - - fatalIf(createSharedURLsDataDir().Trace(), "Unable to create shared URL data folder ‘"+shareDir+"’.") - console.Infof("Successfully created ‘%s’ \n", shareDir) - } - if !isSharedURLsDataFileExists() { - shareFile, err := getSharedURLsDataFile() - fatalIf(err.Trace(), "Unable to get shared URL data file") - - fatalIf(createSharedURLsDataFile().Trace(), "Unable to create shared URL data file ‘"+shareFile+"’.") - console.Infof("Successfully created ‘%s’ \n", shareFile) - } -} - -// migrateSharedURLs migrate to newest version sequentially -func migrateSharedURLs() { - migrateSharedURLsV1ToV2() - migrateSharedURLsV2ToV3() -} - -func migrateSharedURLsV1ToV2() { - if !isSharedURLsDataFileExists() { - return - } - // try to load latest version if possible - sURLsV2, err := loadSharedURLsV2() - if err != nil { - switch err.ToGoError().(type) { - case *json.UnmarshalTypeError: - // try to load V1 if possible - var sURLsV1 *sharedURLsV1 - sURLsV1, err = loadSharedURLsV1() - fatalIf(err.Trace(), "Unable to load shared url version ‘1.0.0’.") - if sURLsV1.Version != "1.0.0" { - fatalIf(errDummy().Trace(), "Invalid version loaded ‘"+sURLsV1.Version+"’.") - } - sURLsV2 = newSharedURLsV2() - for key, value := range sURLsV1.URLs { - value.Message.Key = key - entry := struct { - Date time.Time - Message shareMessageV2 - }{ - Date: value.Date, - Message: shareMessageV2{ - Expiry: value.Message.Expiry, - URL: value.Message.URL, - Key: value.Message.Key, - }, - } - sURLsV2.URLs = append(sURLsV2.URLs, entry) - } - err = saveSharedURLsV2(sURLsV2) - fatalIf(err.Trace(), "Unable to save new shared url version ‘1.1.0’.") - default: - fatalIf(err.Trace(), "Unable to load shared url version ‘1.1.0’.") - } - } -} - -func migrateSharedURLsV2ToV3() { - if !isSharedURLsDataFileExists() { - return - } - conffile, err := getSharedURLsDataFile() - if err != nil { - return - } - v3, err := quick.CheckVersion(conffile, "3") - if err != nil { - fatalIf(err.Trace(), "Unable to check version on share list file") - } - if v3 { - return - } - // try to load V2 if possible - sURLsV2, err := loadSharedURLsV2() - fatalIf(err.Trace(), "Unable to load shared url version ‘1.1.0’.") - if sURLsV2.Version != "1.1.0" { - fatalIf(errDummy().Trace(), "Invalid version loaded ‘"+sURLsV2.Version+"’.") - } - sURLsV3 := newSharedURLsV3() - for _, value := range sURLsV2.URLs { - entry := struct { - Date time.Time - Message shareMessageV3 - }{ - Date: value.Date, - Message: shareMessageV3{ - Expiry: value.Message.Expiry, - DownloadURL: value.Message.URL, - Key: value.Message.Key, - }, - } - sURLsV3.URLs = append(sURLsV3.URLs, entry) - } - err = saveSharedURLsV3(sURLsV3) - fatalIf(err.Trace(), "Unable to save new shared url version ‘3’.") -} - -func getSharedURLsDataDir() (string, *probe.Error) { +// Get share dir name. +func getShareDir() (string, *probe.Error) { configDir, err := getMcConfigDir() if err != nil { return "", err.Trace() @@ -153,81 +106,82 @@ func getSharedURLsDataDir() (string, *probe.Error) { return sharedURLsDataDir, nil } -func isSharedURLsDataDirExists() bool { - shareDir, err := getSharedURLsDataDir() +// Get share dir name or die. (NOTE: This ‘Die’ approach is only OK for mc like tools.) +func mustGetShareDir() string { + shareDir, err := getShareDir() fatalIf(err.Trace(), "Unable to determine share folder.") + return shareDir +} - if _, e := os.Stat(shareDir); e != nil { +// Check if the share dir exists. +func isShareDirExists() bool { + if _, e := os.Stat(mustGetShareDir()); e != nil { return false } return true } -func createSharedURLsDataDir() *probe.Error { - shareDir, err := getSharedURLsDataDir() - if err != nil { - return err.Trace() - } - - if err := os.MkdirAll(shareDir, 0700); err != nil { +// Create config share dir. +func createShareDir() *probe.Error { + if err := os.MkdirAll(mustGetShareDir(), 0700); err != nil { return probe.NewError(err) } return nil } -func getSharedURLsDataFile() (string, *probe.Error) { - shareDir, err := getSharedURLsDataDir() - if err != nil { - return "", err.Trace() - } - - shareFile := filepath.Join(shareDir, "urls.json") - return shareFile, nil +// Get share uploads file. +func getShareUploadsFile() string { + return filepath.Join(mustGetShareDir(), "uploads.json") } -func isSharedURLsDataFileExists() bool { - shareFile, err := getSharedURLsDataFile() - fatalIf(err.Trace(), "Unable to determine share filename.") +// Get share downloads file. +func getShareDownloadsFile() string { + return filepath.Join(mustGetShareDir(), "downloads.json") +} - if _, e := os.Stat(shareFile); e != nil { +// Check if share uploads file exists? +func isShareUploadsExists() bool { + if _, e := os.Stat(getShareUploadsFile()); e != nil { return false } return true } -func createSharedURLsDataFile() *probe.Error { - if err := saveSharedURLsV3(newSharedURLsV3()); err != nil { - return err.Trace() +// Check if share downloads file exists? +func isShareDownloadsExists() bool { + if _, e := os.Stat(getShareDownloadsFile()); e != nil { + return false } - return nil + return true } -// this code is necessary since, share only operates on cloud storage URLs not filesystem -func isObjectKeyPresent(url string) bool { - u := client.NewURL(url) - path := u.Path - matchS3, _ := filepath.Match("*.s3*.amazonaws.com", u.Host) - if matchS3 { - hostSplits := strings.SplitN(u.Host, ".", 2) - path = string(u.Separator) + hostSplits[0] + u.Path +// Initialize share uploads file. +func initShareUploadsFile() *probe.Error { + return newShareDBV1().Save(getShareUploadsFile()) +} + +// Initialize share downloads file. +func initShareDownloadsFile() *probe.Error { + return newShareDBV1().Save(getShareDownloadsFile()) +} + +// Initialize share directory, if not done already. +func initShareConfig() { + // Share directory. + if !isShareDirExists() { + fatalIf(createShareDir().Trace(), "Failed to create share ‘"+mustGetShareDir()+"’ folder.") + console.Infof("Successfully created ‘%s’.\n", mustGetShareDir()) } - matchGcs, _ := filepath.Match("*.storage.googleapis.com", u.Host) - if matchGcs { - hostSplits := strings.SplitN(u.Host, ".", 2) - path = string(u.Separator) + hostSplits[0] + u.Path + + // Uploads share file. + if !isShareUploadsExists() { + fatalIf(initShareUploadsFile().Trace(), "Failed to initialize share uploads ‘"+getShareUploadsFile()+"’ file.") + console.Infof("Initialized share uploads ‘%s’ file.\n", getShareUploadsFile()) } - pathSplits := strings.SplitN(path, "?", 2) - splits := strings.SplitN(pathSplits[0], string(u.Separator), 3) - switch len(splits) { - case 0, 1: - return false - case 2: - return false - case 3: - if splits[2] == "" { - return false - } - return true + + // Downloads share file. + if !isShareDownloadsExists() { + fatalIf(initShareDownloadsFile().Trace(), "Failed to initialize share downloads ‘"+getShareDownloadsFile()+"’ file.") + console.Infof("Initialized share downloads ‘%s’ file.\n", getShareDownloadsFile()) } - return false } diff --git a/share_test.go b/share_test.go index a9561568..af39710a 100644 --- a/share_test.go +++ b/share_test.go @@ -26,28 +26,28 @@ import ( func (s *TestSuite) TestShareFailure(c *C) { objectURL := server.URL + "/bucket/object1" - // invalid duration format ``1hr`` - err := app.Run([]string{os.Args[0], "share", "download", objectURL, "1hr"}) + // Invalid duration format ``1hr``. + err := app.Run([]string{os.Args[0], "share", "download", "--expire=1hr", objectURL}) c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, true) - // reset back + // Reset back. console.IsExited = false - // too high duration 169h, maximum is 168h i.e 7days. - err = app.Run([]string{os.Args[0], "share", "download", objectURL, "169hr"}) + // Too high duration 169h, maximum is 168h i.e 7days. + err = app.Run([]string{os.Args[0], "share", "download", "--expire=169hr", objectURL}) c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, true) - // reset back + // Reset back console.IsExited = false - // too low duration 0s, minimum required is 1s. - err = app.Run([]string{os.Args[0], "share", "download", objectURL, "0s"}) + // Too low duration 0s, minimum required is 1s. + err = app.Run([]string{os.Args[0], "share", "download", "--expire=0s", objectURL}) c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, true) - // reset back + // Reset back. console.IsExited = false } @@ -58,13 +58,13 @@ func (s *TestSuite) TestShareSuccess(c *C) { c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, false) - // reset back + // Reset back console.IsExited = false - err = app.Run([]string{os.Args[0], "share", "download", objectURL, "1h"}) + err = app.Run([]string{os.Args[0], "share", "download", "--expire=1h", objectURL}) c.Assert(err, IsNil) c.Assert(console.IsExited, Equals, false) - // reset back + // Reset back console.IsExited = false } diff --git a/verify-runtime.go b/verify-runtime.go index a4ae9e7e..90730c7c 100644 --- a/verify-runtime.go +++ b/verify-runtime.go @@ -93,6 +93,7 @@ func checkGolangRuntimeVersion() { func verifyMCRuntime() { checkGolangRuntimeVersion() + // .mc config folder. if !isMcConfigExists() { err := createMcConfigDir() fatalIf(err.Trace(), "Unable to create ‘mc’ config folder.") @@ -105,10 +106,14 @@ func verifyMCRuntime() { console.Infoln("Configuration written to [" + mustGetMcConfigPath() + "]. Please update your access credentials.") } + + // .mc/session folder. if !isSessionDirExists() { - fatalIf(createSessionDir().Trace(), "Unable to create session dir.") + fatalIf(createSessionDir().Trace(), "Unable to create session config folder.") } - if !isSharedURLsDataDirExists() { - fatalIf(createSharedURLsDataDir().Trace(), "Unable to create shared url datadir.") + + // .mc/share folder. + if !isShareDirExists() { + initShareConfig() } }