file_copy.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package file_copy
  2. import (
  3. "fmt"
  4. "github.com/aws/aws-sdk-go/service/s3"
  5. "github.com/ente-io/museum/ente"
  6. "github.com/ente-io/museum/pkg/controller"
  7. "github.com/ente-io/museum/pkg/repo"
  8. "github.com/ente-io/museum/pkg/utils/auth"
  9. "github.com/ente-io/museum/pkg/utils/s3config"
  10. enteTime "github.com/ente-io/museum/pkg/utils/time"
  11. "github.com/gin-contrib/requestid"
  12. "github.com/gin-gonic/gin"
  13. "github.com/sirupsen/logrus"
  14. "time"
  15. )
  16. type FileCopyController struct {
  17. S3Config *s3config.S3Config
  18. FileController *controller.FileController
  19. FileRepo *repo.FileRepository
  20. CollectionCtrl *controller.CollectionController
  21. ObjectRepo *repo.ObjectRepository
  22. }
  23. type copyS3ObjectReq struct {
  24. SourceS3Object ente.S3ObjectKey
  25. DestObjectKey string
  26. }
  27. type fileCopyInternal struct {
  28. SourceFile ente.File
  29. DestCollectionID int64
  30. // The FileKey is encrypted with the destination collection's key
  31. EncryptedFileKey string
  32. EncryptedFileKeyNonce string
  33. FileCopyReq *copyS3ObjectReq
  34. ThumbCopyReq *copyS3ObjectReq
  35. }
  36. func (fci fileCopyInternal) newFile(ownedID int64) ente.File {
  37. newFileAttributes := fci.SourceFile.File
  38. newFileAttributes.ObjectKey = fci.FileCopyReq.DestObjectKey
  39. newThumbAttributes := fci.SourceFile.Thumbnail
  40. newThumbAttributes.ObjectKey = fci.ThumbCopyReq.DestObjectKey
  41. return ente.File{
  42. OwnerID: ownedID,
  43. CollectionID: fci.DestCollectionID,
  44. EncryptedKey: fci.EncryptedFileKey,
  45. KeyDecryptionNonce: fci.EncryptedFileKeyNonce,
  46. File: newFileAttributes,
  47. Thumbnail: newThumbAttributes,
  48. Metadata: fci.SourceFile.Metadata,
  49. UpdationTime: enteTime.Microseconds(),
  50. IsDeleted: false,
  51. }
  52. }
  53. func (fc *FileCopyController) CopyFiles(c *gin.Context, req ente.CopyFileSyncRequest) (*ente.CopyResponse, error) {
  54. userID := auth.GetUserID(c.Request.Header)
  55. app := auth.GetApp(c)
  56. logger := logrus.WithFields(logrus.Fields{"req_id": requestid.Get(c), "user_id": userID})
  57. err := fc.CollectionCtrl.IsCopyAllowed(c, userID, req)
  58. if err != nil {
  59. return nil, err
  60. }
  61. fileIDs := req.FileIDs()
  62. fileToCollectionFileMap := make(map[int64]*ente.CollectionFileItem, len(req.CollectionFileItems))
  63. for i, _ := range req.CollectionFileItems {
  64. item := &req.CollectionFileItems[i]
  65. fileToCollectionFileMap[item.ID] = item
  66. }
  67. s3ObjectsToCopy, err := fc.ObjectRepo.GetObjectsForFileIDs(fileIDs)
  68. if err != nil {
  69. return nil, err
  70. }
  71. // note: this assumes that preview existingFilesToCopy for videos are not tracked inside the object_keys table
  72. if len(s3ObjectsToCopy) != 2*len(fileIDs) {
  73. return nil, ente.NewInternalError(fmt.Sprintf("expected %d objects, got %d", 2*len(fileIDs), len(s3ObjectsToCopy)))
  74. }
  75. // todo:(neeraj) if the total size is greater than 1GB, do an early check if the user can upload the existingFilesToCopy
  76. var totalSize int64
  77. for _, obj := range s3ObjectsToCopy {
  78. totalSize += obj.FileSize
  79. }
  80. logger.WithField("totalSize", totalSize).Info("total size of existingFilesToCopy to copy")
  81. // request the uploadUrls using existing method. This is to ensure that orphan objects are automatically cleaned up
  82. // todo:(neeraj) optimize this method by removing the need for getting a signed url for each object
  83. uploadUrls, err := fc.FileController.GetUploadURLs(c, userID, len(s3ObjectsToCopy), app)
  84. if err != nil {
  85. return nil, err
  86. }
  87. existingFilesToCopy, err := fc.FileRepo.GetFileAttributesForCopy(fileIDs)
  88. if err != nil {
  89. return nil, err
  90. }
  91. if len(existingFilesToCopy) != len(fileIDs) {
  92. return nil, ente.NewInternalError(fmt.Sprintf("expected %d existingFilesToCopy, got %d", len(fileIDs), len(existingFilesToCopy)))
  93. }
  94. fileOGS3Object := make(map[int64]*copyS3ObjectReq)
  95. fileThumbS3Object := make(map[int64]*copyS3ObjectReq)
  96. for i, s3Obj := range s3ObjectsToCopy {
  97. if s3Obj.Type == ente.FILE {
  98. fileOGS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  99. SourceS3Object: s3Obj,
  100. DestObjectKey: uploadUrls[i].ObjectKey,
  101. }
  102. } else if s3Obj.Type == ente.THUMBNAIL {
  103. fileThumbS3Object[s3Obj.FileID] = &copyS3ObjectReq{
  104. SourceS3Object: s3Obj,
  105. DestObjectKey: uploadUrls[i].ObjectKey,
  106. }
  107. } else {
  108. return nil, ente.NewInternalError(fmt.Sprintf("unexpected object type %s", s3Obj.Type))
  109. }
  110. }
  111. fileCopyList := make([]fileCopyInternal, 0, len(existingFilesToCopy))
  112. for i, _ := range existingFilesToCopy {
  113. file := existingFilesToCopy[i]
  114. collectionItem := fileToCollectionFileMap[file.ID]
  115. if collectionItem.ID != file.ID {
  116. return nil, ente.NewInternalError(fmt.Sprintf("expected collectionItem.ID %d, got %d", file.ID, collectionItem.ID))
  117. }
  118. fileCopy := fileCopyInternal{
  119. SourceFile: file,
  120. DestCollectionID: req.DstCollection,
  121. EncryptedFileKey: fileToCollectionFileMap[file.ID].EncryptedKey,
  122. EncryptedFileKeyNonce: fileToCollectionFileMap[file.ID].KeyDecryptionNonce,
  123. FileCopyReq: fileOGS3Object[file.ID],
  124. ThumbCopyReq: fileThumbS3Object[file.ID],
  125. }
  126. fileCopyList = append(fileCopyList, fileCopy)
  127. }
  128. oldToNewFileIDMap := make(map[int64]int64)
  129. for _, fileCopy := range fileCopyList {
  130. newFile, err := fc.createCopy(c, fileCopy, userID, app)
  131. if err != nil {
  132. return nil, err
  133. }
  134. oldToNewFileIDMap[fileCopy.SourceFile.ID] = newFile.ID
  135. }
  136. return &ente.CopyResponse{OldToNewFileIDMap: oldToNewFileIDMap}, nil
  137. }
  138. func (fc *FileCopyController) createCopy(c *gin.Context, fcInternal fileCopyInternal, userID int64, app ente.App) (*ente.File, error) {
  139. // using HotS3Client copy the File and Thumbnail
  140. s3Client := fc.S3Config.GetHotS3Client()
  141. hotBucket := fc.S3Config.GetHotBucket()
  142. err := copyS3Object(s3Client, hotBucket, fcInternal.FileCopyReq)
  143. if err != nil {
  144. return nil, err
  145. }
  146. err = copyS3Object(s3Client, hotBucket, fcInternal.ThumbCopyReq)
  147. if err != nil {
  148. return nil, err
  149. }
  150. file := fcInternal.newFile(userID)
  151. newFile, err := fc.FileController.Create(c, userID, file, "", app)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return &newFile, nil
  156. }
  157. // Helper function for S3 object copying.
  158. func copyS3Object(s3Client *s3.S3, bucket *string, req *copyS3ObjectReq) error {
  159. copySource := fmt.Sprintf("%s/%s", *bucket, req.SourceS3Object.ObjectKey)
  160. copyInput := &s3.CopyObjectInput{
  161. Bucket: bucket,
  162. CopySource: &copySource,
  163. Key: &req.DestObjectKey,
  164. }
  165. start := time.Now()
  166. _, err := s3Client.CopyObject(copyInput)
  167. elapsed := time.Since(start)
  168. if err != nil {
  169. return fmt.Errorf("failed to copy (%s) from %s to %s: %w", req.SourceS3Object.Type, copySource, req.DestObjectKey, err)
  170. }
  171. logrus.WithField("duration", elapsed).WithField("size", req.SourceS3Object.FileSize).Infof("copied (%s) from %s to %s", req.SourceS3Object.Type, copySource, req.DestObjectKey)
  172. return nil
  173. }