Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: cloudinary driver for goravel #4

Merged
merged 18 commits into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
96 changes: 46 additions & 50 deletions cloudinary.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"

Expand Down Expand Up @@ -103,8 +102,8 @@ func (r *Cloudinary) AllFiles(path string) ([]string, error) {
// Copy copies a file to a new location.
func (r *Cloudinary) Copy(source, destination string) error {
result, err := r.instance.Upload.Upload(r.ctx, r.Url(source), uploader.UploadParams{
PublicID: r.getPublicId(destination),
ResourceType: r.getResourceType(destination),
PublicID: destination,
ResourceType: "auto",
})
if err != nil {
return err
Expand All @@ -118,10 +117,14 @@ func (r *Cloudinary) Copy(source, destination string) error {
// Delete deletes a file.
func (r *Cloudinary) Delete(file ...string) error {
for _, f := range file {
asset, err := r.getAsset(f)
if err != nil {
return err
}
result, err := r.instance.Upload.Destroy(r.ctx, uploader.DestroyParams{
PublicID: r.getPublicId(f),
ResourceType: r.getResourceType(f),
PublicID: asset.PublicID,
Invalidate: api.Bool(true),
ResourceType: asset.ResourceType,
})
if err != nil {
return err
Expand All @@ -145,6 +148,7 @@ func (r *Cloudinary) DeleteDirectory(directory string) error {
return err
}
}

_, err := r.instance.Admin.DeleteFolder(r.ctx, admin.DeleteFolderParams{
Folder: directory,
})
Expand All @@ -171,8 +175,8 @@ func (r *Cloudinary) Directories(path string) ([]string, error) {

// Exists checks if a file exists in the Cloudinary storage.
func (r *Cloudinary) Exists(file string) bool {
asset, err := r.getAsset(file)
if err != nil || asset.Error.Message != "" {
_, err := r.getAsset(file)
if err != nil {
return false
}
return true
Expand Down Expand Up @@ -251,10 +255,14 @@ func (r *Cloudinary) Missing(file string) bool {

// Move moves a file to a new location.
func (r *Cloudinary) Move(source, destination string) error {
asset, err := r.getAsset(source)
if err != nil {
return err
}
rename, err := r.instance.Upload.Rename(r.ctx, uploader.RenameParams{
FromPublicID: r.getPublicId(source),
ToPublicID: r.getPublicId(destination),
ResourceType: r.getResourceType(destination),
FromPublicID: asset.PublicID,
ToPublicID: destination,
ResourceType: asset.ResourceType,
})
if err != nil {
return err
Expand All @@ -278,24 +286,32 @@ func (r *Cloudinary) Put(file, content string) error {
return err
}
_, err = r.instance.Upload.Upload(r.ctx, tempFile.Name(), uploader.UploadParams{
PublicID: r.getPublicId(file),
PublicID: file,
UseFilename: api.Bool(true),
UniqueFilename: api.Bool(false),
ResourceType: r.getResourceType(file),
ResourceType: "auto",
})
return err
}

// PutFile stores a new file on the disk.
func (r *Cloudinary) PutFile(path string, source filesystem.File) (string, error) {
return r.PutFileAs(path, source, source.File())
uploadResult, err := r.instance.Upload.Upload(r.ctx, source.File(), uploader.UploadParams{
Folder: validPath(path),
UseFilename: api.Bool(true),
UniqueFilename: api.Bool(false),
})
if err != nil {
return "", err
}
return uploadResult.PublicID, nil
}

// PutFileAs stores a new file on the disk.
func (r *Cloudinary) PutFileAs(path string, source filesystem.File, name string) (string, error) {
uploadResult, err := r.instance.Upload.Upload(r.ctx, source.File(), uploader.UploadParams{
Folder: validPath(path),
PublicID: r.getPublicId(name),
PublicID: name,
Copy link
Contributor

Choose a reason for hiding this comment

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

Q: Can the name contain extension?

Copy link
Member Author

@kkumar-gcc kkumar-gcc Sep 4, 2023

Choose a reason for hiding this comment

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

If you are following cloudinary then u shouldn't but it won't give any error.
BUT URL OF FILE will contain two file extensions ie .../filename.png.png.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we'd better follow the cloudinary suggestion.

Copy link
Member Author

@kkumar-gcc kkumar-gcc Sep 4, 2023

Choose a reason for hiding this comment

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

I think we'd better follow the cloudinary suggestion.

Yeah, we are following cloudinay(user's choice).

UseFilename: api.Bool(true),
UniqueFilename: api.Bool(false),
})
Expand Down Expand Up @@ -339,11 +355,22 @@ func (r *Cloudinary) Url(file string) string {
}

func (r *Cloudinary) getAsset(path string) (*uploader.ExplicitResult, error) {
return r.instance.Upload.Explicit(r.ctx, uploader.ExplicitParams{
PublicID: r.getPublicId(path),
Type: "upload",
ResourceType: r.getResourceType(path),
})
// TODO: Search if there is a better way to get asset info
assetTypes := []api.AssetType{api.Image, api.Video, api.File}
Copy link
Contributor

Choose a reason for hiding this comment

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

Q: Why is there no api.Raw?

Copy link
Member Author

@kkumar-gcc kkumar-gcc Sep 4, 2023

Choose a reason for hiding this comment

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

api.File is actually api.Raw.

Copy link
Contributor

Choose a reason for hiding this comment

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

Why?

Copy link
Member Author

@kkumar-gcc kkumar-gcc Sep 4, 2023

Choose a reason for hiding this comment

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

for _, assetType := range assetTypes {
explicit, err := r.instance.Upload.Explicit(r.ctx, uploader.ExplicitParams{
PublicID: path,
Type: "upload",
ResourceType: string(assetType),
})
if err != nil {
return nil, err
}
if explicit.Error.Message == "" {
return explicit, nil
}
}
return nil, errors.New("file not found")
}

func (r *Cloudinary) tempFile(content string) (*os.File, error) {
Expand All @@ -358,34 +385,3 @@ func (r *Cloudinary) tempFile(content string) (*os.File, error) {

return tempFile, nil
}

func (r *Cloudinary) getResourceType(path string) string {
extension := strings.TrimPrefix(filepath.Ext(path), ".")
value := "image"
resourceTypes := r.config.Get(fmt.Sprintf("filesystems.disks.%s.resource_types", r.disk), defaultResourcesTypes()).(map[string][]string)

for resourceType, extensions := range resourceTypes {
for _, ext := range extensions {
if ext == extension {
value = resourceType
break
}
}
}

return value
}

func (r *Cloudinary) getPublicId(path string) string {
basename := filepath.Base(path)
dirname := filepath.Dir(path)
filename := strings.TrimSuffix(basename, filepath.Ext(basename))
if r.getResourceType(path) == "raw" {
filename = basename
}
// Prepend the dirname if it exists and is not "."
if dirname != "." {
return filepath.Join(dirname, filename)
}
return filename
}
7 changes: 1 addition & 6 deletions cloudinary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ func TestStorage(t *testing.T) {
mockConfig.On("GetString", "filesystems.disks.cloudinary.key").Return(os.Getenv("CLOUDINARY_ACCESS_KEY_ID"))
mockConfig.On("GetString", "filesystems.disks.cloudinary.secret").Return(os.Getenv("CLOUDINARY_ACCESS_KEY_SECRET"))
mockConfig.On("GetString", "filesystems.disks.cloudinary.cloud").Return(os.Getenv("CLOUDINARY_CLOUD"))
mockConfig.On("Get", "filesystems.disks.cloudinary.resource_types", defaultResourcesTypes()).Return(map[string][]string{
"image": {"png"},
"video": {},
"raw": {"txt", "pdf"},
})

var driver contractsfilesystem.Driver
randNum, err := rand.Int(rand.Reader, big.NewInt(1000))
Expand Down Expand Up @@ -331,7 +326,7 @@ func TestStorage(t *testing.T) {

path, err = driver.PutFileAs(rootFolder+"PutFileAs1", fileInfo, "image1.png")
assert.Nil(t, err)
assert.Equal(t, rootFolder+"PutFileAs1/image1", path)
assert.Equal(t, rootFolder+"PutFileAs1/image1.png", path)
assert.True(t, driver.Exists(path))

assert.Nil(t, driver.DeleteDirectory(rootFolder+"PutFileAs1"))
Expand Down
8 changes: 0 additions & 8 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,3 @@ func validPath(path string) string {
realPath = strings.TrimSuffix(realPath, string(filepath.Separator))
return realPath
}

func defaultResourcesTypes() map[string][]string {
return map[string][]string{
"image": {"ai", "avif", "bmp", "bw", "djvu", "dng", "ps", "ept", "eps", "eps3", "fbx", "flif", "gif", "glb", "heif", "heic", "ico", "indd", "jpg", "jpe", "jpeg", "jp2", "wdp", "jxr", "hdp", "jxl", "obj", "pdf", "ply", "png", "psd", "arw", "cr2", "svg", "tga", "tif", "tiff", "u3ma", "usdz", "webp"},
"video": {"3g2", "3gp", "avi", "flv", "m3u8", "ts", "m2ts", "mts", "mov", "mkv", "mp4", "mpeg", "mpd", "mxf", "ogv", "webm", "wmv", "aac", "aiff", "amr", "flac", "m4a", "mp3", "ogg", "opus", "wav"},
"raw": {"txt", "doc", "rtf", "xls", "ppt", "docx", "xlsx", "pptx", "pps", "ppsx", "odt", "ods", "odp"},
}
}