serviceimpl.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package gdrivefs
  2. import (
  3. "io"
  4. "net/http"
  5. "dev.hexasoftware.com/hxs/cloudmount/internal/fs/basefs"
  6. "google.golang.org/api/drive/v3"
  7. )
  8. type gdriveService struct {
  9. client *drive.Service
  10. }
  11. func (s *gdriveService) Truncate(file basefs.File) (basefs.File, error) {
  12. err := s.client.Files.Delete(file.ID()).Do() // XXX: Careful on this
  13. createdFile, err := s.client.Files.Create(&drive.File{Parents: file.Parents(), Name: file.Name()}).Fields(fileFields).Do()
  14. if err != nil {
  15. return nil, err
  16. }
  17. return &basefs.GFile{createdFile}, nil
  18. }
  19. func (s *gdriveService) Upload(reader io.Reader, file basefs.File) (basefs.File, error) {
  20. ngFile := &drive.File{}
  21. up := s.client.Files.Update(file.ID(), ngFile)
  22. upFile, err := up.Media(reader).Fields(fileFields).Do()
  23. if err != nil {
  24. return nil, err
  25. }
  26. return &basefs.GFile{upFile}, nil
  27. }
  28. func (s *gdriveService) DownloadTo(w io.Writer, file basefs.File) error {
  29. var res *http.Response
  30. var err error
  31. // TODO :Place this in service Download
  32. gfile := file.(*basefs.GFile).File
  33. // Export GDocs (Special google doc documents needs to be exported make a config somewhere for this)
  34. switch gfile.MimeType { // Make this somewhat optional special case
  35. case "application/vnd.google-apps.document":
  36. res, err = s.client.Files.Export(gfile.Id, "text/plain").Download()
  37. case "application/vnd.google-apps.spreadsheet":
  38. res, err = s.client.Files.Export(gfile.Id, "text/csv").Download()
  39. default:
  40. res, err = s.client.Files.Get(gfile.Id).Download()
  41. }
  42. if err != nil {
  43. log.Println("Error from GDrive API", err)
  44. return err
  45. }
  46. defer res.Body.Close()
  47. io.Copy(w, res.Body)
  48. return nil
  49. }