Merge pull request #1092 from harshavardhana/share-list
Store list of shared URLs locally until their expiry, this implements…
This commit is contained in:
+3
-2
@@ -33,8 +33,9 @@ const (
|
||||
globalMCConfigWindowsDir = "mc\\"
|
||||
globalMCConfigFile = "config.json"
|
||||
|
||||
// session config related constants
|
||||
globalSessionDir = "session"
|
||||
// session config and shared urls related constants
|
||||
globalSessionDir = "session"
|
||||
globalSharedURLsDatadir = "share"
|
||||
|
||||
// default access and secret key
|
||||
// do not pass accesskeyid and secretaccesskey through cli
|
||||
|
||||
@@ -1,74 +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 (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// shareDuration extended version of time.Duration implementing .Days() for convenience
|
||||
type shareDuration struct {
|
||||
duration time.Duration
|
||||
presignedURL string
|
||||
}
|
||||
|
||||
func (s shareDuration) Days() float64 {
|
||||
return s.duration.Hours() / 24
|
||||
}
|
||||
|
||||
func (s shareDuration) Seconds() float64 {
|
||||
return s.duration.Seconds()
|
||||
}
|
||||
|
||||
func (s shareDuration) Hours() float64 {
|
||||
return s.duration.Hours()
|
||||
}
|
||||
|
||||
func (s shareDuration) GetDuration() time.Duration {
|
||||
return s.duration
|
||||
}
|
||||
|
||||
func (s shareDuration) String() string {
|
||||
if !globalJSONFlag {
|
||||
durationString := func() string {
|
||||
if s.duration.Hours() > 24 {
|
||||
return fmt.Sprintf("%dd", int64(s.Days()))
|
||||
}
|
||||
return s.duration.String()
|
||||
}
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s", durationString(), s.presignedURL))
|
||||
}
|
||||
shareMessageBytes, err := json.Marshal(struct {
|
||||
Expires time.Duration `json:"expireSeconds"`
|
||||
PresignedURL string `json:"presignedURL"`
|
||||
}{
|
||||
Expires: time.Duration(s.Seconds()),
|
||||
PresignedURL: s.presignedURL,
|
||||
})
|
||||
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)
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
+154
-18
@@ -17,7 +17,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -55,9 +59,59 @@ EXAMPLES:
|
||||
4. Generate URL with space characters for sharing, with an expiry of 5 seconds.
|
||||
$ mc {{.Name}} s3/miniocloud/nothing-like-anything 5s
|
||||
|
||||
5. List all the shared URLs which have not expired yet.
|
||||
$ mc {{.Name}} list
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// shareMessage implements extended version of time.Duration, .Days() for convenience
|
||||
type shareMessage struct {
|
||||
Expiry time.Duration
|
||||
URL string
|
||||
}
|
||||
|
||||
func (s shareMessage) Days() float64 {
|
||||
return s.Expiry.Hours() / 24
|
||||
}
|
||||
|
||||
func (s shareMessage) Seconds() float64 {
|
||||
return s.Expiry.Seconds()
|
||||
}
|
||||
|
||||
func (s shareMessage) Hours() float64 {
|
||||
return s.Expiry.Hours()
|
||||
}
|
||||
|
||||
func (s shareMessage) GetDuration() time.Duration {
|
||||
return s.Expiry
|
||||
}
|
||||
|
||||
func (s shareMessage) String() string {
|
||||
if !globalJSONFlag {
|
||||
durationString := func() string {
|
||||
if s.Expiry.Hours() > 24 {
|
||||
return fmt.Sprintf("%dd", int64(s.Days()))
|
||||
}
|
||||
return s.Expiry.String()
|
||||
}
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s", durationString(), s.URL))
|
||||
}
|
||||
shareMessageBytes, err := json.Marshal(struct {
|
||||
Expires time.Duration `json:"expireSeconds"`
|
||||
SharedURL string `json:"sharedURL"`
|
||||
}{
|
||||
Expires: time.Duration(s.Seconds()),
|
||||
SharedURL: s.URL,
|
||||
})
|
||||
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)
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
|
||||
func checkShareSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
@@ -65,7 +119,12 @@ func checkShareSyntax(ctx *cli.Context) {
|
||||
if len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
if ctx.Args().Get(0) == "list" {
|
||||
if len(ctx.Args()) >= 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().Get(0)) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
@@ -74,43 +133,100 @@ func checkShareSyntax(ctx *cli.Context) {
|
||||
func mainShare(ctx *cli.Context) {
|
||||
checkShareSyntax(ctx)
|
||||
|
||||
if !isSharedURLsDatadirExists() {
|
||||
fatalIf(createSharedURLsDatadir().Trace(), "Unable to create shared url datadir.")
|
||||
}
|
||||
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Share": color.New(color.FgGreen, color.Bold),
|
||||
"Share": color.New(color.FgGreen, color.Bold),
|
||||
"Expires": color.New(color.FgRed, color.Bold),
|
||||
"URL": color.New(color.FgCyan, color.Bold),
|
||||
})
|
||||
|
||||
args := ctx.Args()
|
||||
config := mustGetMcConfig()
|
||||
|
||||
// if its only list, return quickly
|
||||
if args.Get(0) == "list" {
|
||||
err := doShareList()
|
||||
fatalIf(err.Trace(), "Unable to list shared URLs.")
|
||||
return
|
||||
}
|
||||
|
||||
/// get first and last arguments
|
||||
url := args.First() // url to be shared
|
||||
url := args.Get(0) // url to be shared
|
||||
// default expiration is 7days
|
||||
expires := time.Duration(604800) * time.Second
|
||||
if len(args) == 2 {
|
||||
var err error
|
||||
expires, err = time.ParseDuration(args.Last())
|
||||
expires, err = time.ParseDuration(args.Get(1))
|
||||
fatalIf(probe.NewError(err), "Unable to parse time argument.")
|
||||
}
|
||||
|
||||
targetURL := getAliasURL(url, config.Aliases)
|
||||
|
||||
// if recursive strip off the "..."
|
||||
err := doShareCmd(stripRecursiveURL(targetURL), isURLRecursive(targetURL), shareDuration{duration: expires})
|
||||
err := doShareURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), shareMessage{Expiry: expires})
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
|
||||
}
|
||||
|
||||
func getNewTargetURL(targetParser *client.URL, name string) string {
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
|
||||
if match {
|
||||
targetParser.Path = string(targetParser.Separator) + name
|
||||
} else {
|
||||
targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name
|
||||
// doShareList list shared url's
|
||||
func doShareList() *probe.Error {
|
||||
sURLs, err := loadSharedURLsV1()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return targetParser.String()
|
||||
for url, data := range sURLs.URLs {
|
||||
if time.Since(data.Date) > data.Message.GetDuration() {
|
||||
delete(sURLs.URLs, url)
|
||||
continue
|
||||
}
|
||||
expiresIn := data.Message.GetDuration() - time.Since(data.Date)
|
||||
if !globalJSONFlag {
|
||||
msg := console.Colorize("Share", "Shared URL: ")
|
||||
msg += console.Colorize("URL", url+"\n")
|
||||
msg += console.Colorize("Share", "Expires-In: ")
|
||||
msg += console.Colorize("Expires", expiresIn)
|
||||
msg += "\n"
|
||||
console.Println(msg)
|
||||
}
|
||||
shareListBytes, err := json.Marshal(struct {
|
||||
ExpiresIn time.Duration
|
||||
URL string
|
||||
}{
|
||||
ExpiresIn: time.Duration(expiresIn.Seconds()),
|
||||
URL: url,
|
||||
})
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
console.Println(string(shareListBytes))
|
||||
}
|
||||
if err := saveSharedURLsV1(sURLs); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doShareCmd share files from target
|
||||
func doShareCmd(targetURL string, recursive bool, expires shareDuration) *probe.Error {
|
||||
clnt, err := target2Client(targetURL)
|
||||
// doShareURL share files from target
|
||||
func doShareURL(targetURL string, recursive bool, expires shareMessage) *probe.Error {
|
||||
shareDate := time.Now().UTC()
|
||||
sURLs, err := loadSharedURLsV1()
|
||||
if err != nil {
|
||||
if os.IsNotExist(err.ToGoError()) {
|
||||
sURLs = &sharedURLs{}
|
||||
sURLs.Version = "1.0.0"
|
||||
sURLs.URLs = make(map[string]struct {
|
||||
Date time.Time
|
||||
Message shareMessage
|
||||
})
|
||||
} else {
|
||||
return err.Trace()
|
||||
}
|
||||
}
|
||||
|
||||
var clnt client.Client
|
||||
clnt, err = target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
@@ -124,20 +240,40 @@ func doShareCmd(targetURL string, recursive bool, expires shareDuration) *probe.
|
||||
if contentCh.Err != nil {
|
||||
return contentCh.Err.Trace()
|
||||
}
|
||||
newClnt, err := url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name))
|
||||
var newClnt client.Client
|
||||
newClnt, err = url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name))
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
presignedURL, err := newClnt.Share(expires.GetDuration())
|
||||
var sharedURL string
|
||||
sharedURL, err = newClnt.Share(expires.GetDuration())
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
expires.presignedURL = presignedURL
|
||||
expires.URL = sharedURL
|
||||
sURLs.URLs[newClnt.URL().String()] = struct {
|
||||
Date time.Time
|
||||
Message shareMessage
|
||||
}{
|
||||
Date: shareDate,
|
||||
Message: expires,
|
||||
}
|
||||
console.Println(expires)
|
||||
}
|
||||
saveSharedURLsV1(sURLs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getNewTargetURL(targetParser *client.URL, name string) string {
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
|
||||
if match {
|
||||
targetParser.Path = string(targetParser.Separator) + name
|
||||
} else {
|
||||
targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name
|
||||
}
|
||||
return targetParser.String()
|
||||
}
|
||||
|
||||
// this code is necessary since, share only operates on cloud storage URLs not filesystem
|
||||
func path2Bucket(u *client.URL) (bucketName string) {
|
||||
pathSplits := strings.SplitN(u.Path, "?", 2)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* 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"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type sharedURLs struct {
|
||||
Version string
|
||||
URLs map[string]struct {
|
||||
Date time.Time
|
||||
Message shareMessage
|
||||
}
|
||||
}
|
||||
|
||||
func createSharedURLsDatadir() *probe.Error {
|
||||
shareDir, err := getSharedURLsDatadir()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(shareDir, 0700); err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getSharedURLsDatadir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sharedURLsDatadir := filepath.Join(configDir, globalSharedURLsDatadir)
|
||||
return sharedURLsDatadir, nil
|
||||
}
|
||||
|
||||
func isSharedURLsDatadirExists() bool {
|
||||
shareDir, err := getSharedURLsDatadir()
|
||||
fatalIf(err.Trace(), "Unable to determine share folder.")
|
||||
|
||||
if _, e := os.Stat(shareDir); e != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getSharedURLsDataFile() (string, *probe.Error) {
|
||||
sharedURLsDatadir, err := getSharedURLsDatadir()
|
||||
if err != nil {
|
||||
return "", err.Trace()
|
||||
}
|
||||
|
||||
sharedURLsDataFile := filepath.Join(sharedURLsDatadir, "urls.json")
|
||||
return sharedURLsDataFile, nil
|
||||
}
|
||||
|
||||
func loadSharedURLsV1() (*sharedURLs, *probe.Error) {
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
if _, err := os.Stat(sharedURLsDataFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
s := &sharedURLs{}
|
||||
s.Version = "1.0.0"
|
||||
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
err = qs.Load(sharedURLsDataFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sharedURLsDataFile)
|
||||
}
|
||||
s = qs.Data().(*sharedURLs)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func saveSharedURLsV1(s *sharedURLs) *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)
|
||||
}
|
||||
+4
-1
@@ -86,7 +86,7 @@ func checkGolangRuntimeVersion() {
|
||||
v2 := newVersion(minGolangRuntimeVersion)
|
||||
if v1.LessThan(v2) {
|
||||
errorIf(errDummy().Trace(),
|
||||
"Old Golang runtime version ‘"+v1.String()+"’ detected., ‘mc’ requires minimum go1.5 or later.")
|
||||
"Old Golang runtime version ‘"+v1.String()+"’ detected., ‘mc’ requires minimum go1.5.1 or later.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,5 +106,8 @@ func verifyMCRuntime() {
|
||||
if !isSessionDirExists() {
|
||||
fatalIf(createSessionDir().Trace(), "Unable to create session dir.")
|
||||
}
|
||||
if !isSharedURLsDatadirExists() {
|
||||
fatalIf(createSharedURLsDatadir().Trace(), "Unable to create shared url datadir.")
|
||||
}
|
||||
checkGolangRuntimeVersion()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user