@socialize/cloudinary

Meteor's socialize:cloudinary package ported for React Native

Usage no npm install needed!

<script type="module">
  import socializeCloudinary from 'https://cdn.skypack.dev/@socialize/cloudinary';
</script>

README

Cloudinary API And Image/File Uploader

This Package provides a simple way for uploading files to Cloudinary, which in turn can be set up to sync with your Amazon S3 service. This is useful for uploading and actively manipulating images and files that you want accessible to the public.

This is a [Meteor][meteor] package with part of it's code published as a companion NPM package made to work with clients other than Meteor. For example your server is Meteor, but you want to build a React Native app for the client. This allows you to share code between your Meteor server and other clients to give you a competitive advantage when bringing your mobile and web application to market.

Prior Art

This project is based heavily on lepozepo:cloudinary. Coffeescript has been converted to ES2015, Modules are now implemented, no more dependence on jQuery or Blaze, functions that call server methods now return promises, and client side cloudinary config has been tweaked to bring it in line with the server side implementation.

Supporting The Project

Finding the time to maintain FOSS projects can be quite difficult. I am myself responsible for over 30 personal projects across 2 platforms, as well as Multiple others maintained by the Meteor Community Packages organization. Therfore, if you appreciate my work, I ask that you either sponsor my work through GitHub, or donate via Paypal or Patreon. Every dollar helps give cause for spending my free time fielding issues, feature requests, pull requests and releasing updates. Info can be found in the "Sponsor this project" section of the GitHub Repo

Features

  • Frontend agnostic
  • Signed URLs
  • Expiring URLs
  • Download URLs
  • Auththentication Rules
  • Client side signed uploads

Meteor Installation

Cloudinary is built on Cloudinary (NPM) and Cloudinary (JS). These packages must be installed from NPM for this package to work.

meteor npm install --save cloudinary cloudinary-core
meteor add socialize:cloudinary

NPM Installation

When installing the npm package, npm takes care of installing cloudinary deps and theres no need to install them like is necessary inside the Meteor app.

npm install --save @socialize/cloudinary

Usage Outside Meteor

The client side parts of this package are published to NPM as @socialize/cloudinary for use in front ends outside of Meteor.

When using the npm package you'll need to connect to a server, which hosts the server side Meteor code for your app, using Meteor.connect as per the @socialize/react-native-meteor usage example documentation.

Meteor.connect('ws://192.168.X.X:3000/websocket');

React Native

When using this package with React Native there is some minor setup required by the @socialize/react-native-meteor package. See @socialize/react-native-meteor react-native for necessary instructions.

Configuration

Server

import { Cloudinary } from 'meteor/socialize:cloudinary';

Cloudinary.config({
  cloud_name: 'cloud_name',
  api_key: '1237419',
  api_secret: 'asdf24adsfjk',
});

// Rules are bound to the connection from which they are are executed. This means you have a userId available as this.userId if there is a logged in user. Throw a new Meteor.Error to stop the method from executing and propagate the error to the client. If rule is not set a standard error will be thrown.
Cloudinary.rules.delete = function (publicId) {
  if (!this.userId && !publicId) throw new Meteor.Error("Not Authorized", "Sorry, you can't do that!");
};

Cloudinary.rules.sign_upload = function () {
  if (!this.userId) throw new Meteor.Error("Not Authorized", "Sorry, you can't do that!")
};

Cloudinary.rules.private_resource = function (publicId) {
  if (!this.userId && !publicId) throw new Meteor.Error("Not Authorized", "Sorry, you can't do that!");
};

Cloudinary.rules.download_url = function (publicId) {
  if (!this.userId && !publicId) throw new Meteor.Error("Not Authorized", "Sorry, you can't do that!");
};

Client

import { Cloudinary } from 'meteor/socialize:cloudinary';

Cloudinary.config({
  cloud_name:'cloud_name',
  api_key: 'Your Key Here',
});

Uploading

Wire up your input[type="file"]. CLIENT SIDE.

class Uploader extends Component {
    onChange = (e) => {
    const uploads = Cloudinary.uploadFiles(e.currentTarget.files);
    uploads.forEach(async (response) => {
      const photoData = await response;
      new Photo(photoData).save();
    });
    }
    render() {
        return (
          <input type="file" accept="image/*" multiple onChange={this.onChange} />
        );
    }
}

Uploads Collection

All uploads are stored in Cloudinary.collection with the following fields.

{
  status: 'uploading', // status of the upload
  loaded: 935, // how much of the file has been uploaded so far
  total: 10000, // the total size of the file
  percent_uploaded: 9
}

The status field can be one of uploading, complete, error, aborted. Matching on this field lets you easily find and display files that are uploading.

import { Cloudinary } from 'meteor/socialize:cloudinary';

const uploadingFiles = Cloudinary.collection.find({status:'uploading'});

const completedFiles = Cloudinary.collection.find({status:'complete'});

Manipulating and Displaying

All of Cloudinary's manipulation options can be passed to the Cloudinary.url and Cloudinary.privateUrl Methods which can be used to generate a url for an <img> tags src attribute

<img src={Cloudinary.url(public_id)}>
<img src={Cloudinary.privateUrl(public_id)}>

You can manipulate an image by adding parameters to the helper

<img src={Cloudinary.url(public_id, {effect:'blur:300' angle:"10"})}">

For more information see the cloudinary's documentation: http://cloudinary.com/documentation/image_transformations#crop_modes

Deleting From Cloudinary

Just pass the public_id of the image or file through this function. It will return an object with a list of the images deleted as a result.

// client side
try {
  const result = await Cloudinary.delete(public_id);
} catch (e) {
  console.log(e.reason);
}

Generating A Download Link

try {
  const url = await Cloudinary.downloadUrl(public_id, options);
} catch (e){
  console.log(e.reason);
}

Compatibility

If you are using the browser-policy package, don't forget to allow images from cloudinary to load on your webapp by using BrowserPolicy.content.allowImageOrigin("res.cloudinary.com")

Here are all the transformations you can apply: http://cloudinary.com/documentation/image_transformations#reference

Cordova Android Bug with Meteor 1.2+

Due to a bug in the Cordova Android version that is used with Meteor 1.2, you will need to add the following to your mobile-config.js or you will have problems with this package on Android devices:

App.accessRule("blob:*");

API

  • Cloudinary.config(options) required:

    • cloud_name: Name of your cloud
      • api_key: Your Cloudinary API Key
      • api_secret: Your Cloudinary API Secret - only set this on the server
  • async Cloudinary.uploadFile(dataUrl, config = { groupId: 'general', options: {}, callback: null }) (CLIENT): returns a promise that resolves to a json object containing information about the uploaded resource

    • dataUrl: A file that has been read as a data url
    • config: An object containing the upload configuration.
      • groupId: A string to group uploads by. This makes finding uploads that should be grouped together easier. By default the groupId is 'general'
      • options: The cloudinary configuration options
      • callback: A callback to execute if you don't wish to use async/await
  • async Cloudinary.uploadFiles(files, config = { groupId: 'general', options: {}, callback: null }) (CLIENT): returns an array of promises that each resolves to a json object containing information about the uploaded resource

    • files: An instance of, or array of instances of File or Blob
    • config: An object containing the upload configuration.
      • groupId: A string to group uploads by. This makes finding uploads that should be grouped together easier. By default the groupId is 'general'
      • options: The cloudinary configuration options
      • callback: A callback to execute if you don't wish to use async/await
  • Cloudinary.url(public_id, options) (CLIENT): returns a generated url

  • async Cloudinary.privateUrl(public_id, options) (CLIENT): returns a promise which resolves to a signed URL

  • async Cloudinary.downloadUrl(public_id) (CLIENT): returns a promise that resolves to a url that will expire in 1 hour, does not take any transformations

    • public_id: The public ID returned after uploading a resource
  • async Cloudinary.delete(public_id, type) (CLIENT): returns a promise that resolves to json object containing information about the resource that was deleted.

    • public_id: The public ID returned after uploading a resource
    • type: The type that was specified when the resource was uploaded
  • Cloudinary.rules (SERVER) required: This is a javascript object of rules as functions

    • Cloudinary.rules.delete: Checks whether deleting a resource is allowed. Throw a Meteor.Error to disallow this action
    • Cloudinary.rules.sign_upload: Checks whether uploading a resource is allowed. Throw a Meteor.Error to disallow this action
    • Cloudinary.rules.private_resource: Checks whether getting a private resource is allowed. Throw a Meteor.Error to disallow this action
    • Cloudinary.rules.download_url: Checks whether fetching a download link for a resource is allowed. Throw a Meteor.Error to disallow this action