download/google_drive.go

82 lines
1.6 KiB
Go

package download
import (
"context"
"errors"
"fmt"
"github.com/kr/pretty"
"github.com/tanaikech/go-getfilelist"
"git.selly.red/Selly-Modules/logger"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
type GoogleDrive struct {
APIKey string
svc *drive.Service
}
type GoogleDriveFile struct {
ID string
Name string
}
func (g GoogleDrive) Init() (err error) {
if g.APIKey == "" {
err = errors.New("missing google api key")
logger.Error("validation", logger.LogData{
Source: "download.google_drive.Init",
Message: err.Error(),
Data: nil,
})
return
}
// init google drive
svc, err := drive.NewService(context.Background(), option.WithAPIKey(g.APIKey))
if err != nil {
err = fmt.Errorf("unable to retrieve Drive: %v", err)
logger.Error("init google drive service", logger.LogData{
Source: "download.google_drive.Init",
Message: err.Error(),
Data: nil,
})
return
}
// assign
g.svc = svc
return
}
func (g GoogleDrive) GetFilesByFolderID(folderID string) ([]GoogleDriveFile, error) {
var (
result = make([]GoogleDriveFile, 0)
)
res, err := getfilelist.Folder(folderID).Fields("files(name,id)").Do(g.svc)
if err != nil {
err := fmt.Errorf("error when fetch folder %s: %s", folderID, err.Error())
logger.Error("", logger.LogData{
Source: "download.google_drive.GetFilesByFolderID",
Message: err.Error(),
Data: logger.Map{"folder": folderID},
})
return result, err
}
// if there is no files
//if len(res.FileList) == 0 {
// return result, nil
//}
pretty.Println("res", res)
return result, nil
}