2013-01-15 00:38:18 +01:00
|
|
|
// Drive interface
|
|
|
|
package main
|
|
|
|
|
2013-01-19 11:11:55 +01:00
|
|
|
// FIXME drive code is leaking goroutines somehow - reported bug
|
|
|
|
// https://code.google.com/p/google-api-go-client/issues/detail?id=23
|
2013-01-19 00:21:02 +01:00
|
|
|
|
2013-01-15 00:38:18 +01:00
|
|
|
// FIXME list containers equivalent should list directories?
|
|
|
|
|
2013-01-19 00:21:02 +01:00
|
|
|
// FIXME list directory should list to channel for concurrency not
|
|
|
|
// append to array
|
|
|
|
|
2013-01-15 00:38:18 +01:00
|
|
|
// FIXME perhaps have a drive setup mode where we ask for all the
|
|
|
|
// params interactively and store them all in one file
|
|
|
|
// - don't need to store client* apparently
|
|
|
|
|
|
|
|
// NB permissions of token file is too open
|
|
|
|
|
|
|
|
// FIXME need to deal with some corner cases
|
|
|
|
// * multiple files with the same name
|
|
|
|
// * files can be in multiple directories
|
|
|
|
// * can have directory loops
|
2013-01-20 12:56:56 +01:00
|
|
|
// * files with / in name
|
2013-01-15 00:38:18 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"code.google.com/p/goauth2/oauth"
|
|
|
|
"code.google.com/p/google-api-go-client/drive/v2"
|
|
|
|
"errors"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
2013-01-19 00:21:02 +01:00
|
|
|
"mime"
|
2013-01-15 00:38:18 +01:00
|
|
|
"net/http"
|
|
|
|
"os"
|
2013-01-19 00:21:02 +01:00
|
|
|
"path"
|
2013-01-15 00:38:18 +01:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// FsDrive represents a remote drive server
|
|
|
|
type FsDrive struct {
|
|
|
|
svc *drive.Service // the connection to the drive server
|
|
|
|
root string // the path we are working on
|
|
|
|
client *http.Client // authorized client
|
|
|
|
about *drive.About // information about the drive, including the root
|
|
|
|
rootId string // Id of the root directory
|
|
|
|
foundRoot sync.Once // Whether we need to find the root directory or not
|
2013-01-23 22:19:26 +01:00
|
|
|
dirCache dirCache // Map of directory path to directory id
|
2013-01-15 00:38:18 +01:00
|
|
|
findDirLock sync.Mutex // Protect findDir from concurrent use
|
|
|
|
}
|
|
|
|
|
|
|
|
// FsObjectDrive describes a drive object
|
|
|
|
type FsObjectDrive struct {
|
2013-01-19 11:11:55 +01:00
|
|
|
drive *FsDrive // what this object is part of
|
|
|
|
remote string // The remote path
|
|
|
|
id string // Drive Id of this object
|
|
|
|
url string // Download URL of this object
|
|
|
|
md5sum string // md5sum of the object
|
|
|
|
bytes int64 // size of the object
|
|
|
|
modifiedDate string // RFC3339 time it was last modified
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
2013-01-23 22:19:26 +01:00
|
|
|
// dirCache caches paths to directory Ids and vice versa
|
|
|
|
type dirCache struct {
|
2013-01-15 00:38:18 +01:00
|
|
|
sync.RWMutex
|
2013-01-23 22:19:26 +01:00
|
|
|
cache map[string]string
|
|
|
|
invCache map[string]string
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Make a new locked map
|
2013-01-23 22:19:26 +01:00
|
|
|
func newDirCache() dirCache {
|
|
|
|
d := dirCache{}
|
|
|
|
d.Flush()
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
|
|
|
// Gets an Id given a path
|
|
|
|
func (m *dirCache) Get(path string) (id string, ok bool) {
|
|
|
|
m.RLock()
|
|
|
|
id, ok = m.cache[path]
|
|
|
|
m.RUnlock()
|
|
|
|
return
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
2013-01-23 22:19:26 +01:00
|
|
|
// GetInv gets a path given an Id
|
|
|
|
func (m *dirCache) GetInv(path string) (id string, ok bool) {
|
2013-01-15 00:38:18 +01:00
|
|
|
m.RLock()
|
2013-01-23 22:19:26 +01:00
|
|
|
id, ok = m.invCache[path]
|
2013-01-15 00:38:18 +01:00
|
|
|
m.RUnlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-01-23 22:19:26 +01:00
|
|
|
// Put a path, id into the map
|
|
|
|
func (m *dirCache) Put(path, id string) {
|
2013-01-15 00:38:18 +01:00
|
|
|
m.Lock()
|
2013-01-23 22:19:26 +01:00
|
|
|
m.cache[path] = id
|
|
|
|
m.invCache[id] = path
|
2013-01-15 00:38:18 +01:00
|
|
|
m.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Flush the map of all data
|
2013-01-23 22:19:26 +01:00
|
|
|
func (m *dirCache) Flush() {
|
2013-01-15 00:38:18 +01:00
|
|
|
m.Lock()
|
|
|
|
m.cache = make(map[string]string)
|
2013-01-23 22:19:26 +01:00
|
|
|
m.invCache = make(map[string]string)
|
2013-01-15 00:38:18 +01:00
|
|
|
m.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ------------------------------------------------------------
|
|
|
|
|
|
|
|
// Constants
|
|
|
|
const (
|
|
|
|
// defaultDriveTokenFile = ".google-drive-token" // FIXME root in home directory somehow
|
|
|
|
driveFolderType = "application/vnd.google-apps.folder"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Globals
|
|
|
|
var (
|
|
|
|
// Flags
|
|
|
|
driveClientId = flag.String("drive-client-id", os.Getenv("GDRIVE_CLIENT_ID"), "Auth URL for server. Defaults to environment var GDRIVE_CLIENT_ID.")
|
|
|
|
driveClientSecret = flag.String("drive-client-secret", os.Getenv("GDRIVE_CLIENT_SECRET"), "User name. Defaults to environment var GDRIVE_CLIENT_SECRET.")
|
|
|
|
driveTokenFile = flag.String("drive-token-file", os.Getenv("GDRIVE_TOKEN_FILE"), "API key (password). Defaults to environment var GDRIVE_TOKEN_FILE.")
|
|
|
|
driveAuthCode = flag.String("drive-auth-code", "", "Pass in when requested to make the drive token file.")
|
2013-01-23 22:19:26 +01:00
|
|
|
driveFullList = flag.Bool("drive-full-list", true, "Use a full listing for directory list. More data but usually quicker.")
|
2013-01-15 00:38:18 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// String converts this FsDrive to a string
|
|
|
|
func (f *FsDrive) String() string {
|
|
|
|
return fmt.Sprintf("Google drive root '%s'", f.root)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pattern to match a drive url
|
|
|
|
var driveMatch = regexp.MustCompile(`^drive://(.*)$`)
|
|
|
|
|
|
|
|
// parseParse parses a drive 'url'
|
|
|
|
func parseDrivePath(path string) (root string, err error) {
|
|
|
|
parts := driveMatch.FindAllStringSubmatch(path, -1)
|
|
|
|
if len(parts) != 1 || len(parts[0]) != 2 {
|
|
|
|
err = fmt.Errorf("Couldn't parse drive url %q", path)
|
|
|
|
} else {
|
|
|
|
root = parts[0][1]
|
|
|
|
root = strings.Trim(root, "/")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-01-20 12:56:56 +01:00
|
|
|
// User function to process a File item from listAll
|
|
|
|
//
|
|
|
|
// Should return true to finish processing
|
|
|
|
type listAllFn func(*drive.File) bool
|
|
|
|
|
|
|
|
// Lists the directory required calling the user function on each item found
|
|
|
|
//
|
|
|
|
// If the user fn ever returns true then it early exits with found = true
|
2013-01-15 00:38:18 +01:00
|
|
|
//
|
|
|
|
// Search params: https://developers.google.com/drive/search-parameters
|
2013-01-20 12:56:56 +01:00
|
|
|
func (f *FsDrive) listAll(dirId string, title string, directoriesOnly bool, filesOnly bool, fn listAllFn) (found bool, err error) {
|
2013-01-23 22:19:26 +01:00
|
|
|
query := fmt.Sprintf("trashed=false")
|
|
|
|
if dirId != "" {
|
|
|
|
query += fmt.Sprintf(" and '%s' in parents", dirId)
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
if title != "" {
|
|
|
|
// Escaping the backslash isn't documented but seems to work
|
|
|
|
title = strings.Replace(title, `\`, `\\`, -1)
|
|
|
|
title = strings.Replace(title, `'`, `\'`, -1)
|
|
|
|
query += fmt.Sprintf(" and title='%s'", title)
|
|
|
|
}
|
|
|
|
if directoriesOnly {
|
|
|
|
query += fmt.Sprintf(" and mimeType='%s'", driveFolderType)
|
|
|
|
}
|
|
|
|
if filesOnly {
|
|
|
|
query += fmt.Sprintf(" and mimeType!='%s'", driveFolderType)
|
|
|
|
}
|
2013-01-23 22:19:26 +01:00
|
|
|
// fmt.Printf("listAll Query = %q\n", query)
|
|
|
|
list := f.svc.Files.List().Q(query).MaxResults(1000)
|
2013-01-20 12:56:56 +01:00
|
|
|
OUTER:
|
2013-01-15 00:38:18 +01:00
|
|
|
for {
|
|
|
|
files, err := list.Do()
|
|
|
|
if err != nil {
|
2013-01-20 12:56:56 +01:00
|
|
|
return false, fmt.Errorf("Couldn't list directory: %s", err)
|
|
|
|
}
|
|
|
|
for _, item := range files.Items {
|
|
|
|
if fn(item) {
|
|
|
|
found = true
|
|
|
|
break OUTER
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
if files.NextPageToken == "" {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
list.PageToken(files.NextPageToken)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ask the user for a new auth
|
|
|
|
func MakeNewToken(t *oauth.Transport) error {
|
|
|
|
if *driveAuthCode == "" {
|
|
|
|
// Generate a URL to visit for authorization.
|
|
|
|
authUrl := t.Config.AuthCodeURL("state")
|
|
|
|
fmt.Fprintf(os.Stderr, "Go to the following link in your browser\n")
|
|
|
|
fmt.Fprintf(os.Stderr, "%s\n", authUrl)
|
|
|
|
fmt.Fprintf(os.Stderr, "Log in, then re-run this program with the -drive-auth-code parameter\n")
|
|
|
|
fmt.Fprintf(os.Stderr, "You only need this parameter once until the drive token file has been created\n")
|
|
|
|
return errors.New("Re-run with --drive-auth-code")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the code, and exchange it for a token.
|
|
|
|
//fmt.Printf("Enter verification code: ")
|
|
|
|
//var code string
|
|
|
|
//fmt.Scanln(&code)
|
|
|
|
_, err := t.Exchange(*driveAuthCode)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewFsDrive contstructs an FsDrive from the path, container:path
|
|
|
|
func NewFsDrive(path string) (*FsDrive, error) {
|
|
|
|
if *driveClientId == "" {
|
|
|
|
return nil, errors.New("Need -drive-client-id or environmental variable GDRIVE_CLIENT_ID")
|
|
|
|
}
|
|
|
|
if *driveClientSecret == "" {
|
|
|
|
return nil, errors.New("Need -drive-client-secret or environmental variable GDRIVE_CLIENT_SECRET")
|
|
|
|
}
|
|
|
|
if *driveTokenFile == "" {
|
|
|
|
return nil, errors.New("Need -drive-token-file or environmental variable GDRIVE_TOKEN_FILE")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Settings for authorization.
|
|
|
|
var driveConfig = &oauth.Config{
|
|
|
|
ClientId: *driveClientId,
|
|
|
|
ClientSecret: *driveClientSecret,
|
|
|
|
Scope: "https://www.googleapis.com/auth/drive",
|
|
|
|
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
|
|
|
|
AuthURL: "https://accounts.google.com/o/oauth2/auth",
|
|
|
|
TokenURL: "https://accounts.google.com/o/oauth2/token",
|
|
|
|
TokenCache: oauth.CacheFile(*driveTokenFile),
|
|
|
|
}
|
|
|
|
|
|
|
|
root, err := parseDrivePath(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2013-01-23 22:19:26 +01:00
|
|
|
f := &FsDrive{root: root, dirCache: newDirCache()}
|
2013-01-15 00:38:18 +01:00
|
|
|
|
|
|
|
t := &oauth.Transport{
|
|
|
|
Config: driveConfig,
|
|
|
|
Transport: http.DefaultTransport,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to pull the token from the cache; if this fails, we need to get one.
|
|
|
|
token, err := driveConfig.TokenCache.Token()
|
|
|
|
if err != nil {
|
|
|
|
err := MakeNewToken(t)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to authorise: %s", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if *driveAuthCode != "" {
|
|
|
|
return nil, fmt.Errorf("Only supply -drive-auth-code once")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
t.Token = token
|
|
|
|
|
|
|
|
// Create a new authorized Drive client.
|
|
|
|
f.client = t.Client()
|
|
|
|
f.svc, err = drive.New(f.client)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Couldn't create Drive client: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read About so we know the root path
|
|
|
|
f.about, err = f.svc.About.Get().Do()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Couldn't read info about Drive: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find the Id of the root directory and the Id of its parent
|
|
|
|
f.rootId = f.about.RootFolderId
|
2013-01-23 22:19:26 +01:00
|
|
|
// Put the root directory in
|
|
|
|
f.dirCache.Put("", f.rootId)
|
|
|
|
// fmt.Printf("Root id %s", f.rootId)
|
2013-01-15 00:38:18 +01:00
|
|
|
return f, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return an FsObject from a path
|
|
|
|
//
|
|
|
|
// May return nil if an error occurred
|
|
|
|
func (f *FsDrive) NewFsObjectWithInfo(remote string, info *drive.File) FsObject {
|
|
|
|
fs := &FsObjectDrive{
|
|
|
|
drive: f,
|
|
|
|
remote: remote,
|
|
|
|
}
|
|
|
|
if info != nil {
|
2013-01-19 11:11:55 +01:00
|
|
|
fs.setMetaData(info)
|
2013-01-15 00:38:18 +01:00
|
|
|
} else {
|
|
|
|
err := fs.readMetaData() // reads info and meta, returning an error
|
|
|
|
if err != nil {
|
|
|
|
// logged already FsDebug("Failed to read info: %s", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fs
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return an FsObject from a path
|
|
|
|
//
|
|
|
|
// May return nil if an error occurred
|
|
|
|
func (f *FsDrive) NewFsObject(remote string) FsObject {
|
|
|
|
return f.NewFsObjectWithInfo(remote, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Path should be directory path either "" or "path/"
|
2013-01-23 22:19:26 +01:00
|
|
|
//
|
|
|
|
// List the directory using a recursive list from the root
|
|
|
|
//
|
|
|
|
// This fetches the minimum amount of stuff but does more API calls
|
|
|
|
// which makes it slow
|
|
|
|
func (f *FsDrive) listDirRecursive(dirId string, path string, out FsObjectsChan) error {
|
2013-01-20 12:56:56 +01:00
|
|
|
var subError error
|
2013-01-15 00:38:18 +01:00
|
|
|
// Make the API request
|
2013-01-20 12:56:56 +01:00
|
|
|
_, err := f.listAll(dirId, "", false, false, func(item *drive.File) bool {
|
2013-01-15 00:38:18 +01:00
|
|
|
// Recurse on directories
|
|
|
|
// FIXME should do this in parallel
|
|
|
|
// use a wg to sync then collect error
|
|
|
|
if item.MimeType == driveFolderType {
|
2013-01-23 22:19:26 +01:00
|
|
|
subError = f.listDirRecursive(item.Id, path+item.Title+"/", out)
|
2013-01-20 12:56:56 +01:00
|
|
|
if subError != nil {
|
|
|
|
return true
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If item has no MD5 sum it isn't stored on drive, so ignore it
|
2013-01-20 12:56:56 +01:00
|
|
|
if item.Md5Checksum != "" {
|
|
|
|
if fs := f.NewFsObjectWithInfo(path+item.Title, item); fs != nil {
|
|
|
|
out <- fs
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
}
|
2013-01-20 12:56:56 +01:00
|
|
|
return false
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if subError != nil {
|
|
|
|
return subError
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-01-23 22:19:26 +01:00
|
|
|
// Path should be directory path either "" or "path/"
|
|
|
|
//
|
|
|
|
// List the directory using a full listing and filtering out unwanted
|
|
|
|
// items
|
|
|
|
//
|
|
|
|
// This is fast in terms of number of API calls, but slow in terms of
|
|
|
|
// fetching more data than it needs
|
|
|
|
func (f *FsDrive) listDirFull(dirId string, path string, out FsObjectsChan) error {
|
|
|
|
// Orphans waiting for their parent
|
|
|
|
orphans := make(map[string][]*drive.File)
|
|
|
|
|
|
|
|
var outputItem func(*drive.File, string) // forward def for recursive fn
|
|
|
|
|
|
|
|
// Output an item or directory
|
|
|
|
outputItem = func(item *drive.File, directory string) {
|
|
|
|
// fmt.Printf("found %q %q parent %q dir %q ok %s\n", item.Title, item.Id, parentId, directory, ok)
|
|
|
|
path := item.Title
|
|
|
|
if directory != "" {
|
|
|
|
path = directory + "/" + path
|
|
|
|
}
|
|
|
|
if item.MimeType == driveFolderType {
|
|
|
|
// Put the directory into the dircache
|
|
|
|
f.dirCache.Put(path, item.Id)
|
|
|
|
// fmt.Printf("directory %s %s %s\n", path, item.Title, item.Id)
|
|
|
|
// Collect the orphans if any
|
|
|
|
for _, orphan := range orphans[item.Id] {
|
|
|
|
// fmt.Printf("rescuing orphan %s %s %s\n", path, orphan.Title, orphan.Id)
|
|
|
|
outputItem(orphan, path)
|
|
|
|
}
|
|
|
|
delete(orphans, item.Id)
|
|
|
|
} else {
|
|
|
|
// fmt.Printf("file %s %s %s\n", path, item.Title, item.Id)
|
|
|
|
// If item has no MD5 sum it isn't stored on drive, so ignore it
|
|
|
|
if item.Md5Checksum != "" {
|
|
|
|
if fs := f.NewFsObjectWithInfo(path, item); fs != nil {
|
|
|
|
out <- fs
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make the API request
|
|
|
|
_, err := f.listAll("", "", false, false, func(item *drive.File) bool {
|
|
|
|
if len(item.Parents) == 0 {
|
|
|
|
// fmt.Printf("no parents %s %s: %#v\n", item.Title, item.Id, item)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
parentId := item.Parents[0].Id
|
|
|
|
directory, ok := f.dirCache.GetInv(parentId)
|
|
|
|
if !ok {
|
|
|
|
// Haven't found the parent yet so add to orphans
|
|
|
|
// fmt.Printf("orphan[%s] %s %s\n", parentId, item.Title, item.Id)
|
|
|
|
orphans[parentId] = append(orphans[parentId], item)
|
|
|
|
} else {
|
|
|
|
outputItem(item, directory)
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(orphans) > 0 {
|
|
|
|
// fmt.Printf("Orphans!!!! %v", orphans)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-01-15 00:38:18 +01:00
|
|
|
// Splits a path into directory, leaf
|
|
|
|
//
|
|
|
|
// Path shouldn't start or end with a /
|
|
|
|
//
|
|
|
|
// If there are no slashes then directory will be "" and leaf = path
|
|
|
|
func splitPath(path string) (directory, leaf string) {
|
|
|
|
lastSlash := strings.LastIndex(path, "/")
|
|
|
|
if lastSlash >= 0 {
|
|
|
|
directory = path[:lastSlash]
|
|
|
|
leaf = path[lastSlash+1:]
|
|
|
|
} else {
|
|
|
|
directory = ""
|
|
|
|
leaf = path
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finds the directory passed in returning the directory Id starting from pathId
|
|
|
|
//
|
|
|
|
// Path shouldn't start or end with a /
|
|
|
|
//
|
|
|
|
// If create is set it will make the directory if not found
|
|
|
|
//
|
|
|
|
// Algorithm:
|
|
|
|
// Look in the cache for the path, if found return the pathId
|
|
|
|
// If not found strip the last path off the path and recurse
|
|
|
|
// Now have a parent directory id, so look in the parent for self and return it
|
|
|
|
func (f *FsDrive) findDir(path string, create bool) (pathId string, err error) {
|
|
|
|
pathId = f._findDirInCache(path)
|
|
|
|
if pathId != "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
f.findDirLock.Lock()
|
|
|
|
defer f.findDirLock.Unlock()
|
|
|
|
return f._findDir(path, create)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Look for the root and in the cache - safe to call without the findDirLock
|
|
|
|
func (f *FsDrive) _findDirInCache(path string) string {
|
|
|
|
// fmt.Println("Finding",path,"create",create,"cache",cache)
|
|
|
|
// If it is the root, then return it
|
|
|
|
if path == "" {
|
|
|
|
// fmt.Println("Root")
|
|
|
|
return f.rootId
|
|
|
|
}
|
|
|
|
|
|
|
|
// If it is in the cache then return it
|
|
|
|
pathId, ok := f.dirCache.Get(path)
|
|
|
|
if ok {
|
|
|
|
// fmt.Println("Cache hit on", path)
|
|
|
|
return pathId
|
|
|
|
}
|
|
|
|
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unlocked findDir - must have findDirLock
|
|
|
|
func (f *FsDrive) _findDir(path string, create bool) (pathId string, err error) {
|
|
|
|
pathId = f._findDirInCache(path)
|
|
|
|
if pathId != "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Split the path into directory, leaf
|
|
|
|
directory, leaf := splitPath(path)
|
|
|
|
|
|
|
|
// Recurse and find pathId for directory
|
|
|
|
pathId, err = f._findDir(directory, create)
|
|
|
|
if err != nil {
|
|
|
|
return pathId, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find the leaf in pathId
|
2013-01-20 12:56:56 +01:00
|
|
|
found, err := f.listAll(pathId, leaf, true, false, func(item *drive.File) bool {
|
|
|
|
if item.Title == leaf {
|
|
|
|
pathId = item.Id
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
2013-01-15 00:38:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return pathId, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// If not found create the directory if required or return an error
|
|
|
|
if !found {
|
|
|
|
if create {
|
|
|
|
// fmt.Println("Making", path)
|
|
|
|
// Define the metadata for the directory we are going to create.
|
|
|
|
info := &drive.File{
|
|
|
|
Title: leaf,
|
|
|
|
Description: leaf,
|
|
|
|
MimeType: driveFolderType,
|
|
|
|
Parents: []*drive.ParentReference{{Id: pathId}},
|
|
|
|
}
|
|
|
|
info, err := f.svc.Files.Insert(info).Do()
|
|
|
|
if err != nil {
|
|
|
|
return pathId, fmt.Errorf("Failed to make directory")
|
|
|
|
}
|
|
|
|
pathId = info.Id
|
|
|
|
} else {
|
|
|
|
return pathId, fmt.Errorf("Couldn't find directory: %q", path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store the directory in the cache
|
|
|
|
f.dirCache.Put(path, pathId)
|
|
|
|
|
|
|
|
// fmt.Println("Dir", path, "is", pathId)
|
|
|
|
return pathId, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finds the root directory if not already found
|
|
|
|
//
|
|
|
|
// Resets the root directory
|
|
|
|
//
|
|
|
|
// If create is set it will make the directory if not found
|
|
|
|
func (f *FsDrive) findRoot(create bool) error {
|
|
|
|
var err error
|
|
|
|
f.foundRoot.Do(func() {
|
|
|
|
f.rootId, err = f.findDir(f.root, create)
|
|
|
|
f.dirCache.Flush()
|
2013-01-23 22:19:26 +01:00
|
|
|
// Put the root directory in
|
|
|
|
f.dirCache.Put("", f.rootId)
|
2013-01-15 00:38:18 +01:00
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Walk the path returning a channel of FsObjects
|
|
|
|
func (f *FsDrive) List() FsObjectsChan {
|
|
|
|
out := make(FsObjectsChan, *checkers)
|
|
|
|
go func() {
|
|
|
|
defer close(out)
|
|
|
|
err := f.findRoot(false)
|
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
log.Printf("Couldn't find root: %s", err)
|
|
|
|
} else {
|
2013-01-23 22:19:26 +01:00
|
|
|
if *driveFullList {
|
|
|
|
err = f.listDirFull(f.rootId, "", out)
|
|
|
|
} else {
|
|
|
|
err = f.listDirRecursive(f.rootId, "", out)
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
log.Printf("List failed: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2013-01-23 23:43:20 +01:00
|
|
|
// Walk the path returning a channel of FsObjects
|
|
|
|
func (f *FsDrive) ListDir() FsDirChan {
|
|
|
|
out := make(FsDirChan, *checkers)
|
|
|
|
go func() {
|
|
|
|
defer close(out)
|
|
|
|
err := f.findRoot(false)
|
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
log.Printf("Couldn't find root: %s", err)
|
|
|
|
} else {
|
|
|
|
_, err := f.listAll(f.rootId, "", true, false, func(item *drive.File) bool {
|
|
|
|
dir := &FsDir{
|
|
|
|
Name: item.Title,
|
|
|
|
Bytes: -1,
|
|
|
|
Count: -1,
|
|
|
|
}
|
|
|
|
dir.When, _ = time.Parse(time.RFC3339, item.ModifiedDate)
|
|
|
|
out <- dir
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
log.Printf("ListDir failed: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2013-01-15 00:38:18 +01:00
|
|
|
// Put the FsObject into the container
|
|
|
|
//
|
|
|
|
// Copy the reader in to the new object which is returned
|
|
|
|
//
|
|
|
|
// The new object may have been created
|
|
|
|
func (f *FsDrive) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {
|
|
|
|
// Temporary FsObject under construction
|
|
|
|
fs := &FsObjectDrive{drive: f, remote: remote}
|
|
|
|
|
|
|
|
directory, leaf := splitPath(remote)
|
|
|
|
directoryId, err := f.findDir(directory, true)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Couldn't find or make directory: %s", err)
|
|
|
|
}
|
|
|
|
|
2013-01-19 00:21:02 +01:00
|
|
|
// Guess the mime type
|
|
|
|
mimeType := mime.TypeByExtension(path.Ext(remote))
|
|
|
|
if mimeType == "" {
|
|
|
|
mimeType = "application/octet-stream"
|
|
|
|
}
|
|
|
|
|
2013-01-15 00:38:18 +01:00
|
|
|
// Define the metadata for the file we are going to create.
|
|
|
|
info := &drive.File{
|
|
|
|
Title: leaf,
|
|
|
|
Description: leaf,
|
|
|
|
Parents: []*drive.ParentReference{{Id: directoryId}},
|
2013-01-19 00:21:02 +01:00
|
|
|
MimeType: mimeType,
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// FIXME can't set modified date on initial upload as no
|
|
|
|
// .SetModifiedDate(). This agrees with the API docs, but not
|
|
|
|
// with the comment on
|
|
|
|
// https://developers.google.com/drive/v2/reference/files/insert
|
|
|
|
//
|
|
|
|
// modifiedDate datetime Last time this file was modified by
|
|
|
|
// anyone (formatted RFC 3339 timestamp). This is only mutable
|
|
|
|
// on update when the setModifiedDate parameter is set.
|
|
|
|
// writable
|
|
|
|
//
|
|
|
|
// There is no setModifiedDate parameter though
|
|
|
|
|
|
|
|
// Make the API request to upload infodata and file data.
|
|
|
|
info, err = f.svc.Files.Insert(info).Media(in).Do()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Upload failed: %s", err)
|
|
|
|
}
|
2013-01-19 11:11:55 +01:00
|
|
|
fs.setMetaData(info)
|
2013-01-15 00:38:18 +01:00
|
|
|
|
|
|
|
// Set modified date
|
|
|
|
info.ModifiedDate = modTime.Format(time.RFC3339Nano)
|
|
|
|
_, err = f.svc.Files.Update(info.Id, info).SetModifiedDate(true).Do()
|
|
|
|
if err != nil {
|
2013-01-19 00:21:02 +01:00
|
|
|
return fs, fmt.Errorf("Failed to set mtime: %s", err)
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
return fs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mkdir creates the container if it doesn't exist
|
|
|
|
func (f *FsDrive) Mkdir() error {
|
|
|
|
return f.findRoot(true)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Rmdir deletes the container
|
|
|
|
//
|
|
|
|
// Returns an error if it isn't empty
|
|
|
|
func (f *FsDrive) Rmdir() error {
|
|
|
|
err := f.findRoot(false)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
children, err := f.svc.Children.List(f.rootId).MaxResults(10).Do()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(children.Items) > 0 {
|
|
|
|
return fmt.Errorf("Directory not empty: %#v", children.Items)
|
|
|
|
}
|
2013-01-18 18:01:47 +01:00
|
|
|
// Delete the directory if it isn't the root
|
|
|
|
if f.root != "" {
|
|
|
|
err = f.svc.Files.Delete(f.rootId).Do()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2013-01-19 00:21:02 +01:00
|
|
|
// Return the precision
|
|
|
|
func (fs *FsDrive) Precision() time.Duration {
|
|
|
|
return time.Millisecond
|
|
|
|
}
|
|
|
|
|
2013-01-18 18:01:47 +01:00
|
|
|
// Purge deletes all the files and the container
|
|
|
|
//
|
|
|
|
// Returns an error if it isn't empty
|
|
|
|
func (f *FsDrive) Purge() error {
|
|
|
|
if f.root == "" {
|
|
|
|
return fmt.Errorf("Can't purge root directory")
|
|
|
|
}
|
|
|
|
err := f.findRoot(false)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
err = f.svc.Files.Delete(f.rootId).Do()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ------------------------------------------------------------
|
|
|
|
|
|
|
|
// Return the remote path
|
|
|
|
func (fs *FsObjectDrive) Remote() string {
|
|
|
|
return fs.remote
|
|
|
|
}
|
|
|
|
|
|
|
|
// Md5sum returns the Md5sum of an object returning a lowercase hex string
|
|
|
|
func (fs *FsObjectDrive) Md5sum() (string, error) {
|
2013-01-19 11:11:55 +01:00
|
|
|
return fs.md5sum, nil
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Size returns the size of an object in bytes
|
|
|
|
func (fs *FsObjectDrive) Size() int64 {
|
2013-01-19 11:11:55 +01:00
|
|
|
return fs.bytes
|
|
|
|
}
|
|
|
|
|
|
|
|
// setMetaData sets the fs data from a drive.File
|
|
|
|
func (fs *FsObjectDrive) setMetaData(info *drive.File) {
|
|
|
|
fs.id = info.Id
|
|
|
|
fs.url = info.DownloadUrl
|
|
|
|
fs.md5sum = strings.ToLower(info.Md5Checksum)
|
|
|
|
fs.bytes = info.FileSize
|
|
|
|
fs.modifiedDate = info.ModifiedDate
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// readMetaData gets the info if it hasn't already been fetched
|
|
|
|
func (fs *FsObjectDrive) readMetaData() (err error) {
|
2013-01-19 11:11:55 +01:00
|
|
|
if fs.id != "" {
|
2013-01-15 00:38:18 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
directory, leaf := splitPath(fs.remote)
|
|
|
|
directoryId, err := fs.drive.findDir(directory, false)
|
|
|
|
if err != nil {
|
|
|
|
FsDebug(fs, "Couldn't find directory: %s", err)
|
|
|
|
return fmt.Errorf("Couldn't find directory: %s", err)
|
|
|
|
}
|
|
|
|
|
2013-01-20 12:56:56 +01:00
|
|
|
found, err := fs.drive.listAll(directoryId, leaf, false, true, func(item *drive.File) bool {
|
|
|
|
if item.Title == leaf {
|
|
|
|
fs.setMetaData(item)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
})
|
2013-01-15 00:38:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2013-01-20 12:56:56 +01:00
|
|
|
if !found {
|
|
|
|
FsDebug(fs, "Couldn't find object")
|
|
|
|
return fmt.Errorf("Couldn't find object")
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
2013-01-20 12:56:56 +01:00
|
|
|
return nil
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// ModTime returns the modification time of the object
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// It attempts to read the objects mtime and if that isn't present the
|
|
|
|
// LastModified returned in the http headers
|
|
|
|
func (fs *FsObjectDrive) ModTime() time.Time {
|
|
|
|
err := fs.readMetaData()
|
|
|
|
if err != nil {
|
|
|
|
FsLog(fs, "Failed to read metadata: %s", err)
|
|
|
|
return time.Now()
|
|
|
|
}
|
2013-01-19 11:11:55 +01:00
|
|
|
modTime, err := time.Parse(time.RFC3339, fs.modifiedDate)
|
2013-01-15 00:38:18 +01:00
|
|
|
if err != nil {
|
|
|
|
FsLog(fs, "Failed to read mtime from object: %s", err)
|
|
|
|
return time.Now()
|
|
|
|
}
|
|
|
|
return modTime
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sets the modification time of the local fs object
|
|
|
|
func (fs *FsObjectDrive) SetModTime(modTime time.Time) {
|
|
|
|
err := fs.readMetaData()
|
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
FsLog(fs, "Failed to read metadata: %s", err)
|
|
|
|
return
|
|
|
|
}
|
2013-01-19 11:11:55 +01:00
|
|
|
// New metadata
|
|
|
|
info := &drive.File{
|
|
|
|
ModifiedDate: modTime.Format(time.RFC3339Nano),
|
|
|
|
}
|
2013-01-15 00:38:18 +01:00
|
|
|
// Set modified date
|
2013-01-19 11:11:55 +01:00
|
|
|
_, err = fs.drive.svc.Files.Update(fs.id, info).SetModifiedDate(true).Do()
|
2013-01-15 00:38:18 +01:00
|
|
|
if err != nil {
|
|
|
|
stats.Error()
|
|
|
|
FsLog(fs, "Failed to update remote mtime: %s", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Is this object storable
|
|
|
|
func (fs *FsObjectDrive) Storable() bool {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Open an object for read
|
|
|
|
func (fs *FsObjectDrive) Open() (in io.ReadCloser, err error) {
|
2013-01-19 11:11:55 +01:00
|
|
|
req, _ := http.NewRequest("GET", fs.url, nil)
|
2013-01-15 00:38:18 +01:00
|
|
|
req.Header.Set("User-Agent", "swiftsync/1.0")
|
|
|
|
res, err := fs.drive.client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
res.Body.Close()
|
|
|
|
return nil, fmt.Errorf("Bad response: %d: %s", res.StatusCode, res.Status)
|
|
|
|
}
|
|
|
|
return res.Body, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove an object
|
|
|
|
func (fs *FsObjectDrive) Remove() error {
|
2013-01-19 11:11:55 +01:00
|
|
|
return fs.drive.svc.Files.Delete(fs.id).Do()
|
2013-01-15 00:38:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check the interfaces are satisfied
|
|
|
|
var _ Fs = &FsDrive{}
|
2013-01-18 18:01:47 +01:00
|
|
|
var _ Purger = &FsDrive{}
|
2013-01-15 00:38:18 +01:00
|
|
|
var _ FsObject = &FsObjectDrive{}
|