Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions cmd/share-createlink.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Copyright © 2017 Dropbox, Inc.
// Author: Daniel Porteous
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For consistency, can you omit this line? git blame can always reveal authors :)

//
// 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 cmd

import (
"fmt"
"io/ioutil"
"os"
"os/user"
"path"
"path/filepath"
"strings"

"github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/sharing"
"github.com/spf13/cobra"
)

/**
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use // to start comments. While go does support C style block comments, // is the norm and Javadoc-style comments are rare. More at https://golang.org/doc/effective_go.html#commentary

** Try to get the share link for a file if it already exists.
** If it doesn't make a new share link for it.
*/
func getShareLink(cmd *cobra.Command, args []string) (err error) {
if len(args) != 1 {
printShareLinkUsage()
return
}

dbx := sharing.New(config)
path, err := filepath.Abs(args[0])
if err != nil {
return
}

// Confirm that the file exists.
exists, err := exists(path)
if !exists || err != nil {
print("The file / folder specified does not exist.\n")
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Print the path here as well so users have context

return
}

// Try to get a link if it already exists.
if getExistingLink(dbx, path) {
return
}

// print("File / folder does not yet have a sharelink, creating one...\n")
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Delete?


// The file had no share link, let's get it.
getNewLink(dbx, path)

return
}

func printShareLinkUsage() {
fmt.Printf("Usage: %s share getlink [file / folder path]\n", os.Args[0])
}

/*
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same for comments here and elsewhere, start with //

** Try to get an existing share link for a file / folder.
** It returns true if the file / folder had a link. Otherwise it returns false.
*/
func getExistingLink(dbx sharing.Client, path string) bool {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name of this function is counter-intuitive, as it doesn't actually return the existing link. Perhaps checkExistingLink?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't just check the existing link though, it also returns it if it exists. I think checkExistingLinkAndReturnIfExists would be a bit wordy 😉. I can change it regardless if you want.

// Remove the Dropbox folder from the start.
path = strings.Replace(path, getDropboxFolder(), "", 1)

arg := sharing.ListSharedLinksArg{Path: path}
// This method can be called with a path and just get that share link.
res, err := dbx.ListSharedLinks(&arg)
if err != nil || len(res.Links) == 0 {

} else {
printLinks(res.Links)
return true
}
return false
}

/*
** Create and print a link for file / folder that doesn't yet have one.
**
** CreateSharedLinkWithSettings doesn't allow pending uploads,
** so we use the partially deprecated CreateSharedLink.
*/
func getNewLink(dbx sharing.Client, path string) bool {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like you are using bool to handle errors. Why not return error instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds like a good idea, I'll try that.

arg := sharing.NewCreateSharedLinkArg(strings.Replace(path, getDropboxFolder(), "", 1))
// Get the sharelink even if the file isn't fully uploaded yet.
arg.PendingUpload = new(sharing.PendingUploadMode)
// Determine whether the target is a file or folder.
fi, err := os.Stat(path)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can do this check before creating arg

if err != nil {
fmt.Println(err)
return false
}
switch mode := fi.Mode(); {
case mode.IsDir():
arg.PendingUpload.Tag = sharing.PendingUploadModeFolder
case mode.IsRegular():
arg.PendingUpload.Tag = sharing.PendingUploadModeFile
}
res, err := dbx.CreateSharedLink(arg)
if err != nil {
fmt.Printf("%+v\n", err)
return false
}
fmt.Printf("%s\t%s\n", res.Path[1:], res.Url)
return true
}

/* Return the path of the Dropbox folder. */
func getDropboxFolder() string {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole function is super hacky and likely not cross-platform. Let me think if there's a better way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thanks. I'll address the other issues now and we can come back to this when you have a solution. There should be a function somewhere that returns where the Dropbox folder is, the information has to be held somewhere.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the complexity around obtaining the "canonical" Dropbox folder, for all scenarios (e.g. paid users, paired accounts, custom directories) and for all platforms, I'd prefer if we solve this via documentation and help, and being explicit. For instance, we can ask users to just supply the path instead of trying to prefix things ourselves. WDYT?

// I should be using a JSON parser here but it's a pain in Go.
usr, _ := user.Current()
homedir := usr.HomeDir
infoFilePath := path.Join(homedir, ".dropbox/info.json")
raw, err := ioutil.ReadFile(infoFilePath)
if err != nil {
print("Couldn't find Dropbox folder")
return ""
}
// This is obviously dirty.
return strings.Split(strings.Split(string(raw), "\"path\": \"")[1], "\"")[0]
}

/* Check whether a file / folder exists. */
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
7 changes: 7 additions & 0 deletions cmd/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,14 @@ var shareListCmd = &cobra.Command{
Short: "List shared things",
}

var shareGetLinkCmd = &cobra.Command{
Use: "getlink",
Short: "Get share link for file / folder (create if it doesn't exist)",
RunE: getShareLink,
}

func init() {
RootCmd.AddCommand(shareCmd)
shareCmd.AddCommand(shareListCmd)
shareCmd.AddCommand(shareGetLinkCmd)
}