From 136260a822987409e4d9b2aee5e1829ae4d35910 Mon Sep 17 00:00:00 2001 From: JonnyWong16 Date: Sat, 28 Apr 2018 21:44:19 -0700 Subject: [PATCH] Add cloudinary v1.11.0 --- lib/cloudinary/__init__.py | 302 ++ lib/cloudinary/api.py | 448 ++ lib/cloudinary/auth_token.py | 47 + lib/cloudinary/compat.py | 34 + lib/cloudinary/forms.py | 134 + lib/cloudinary/models.py | 121 + lib/cloudinary/poster/__init__.py | 34 + lib/cloudinary/poster/encode.py | 447 ++ lib/cloudinary/poster/streaminghttp.py | 201 + lib/cloudinary/search.py | 59 + .../static/html/cloudinary_cors.html | 43 + .../static/js/canvas-to-blob.min.js | 2 + lib/cloudinary/static/js/jquery.cloudinary.js | 4722 +++++++++++++++++ .../static/js/jquery.fileupload-image.js | 326 ++ .../static/js/jquery.fileupload-process.js | 178 + .../static/js/jquery.fileupload-validate.js | 125 + lib/cloudinary/static/js/jquery.fileupload.js | 1482 ++++++ .../static/js/jquery.iframe-transport.js | 224 + lib/cloudinary/static/js/jquery.ui.widget.js | 572 ++ .../static/js/load-image.all.min.js | 2 + .../templates/cloudinary_direct_upload.html | 12 + .../templates/cloudinary_includes.html | 14 + .../templates/cloudinary_js_config.html | 3 + lib/cloudinary/templatetags/__init__.py | 1 + lib/cloudinary/templatetags/cloudinary.py | 85 + lib/cloudinary/uploader.py | 325 ++ lib/cloudinary/utils.py | 912 ++++ 27 files changed, 10855 insertions(+) create mode 100644 lib/cloudinary/__init__.py create mode 100644 lib/cloudinary/api.py create mode 100644 lib/cloudinary/auth_token.py create mode 100644 lib/cloudinary/compat.py create mode 100644 lib/cloudinary/forms.py create mode 100644 lib/cloudinary/models.py create mode 100644 lib/cloudinary/poster/__init__.py create mode 100644 lib/cloudinary/poster/encode.py create mode 100644 lib/cloudinary/poster/streaminghttp.py create mode 100644 lib/cloudinary/search.py create mode 100644 lib/cloudinary/static/html/cloudinary_cors.html create mode 100644 lib/cloudinary/static/js/canvas-to-blob.min.js create mode 100644 lib/cloudinary/static/js/jquery.cloudinary.js create mode 100644 lib/cloudinary/static/js/jquery.fileupload-image.js create mode 100644 lib/cloudinary/static/js/jquery.fileupload-process.js create mode 100644 lib/cloudinary/static/js/jquery.fileupload-validate.js create mode 100644 lib/cloudinary/static/js/jquery.fileupload.js create mode 100644 lib/cloudinary/static/js/jquery.iframe-transport.js create mode 100644 lib/cloudinary/static/js/jquery.ui.widget.js create mode 100644 lib/cloudinary/static/js/load-image.all.min.js create mode 100644 lib/cloudinary/templates/cloudinary_direct_upload.html create mode 100644 lib/cloudinary/templates/cloudinary_includes.html create mode 100644 lib/cloudinary/templates/cloudinary_js_config.html create mode 100644 lib/cloudinary/templatetags/__init__.py create mode 100644 lib/cloudinary/templatetags/cloudinary.py create mode 100644 lib/cloudinary/uploader.py create mode 100644 lib/cloudinary/utils.py diff --git a/lib/cloudinary/__init__.py b/lib/cloudinary/__init__.py new file mode 100644 index 00000000..19a1e716 --- /dev/null +++ b/lib/cloudinary/__init__.py @@ -0,0 +1,302 @@ +from __future__ import absolute_import + +import logging +logger = logging.getLogger("Cloudinary") +ch = logging.StreamHandler() +formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') +ch.setFormatter(formatter) +logger.addHandler(ch) + +import os +import re + +from six import python_2_unicode_compatible + +from cloudinary import utils +from cloudinary.compat import urlparse, parse_qs +from cloudinary.search import Search + +CF_SHARED_CDN = "d3jpl91pxevbkh.cloudfront.net" +OLD_AKAMAI_SHARED_CDN = "cloudinary-a.akamaihd.net" +AKAMAI_SHARED_CDN = "res.cloudinary.com" +SHARED_CDN = AKAMAI_SHARED_CDN +CL_BLANK = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + +VERSION = "1.11.0" +USER_AGENT = "CloudinaryPython/" + VERSION +""" :const: USER_AGENT """ + +USER_PLATFORM = "" +""" +Additional information to be passed with the USER_AGENT, e.g. "CloudinaryMagento/1.0.1". +This value is set in platform-specific implementations that use cloudinary_php. + +The format of the value should be /Version[ (comment)]. +@see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + +**Do not set this value in application code!** +""" + + +def get_user_agent(): + """Provides the `USER_AGENT` string that is passed to the Cloudinary servers. + Prepends `USER_PLATFORM` if it is defined. + + :returns: the user agent + :rtype: str + """ + + if USER_PLATFORM == "": + return USER_AGENT + else: + return USER_PLATFORM + " " + USER_AGENT + + +def import_django_settings(): + try: + import django.conf + from django.core.exceptions import ImproperlyConfigured + try: + if 'CLOUDINARY' in dir(django.conf.settings): + return django.conf.settings.CLOUDINARY + else: + return None + except ImproperlyConfigured: + return None + except ImportError: + return None + + +class Config(object): + def __init__(self): + django_settings = import_django_settings() + if django_settings: + self.update(**django_settings) + elif os.environ.get("CLOUDINARY_CLOUD_NAME"): + self.update( + cloud_name=os.environ.get("CLOUDINARY_CLOUD_NAME"), + api_key=os.environ.get("CLOUDINARY_API_KEY"), + api_secret=os.environ.get("CLOUDINARY_API_SECRET"), + secure_distribution=os.environ.get("CLOUDINARY_SECURE_DISTRIBUTION"), + private_cdn=os.environ.get("CLOUDINARY_PRIVATE_CDN") == 'true' + ) + elif os.environ.get("CLOUDINARY_URL"): + cloudinary_url = os.environ.get("CLOUDINARY_URL") + self._parse_cloudinary_url(cloudinary_url) + + def _parse_cloudinary_url(self, cloudinary_url): + uri = urlparse(cloudinary_url.replace("cloudinary://", "http://")) + for k, v in parse_qs(uri.query).items(): + if self._is_nested_key(k): + self._put_nested_key(k, v) + else: + self.__dict__[k] = v[0] + self.update( + cloud_name=uri.hostname, + api_key=uri.username, + api_secret=uri.password, + private_cdn=uri.path != '' + ) + if uri.path != '': + self.update(secure_distribution=uri.path[1:]) + + def __getattr__(self, i): + if i in self.__dict__: + return self.__dict__[i] + else: + return None + + def update(self, **keywords): + for k, v in keywords.items(): + self.__dict__[k] = v + + def _is_nested_key(self, key): + return re.match(r'\w+\[\w+\]', key) + + def _put_nested_key(self, key, value): + chain = re.split(r'[\[\]]+', key) + chain = [key for key in chain if key] + outer = self.__dict__ + last_key = chain.pop() + for inner_key in chain: + if inner_key in outer: + inner = outer[inner_key] + else: + inner = dict() + outer[inner_key] = inner + outer = inner + if isinstance(value, list): + value = value[0] + outer[last_key] = value + +_config = Config() + + +def config(**keywords): + global _config + _config.update(**keywords) + return _config + + +def reset_config(): + global _config + _config = Config() + + +@python_2_unicode_compatible +class CloudinaryResource(object): + def __init__(self, public_id=None, format=None, version=None, + signature=None, url_options=None, metadata=None, type=None, resource_type=None, + default_resource_type=None): + self.metadata = metadata + metadata = metadata or {} + self.public_id = public_id or metadata.get('public_id') + self.format = format or metadata.get('format') + self.version = version or metadata.get('version') + self.signature = signature or metadata.get('signature') + self.type = type or metadata.get('type') or "upload" + self.resource_type = resource_type or metadata.get('resource_type') or default_resource_type + self.url_options = url_options or {} + + def __str__(self): + return self.public_id + + def __len__(self): + return len(self.public_id) if self.public_id is not None else 0 + + def validate(self): + return self.signature == self.get_expected_signature() + + def get_prep_value(self): + if None in [self.public_id, + self.type, + self.resource_type]: + return None + prep = '' + prep = prep + self.resource_type + '/' + self.type + '/' + if self.version: prep = prep + 'v' + str(self.version) + '/' + prep = prep + self.public_id + if self.format: prep = prep + '.' + self.format + return prep + + def get_presigned(self): + return self.get_prep_value() + '#' + self.get_expected_signature() + + def get_expected_signature(self): + return utils.api_sign_request({"public_id": self.public_id, "version": self.version}, config().api_secret) + + @property + def url(self): + return self.build_url(**self.url_options) + + def __build_url(self, **options): + combined_options = dict(format=self.format, version=self.version, type=self.type, + resource_type=self.resource_type or "image") + combined_options.update(options) + public_id = combined_options.get('public_id') or self.public_id + return utils.cloudinary_url(public_id, **combined_options) + + def build_url(self, **options): + return self.__build_url(**options)[0] + + def default_poster_options(self, options): + options["format"] = options.get("format", "jpg") + + def default_source_types(self): + return ['webm', 'mp4', 'ogv'] + + def image(self, **options): + if options.get("resource_type", self.resource_type) == "video": + self.default_poster_options(options) + src, attrs = self.__build_url(**options) + client_hints = attrs.pop("client_hints", config().client_hints) + responsive = attrs.pop("responsive", False) + hidpi = attrs.pop("hidpi", False) + if (responsive or hidpi) and not client_hints: + attrs["data-src"] = src + classes = "cld-responsive" if responsive else "cld-hidpi" + if "class" in attrs: classes += " " + attrs["class"] + attrs["class"] = classes + src = attrs.pop("responsive_placeholder", config().responsive_placeholder) + if src == "blank": src = CL_BLANK + + if src: attrs["src"] = src + + return u"".format(utils.html_attrs(attrs)) + + def video_thumbnail(self, **options): + self.default_poster_options(options) + return self.build_url(**options) + + # Creates an HTML video tag for the provided +source+ + # + # ==== Options + # * source_types - Specify which source type the tag should include. defaults to webm, mp4 and ogv. + # * source_transformation - specific transformations to use for a specific source type. + # * poster - override default thumbnail: + # * url: provide an ad hoc url + # * options: with specific poster transformations and/or Cloudinary +:public_id+ + # + # ==== Examples + # CloudinaryResource("mymovie.mp4").video() + # CloudinaryResource("mymovie.mp4").video(source_types = 'webm') + # CloudinaryResource("mymovie.ogv").video(poster = "myspecialplaceholder.jpg") + # CloudinaryResource("mymovie.webm").video(source_types = ['webm', 'mp4'], poster = {'effect': 'sepia'}) + def video(self, **options): + public_id = options.get('public_id', self.public_id) + source = re.sub("\.({0})$".format("|".join(self.default_source_types())), '', public_id) + + source_types = options.pop('source_types', []) + source_transformation = options.pop('source_transformation', {}) + fallback = options.pop('fallback_content', '') + options['resource_type'] = options.pop('resource_type', self.resource_type or 'video') + + if not source_types: source_types = self.default_source_types() + video_options = options.copy() + + if 'poster' in video_options: + poster_options = video_options['poster'] + if isinstance(poster_options, dict): + if 'public_id' in poster_options: + video_options['poster'] = utils.cloudinary_url(poster_options['public_id'], **poster_options)[0] + else: + video_options['poster'] = self.video_thumbnail(public_id=source, **poster_options) + else: + video_options['poster'] = self.video_thumbnail(public_id=source, **options) + + if not video_options['poster']: del video_options['poster'] + + nested_source_types = isinstance(source_types, list) and len(source_types) > 1 + if not nested_source_types: + source = source + '.' + utils.build_array(source_types)[0] + + video_url = utils.cloudinary_url(source, **video_options) + video_options = video_url[1] + if not nested_source_types: + video_options['src'] = video_url[0] + if 'html_width' in video_options: video_options['width'] = video_options.pop('html_width') + if 'html_height' in video_options: video_options['height'] = video_options.pop('html_height') + + sources = "" + if nested_source_types: + for source_type in source_types: + transformation = options.copy() + transformation.update(source_transformation.get(source_type, {})) + src = utils.cloudinary_url(source, format=source_type, **transformation)[0] + video_type = "ogg" if source_type == 'ogv' else source_type + mime_type = "video/" + video_type + sources += "".format(attributes=utils.html_attrs({'src': src, 'type': mime_type})) + + html = "".format( + attributes=utils.html_attrs(video_options), sources=sources, fallback=fallback) + return html + + +class CloudinaryImage(CloudinaryResource): + def __init__(self, public_id=None, **kwargs): + super(CloudinaryImage, self).__init__(public_id=public_id, default_resource_type="image", **kwargs) + + +class CloudinaryVideo(CloudinaryResource): + def __init__(self, public_id=None, **kwargs): + super(CloudinaryVideo, self).__init__(public_id=public_id, default_resource_type="video", **kwargs) diff --git a/lib/cloudinary/api.py b/lib/cloudinary/api.py new file mode 100644 index 00000000..ee92fa0b --- /dev/null +++ b/lib/cloudinary/api.py @@ -0,0 +1,448 @@ +# Copyright Cloudinary + +import email.utils +import json +import socket + +import cloudinary +from six import string_types + +import urllib3 +import certifi + +from cloudinary import utils +from urllib3.exceptions import HTTPError + +logger = cloudinary.logger + +# intentionally one-liners +class Error(Exception): pass +class NotFound(Error): pass +class NotAllowed(Error): pass +class AlreadyExists(Error): pass +class RateLimited(Error): pass +class BadRequest(Error): pass +class GeneralError(Error): pass +class AuthorizationRequired(Error): pass + + +EXCEPTION_CODES = { + 400: BadRequest, + 401: AuthorizationRequired, + 403: NotAllowed, + 404: NotFound, + 409: AlreadyExists, + 420: RateLimited, + 500: GeneralError +} + + +class Response(dict): + def __init__(self, result, response, **kwargs): + super(Response, self).__init__(**kwargs) + self.update(result) + self.rate_limit_allowed = int(response.headers["x-featureratelimit-limit"]) + self.rate_limit_reset_at = email.utils.parsedate(response.headers["x-featureratelimit-reset"]) + self.rate_limit_remaining = int(response.headers["x-featureratelimit-remaining"]) + +_http = urllib3.PoolManager( + cert_reqs='CERT_REQUIRED', + ca_certs=certifi.where() + ) + + +def ping(**options): + return call_api("get", ["ping"], {}, **options) + + +def usage(**options): + return call_api("get", ["usage"], {}, **options) + + +def resource_types(**options): + return call_api("get", ["resources"], {}, **options) + + +def resources(**options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", None) + uri = ["resources", resource_type] + if upload_type: uri.append(upload_type) + params = only(options, + "next_cursor", "max_results", "prefix", "tags", "context", "moderations", "direction", "start_at") + return call_api("get", uri, params, **options) + + +def resources_by_tag(tag, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "tags", tag] + params = only(options, "next_cursor", "max_results", "tags", "context", "moderations", "direction") + return call_api("get", uri, params, **options) + + +def resources_by_moderation(kind, status, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "moderations", kind, status] + params = only(options, "next_cursor", "max_results", "tags", "context", "moderations", "direction") + return call_api("get", uri, params, **options) + + +def resources_by_ids(public_ids, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type] + params = dict(only(options, "tags", "moderations", "context"), public_ids=public_ids) + return call_api("get", uri, params, **options) + + +def resource(public_id, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type, public_id] + params = only(options, "exif", "faces", "colors", "image_metadata", "pages", "phash", "coordinates", "max_results") + return call_api("get", uri, params, **options) + + +def update(public_id, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type, public_id] + params = only(options, "moderation_status", "raw_convert", + "quality_override", "ocr", + "categorization", "detection", "similarity_search", + "background_removal", "notification_url") + if "tags" in options: + params["tags"] = ",".join(utils.build_array(options["tags"])) + if "face_coordinates" in options: + params["face_coordinates"] = utils.encode_double_array(options.get("face_coordinates")) + if "custom_coordinates" in options: + params["custom_coordinates"] = utils.encode_double_array(options.get("custom_coordinates")) + if "context" in options: + params["context"] = utils.encode_context(options.get("context")) + if "auto_tagging" in options: + params["auto_tagging"] = str(options.get("auto_tagging")) + if "access_control" in options: + params["access_control"] = utils.json_encode(utils.build_list_of_dicts(options.get("access_control"))) + + return call_api("post", uri, params, **options) + + +def delete_resources(public_ids, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type] + params = __delete_resource_params(options, public_ids=public_ids) + return call_api("delete", uri, params, **options) + + +def delete_resources_by_prefix(prefix, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type] + params = __delete_resource_params(options, prefix=prefix) + return call_api("delete", uri, params, **options) + + +def delete_all_resources(**options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type] + params = __delete_resource_params(options, all=True) + return call_api("delete", uri, params, **options) + + +def delete_resources_by_tag(tag, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "tags", tag] + params = __delete_resource_params(options) + return call_api("delete", uri, params, **options) + + +def delete_derived_resources(derived_resource_ids, **options): + uri = ["derived_resources"] + params = {"derived_resource_ids": derived_resource_ids} + return call_api("delete", uri, params, **options) + + +def delete_derived_by_transformation(public_ids, transformations, + resource_type='image', type='upload', invalidate=None, + **options): + """ + Delete derived resources of public ids, identified by transformations + + :param public_ids: the base resources + :type public_ids: list of str + :param transformations: the transformation of derived resources, optionally including the format + :type transformations: list of (dict or str) + :param type: The upload type + :type type: str + :param resource_type: The type of the resource: defaults to "image" + :type resource_type: str + :param invalidate: (optional) True to invalidate the resources after deletion + :type invalidate: bool + :return: a list of the public ids for which derived resources were deleted + :rtype: dict + """ + uri = ["resources", resource_type, type] + if not isinstance(public_ids, list): + public_ids = [public_ids] + params = {"public_ids": public_ids, + "transformations": utils.build_eager(transformations), + "keep_original": True} + if invalidate is not None: + params['invalidate'] = invalidate + return call_api("delete", uri, params, **options) + + +def tags(**options): + resource_type = options.pop("resource_type", "image") + uri = ["tags", resource_type] + return call_api("get", uri, only(options, "next_cursor", "max_results", "prefix"), **options) + + +def transformations(**options): + uri = ["transformations"] + return call_api("get", uri, only(options, "next_cursor", "max_results"), **options) + + +def transformation(transformation, **options): + uri = ["transformations", transformation_string(transformation)] + return call_api("get", uri, only(options, "next_cursor", "max_results"), **options) + + +def delete_transformation(transformation, **options): + uri = ["transformations", transformation_string(transformation)] + return call_api("delete", uri, {}, **options) + + +# updates - currently only supported update is the "allowed_for_strict" boolean flag and unsafe_update +def update_transformation(transformation, **options): + uri = ["transformations", transformation_string(transformation)] + updates = only(options, "allowed_for_strict") + if "unsafe_update" in options: + updates["unsafe_update"] = transformation_string(options.get("unsafe_update")) + if not updates: raise Exception("No updates given") + + return call_api("put", uri, updates, **options) + + +def create_transformation(name, definition, **options): + uri = ["transformations", name] + return call_api("post", uri, {"transformation": transformation_string(definition)}, **options) + + +def publish_by_ids(public_ids, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "publish_resources"] + params = dict(only(options, "type", "overwrite", "invalidate"), public_ids=public_ids) + return call_api("post", uri, params, **options) + + +def publish_by_prefix(prefix, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "publish_resources"] + params = dict(only(options, "type", "overwrite", "invalidate"), prefix=prefix) + return call_api("post", uri, params, **options) + + +def publish_by_tag(tag, **options): + resource_type = options.pop("resource_type", "image") + uri = ["resources", resource_type, "publish_resources"] + params = dict(only(options, "type", "overwrite", "invalidate"), tag=tag) + return call_api("post", uri, params, **options) + + +def upload_presets(**options): + uri = ["upload_presets"] + return call_api("get", uri, only(options, "next_cursor", "max_results"), **options) + + +def upload_preset(name, **options): + uri = ["upload_presets", name] + return call_api("get", uri, only(options, "max_results"), **options) + + +def delete_upload_preset(name, **options): + uri = ["upload_presets", name] + return call_api("delete", uri, {}, **options) + + +def update_upload_preset(name, **options): + uri = ["upload_presets", name] + params = utils.build_upload_params(**options) + params = utils.cleanup_params(params) + params.update(only(options, "unsigned", "disallow_public_id")) + return call_api("put", uri, params, **options) + + +def create_upload_preset(**options): + uri = ["upload_presets"] + params = utils.build_upload_params(**options) + params = utils.cleanup_params(params) + params.update(only(options, "unsigned", "disallow_public_id", "name")) + return call_api("post", uri, params, **options) + + +def root_folders(**options): + return call_api("get", ["folders"], {}, **options) + + +def subfolders(of_folder_path, **options): + return call_api("get", ["folders", of_folder_path], {}, **options) + + +def restore(public_ids, **options): + resource_type = options.pop("resource_type", "image") + upload_type = options.pop("type", "upload") + uri = ["resources", resource_type, upload_type, "restore"] + params = dict(public_ids=public_ids) + return call_api("post", uri, params, **options) + + +def upload_mappings(**options): + uri = ["upload_mappings"] + return call_api("get", uri, only(options, "next_cursor", "max_results"), **options) + + +def upload_mapping(name, **options): + uri = ["upload_mappings"] + params = dict(folder=name) + return call_api("get", uri, params, **options) + + +def delete_upload_mapping(name, **options): + uri = ["upload_mappings"] + params = dict(folder=name) + return call_api("delete", uri, params, **options) + + +def update_upload_mapping(name, **options): + uri = ["upload_mappings"] + params = dict(folder=name) + params.update(only(options, "template")) + return call_api("put", uri, params, **options) + + +def create_upload_mapping(name, **options): + uri = ["upload_mappings"] + params = dict(folder=name) + params.update(only(options, "template")) + return call_api("post", uri, params, **options) + + +def list_streaming_profiles(**options): + uri = ["streaming_profiles"] + return call_api('GET', uri, {}, **options) + + +def get_streaming_profile(name, **options): + uri = ["streaming_profiles", name] + return call_api('GET', uri, {}, **options) + + +def delete_streaming_profile(name, **options): + uri = ["streaming_profiles", name] + return call_api('DELETE', uri, {}, **options) + + +def create_streaming_profile(name, **options): + uri = ["streaming_profiles"] + params = __prepare_streaming_profile_params(**options) + params["name"] = name + return call_api('POST', uri, params, **options) + + +def update_streaming_profile(name, **options): + uri = ["streaming_profiles", name] + params = __prepare_streaming_profile_params(**options) + return call_api('PUT', uri, params, **options) + + +def call_json_api(method, uri, jsonBody, **options): + logger.debug(jsonBody) + data = json.dumps(jsonBody).encode('utf-8') + return _call_api(method, uri, body=data, headers={'Content-Type': 'application/json'}, **options) + + +def call_api(method, uri, params, **options): + return _call_api(method, uri, params=params, **options) + + +def _call_api(method, uri, params=None, body=None, headers=None, **options): + prefix = options.pop("upload_prefix", + cloudinary.config().upload_prefix) or "https://api.cloudinary.com" + cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name) + if not cloud_name: raise Exception("Must supply cloud_name") + api_key = options.pop("api_key", cloudinary.config().api_key) + if not api_key: raise Exception("Must supply api_key") + api_secret = options.pop("api_secret", cloudinary.config().api_secret) + if not cloud_name: raise Exception("Must supply api_secret") + api_url = "/".join([prefix, "v1_1", cloud_name] + uri) + + processed_params = None + if isinstance(params, dict): + processed_params = {} + for key, value in params.items(): + if isinstance(value, list): + value_list = {"{}[{}]".format(key, i): i_value for i, i_value in enumerate(value)} + processed_params.update(value_list) + elif value: + processed_params[key] = value + + # Add authentication + req_headers = urllib3.make_headers( + basic_auth="{0}:{1}".format(api_key, api_secret), + user_agent=cloudinary.get_user_agent() + ) + if headers is not None: + req_headers.update(headers) + kw = {} + if 'timeout' in options: + kw['timeout'] = options['timeout'] + if body is not None: + kw['body'] = body + try: + response = _http.request(method.upper(), api_url, processed_params, req_headers, **kw) + body = response.data + except HTTPError as e: + raise GeneralError("Unexpected error {0}", e.message) + except socket.error as e: + raise GeneralError("Socket Error: %s" % (str(e))) + + try: + result = json.loads(body.decode('utf-8')) + except Exception as e: + # Error is parsing json + raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.status, body, e)) + + if "error" in result: + exception_class = EXCEPTION_CODES.get(response.status) or Exception + exception_class = exception_class + raise exception_class("Error {0} - {1}".format(response.status, result["error"]["message"])) + + return Response(result, response) + + +def only(source, *keys): + return {key: source[key] for key in keys if key in source} + + +def transformation_string(transformation): + if isinstance(transformation, string_types): + return transformation + else: + return cloudinary.utils.generate_transformation_string(**transformation)[0] + + +def __prepare_streaming_profile_params(**options): + params = only(options, "display_name") + if "representations" in options: + representations = [{"transformation": transformation_string(trans)} for trans in options["representations"]] + params["representations"] = json.dumps(representations) + return params + +def __delete_resource_params(options, **params): + p = dict(transformations=utils.build_eager(options.get('transformations')), + **only(options, "keep_original", "next_cursor", "invalidate")) + p.update(params) + return p diff --git a/lib/cloudinary/auth_token.py b/lib/cloudinary/auth_token.py new file mode 100644 index 00000000..72fc341e --- /dev/null +++ b/lib/cloudinary/auth_token.py @@ -0,0 +1,47 @@ +import hashlib +import hmac +import re +import time +from binascii import a2b_hex +from cloudinary.compat import quote_plus + +AUTH_TOKEN_NAME = "__cld_token__" + + + +def generate(url=None, acl=None, start_time=None, duration=None, expiration=None, ip=None, key=None, + token_name=AUTH_TOKEN_NAME): + + if expiration is None: + if duration is not None: + start = start_time if start_time is not None else int(time.mktime(time.gmtime())) + expiration = start + duration + else: + raise Exception("Must provide either expiration or duration") + + token_parts = [] + if ip is not None: token_parts.append("ip=" + ip) + if start_time is not None: token_parts.append("st=%d" % start_time) + token_parts.append("exp=%d" % expiration) + if acl is not None: token_parts.append("acl=%s" % _escape_to_lower(acl)) + to_sign = list(token_parts) + if url is not None: + to_sign.append("url=%s" % _escape_to_lower(url)) + auth = _digest("~".join(to_sign), key) + token_parts.append("hmac=%s" % auth) + return "%(token_name)s=%(token)s" % {"token_name": token_name, "token": "~".join(token_parts)} + + +def _digest(message, key): + bin_key = a2b_hex(key) + return hmac.new(bin_key, message.encode('utf-8'), hashlib.sha256).hexdigest() + + +def _escape_to_lower(url): + escaped_url = quote_plus(url) + + def toLowercase(match): + return match.group(0).lower() + + escaped_url = re.sub(r'%..', toLowercase, escaped_url) + return escaped_url diff --git a/lib/cloudinary/compat.py b/lib/cloudinary/compat.py new file mode 100644 index 00000000..430134ea --- /dev/null +++ b/lib/cloudinary/compat.py @@ -0,0 +1,34 @@ +# Copyright Cloudinary +import six.moves.urllib.parse +urlencode = six.moves.urllib.parse.urlencode +unquote = six.moves.urllib.parse.unquote +urlparse = six.moves.urllib.parse.urlparse +parse_qs = six.moves.urllib.parse.parse_qs +parse_qsl = six.moves.urllib.parse.parse_qsl +quote_plus = six.moves.urllib.parse.quote_plus +httplib = six.moves.http_client +from six import PY3, string_types, StringIO, BytesIO +urllib2 = six.moves.urllib.request +NotConnected = six.moves.http_client.NotConnected + +if PY3: + to_bytes = lambda s: s.encode('utf8') + to_bytearray = lambda s: bytearray(s, 'utf8') + to_string = lambda b: b.decode('utf8') + +else: + to_bytes = str + to_bytearray = str + to_string = str + +try: + cldrange = xrange +except NameError: + def cldrange(*args, **kwargs): + return iter(range(*args, **kwargs)) + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() diff --git a/lib/cloudinary/forms.py b/lib/cloudinary/forms.py new file mode 100644 index 00000000..3465889a --- /dev/null +++ b/lib/cloudinary/forms.py @@ -0,0 +1,134 @@ +from django import forms +from cloudinary import CloudinaryResource +import cloudinary.uploader +import cloudinary.utils +import re +import json +from django.utils.translation import ugettext_lazy as _ + + +def cl_init_js_callbacks(form, request): + for field in form.fields.values(): + if isinstance(field, CloudinaryJsFileField): + field.enable_callback(request) + + +class CloudinaryInput(forms.TextInput): + input_type = 'file' + + def render(self, name, value, attrs=None): + attrs = self.build_attrs(attrs) + options = attrs.get('options', {}) + attrs["options"] = '' + + params = cloudinary.utils.build_upload_params(**options) + if options.get("unsigned"): + params = cloudinary.utils.cleanup_params(params) + else: + params = cloudinary.utils.sign_request(params, options) + + if 'resource_type' not in options: options['resource_type'] = 'auto' + cloudinary_upload_url = cloudinary.utils.cloudinary_api_url("upload", **options) + + attrs["data-url"] = cloudinary_upload_url + attrs["data-form-data"] = json.dumps(params) + attrs["data-cloudinary-field"] = name + chunk_size = options.get("chunk_size", None) + if chunk_size: attrs["data-max-chunk-size"] = chunk_size + attrs["class"] = " ".join(["cloudinary-fileupload", attrs.get("class", "")]) + + widget = super(CloudinaryInput, self).render("file", None, attrs=attrs) + if value: + if isinstance(value, CloudinaryResource): + value_string = value.get_presigned() + else: + value_string = value + widget += forms.HiddenInput().render(name, value_string) + return widget + + +class CloudinaryJsFileField(forms.Field): + default_error_messages = { + 'required': _(u"No file selected!") + } + + def __init__(self, attrs=None, options=None, autosave=True, *args, **kwargs): + if attrs is None: attrs = {} + if options is None: options = {} + self.autosave = autosave + attrs = attrs.copy() + attrs["options"] = options.copy() + + field_options = {'widget': CloudinaryInput(attrs=attrs)} + field_options.update(kwargs) + super(CloudinaryJsFileField, self).__init__(*args, **field_options) + + def enable_callback(self, request): + from django.contrib.staticfiles.storage import staticfiles_storage + self.widget.attrs["options"]["callback"] = request.build_absolute_uri( + staticfiles_storage.url("html/cloudinary_cors.html")) + + def to_python(self, value): + """Convert to CloudinaryResource""" + if not value: return None + m = re.search(r'^([^/]+)/([^/]+)/v(\d+)/([^#]+)#([^/]+)$', value) + if not m: + raise forms.ValidationError("Invalid format") + resource_type = m.group(1) + upload_type = m.group(2) + version = m.group(3) + filename = m.group(4) + signature = m.group(5) + m = re.search(r'(.*)\.(.*)', filename) + if not m: + raise forms.ValidationError("Invalid file name") + public_id = m.group(1) + image_format = m.group(2) + return CloudinaryResource(public_id, + format=image_format, + version=version, + signature=signature, + type=upload_type, + resource_type=resource_type) + + def validate(self, value): + """Validate the signature""" + # Use the parent's handling of required fields, etc. + super(CloudinaryJsFileField, self).validate(value) + if not value: return + if not value.validate(): + raise forms.ValidationError("Signature mismatch") + + +class CloudinaryUnsignedJsFileField(CloudinaryJsFileField): + def __init__(self, upload_preset, attrs=None, options=None, autosave=True, *args, **kwargs): + if attrs is None: + attrs = {} + if options is None: + options = {} + options = options.copy() + options.update({"unsigned": True, "upload_preset": upload_preset}) + super(CloudinaryUnsignedJsFileField, self).__init__(attrs, options, autosave, *args, **kwargs) + + +class CloudinaryFileField(forms.FileField): + my_default_error_messages = { + 'required': _(u"No file selected!") + } + default_error_messages = forms.FileField.default_error_messages.copy() + default_error_messages.update(my_default_error_messages) + + def __init__(self, options=None, autosave=True, *args, **kwargs): + self.autosave = autosave + self.options = options or {} + super(CloudinaryFileField, self).__init__(*args, **kwargs) + + def to_python(self, value): + """Upload and convert to CloudinaryResource""" + value = super(CloudinaryFileField, self).to_python(value) + if not value: + return None + if self.autosave: + return cloudinary.uploader.upload_image(value, **self.options) + else: + return value diff --git a/lib/cloudinary/models.py b/lib/cloudinary/models.py new file mode 100644 index 00000000..9f15383d --- /dev/null +++ b/lib/cloudinary/models.py @@ -0,0 +1,121 @@ +import re + + +from cloudinary import CloudinaryResource, forms, uploader + +from django.core.files.uploadedfile import UploadedFile +from django.db import models + +# Add introspection rules for South, if it's installed. +try: + from south.modelsinspector import add_introspection_rules + add_introspection_rules([], ["^cloudinary.models.CloudinaryField"]) +except ImportError: + pass + +CLOUDINARY_FIELD_DB_RE = r'(?:(?Pimage|raw|video)/(?Pupload|private|authenticated)/)?(?:v(?P\d+)/)?(?P.*?)(\.(?P[^.]+))?$' + + +# Taken from six - https://pythonhosted.org/six/ +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +class CloudinaryField(models.Field): + description = "A resource stored in Cloudinary" + + def __init__(self, *args, **kwargs): + options = {'max_length': 255} + self.default_form_class = kwargs.pop("default_form_class", forms.CloudinaryFileField) + options.update(kwargs) + self.type = options.pop("type", "upload") + self.resource_type = options.pop("resource_type", "image") + self.width_field = options.pop("width_field", None) + self.height_field = options.pop("height_field", None) + super(CloudinaryField, self).__init__(*args, **options) + + def get_internal_type(self): + return 'CharField' + + def value_to_string(self, obj): + # We need to support both legacy `_get_val_from_obj` and new `value_from_object` models.Field methods. + # It would be better to wrap it with try -> except AttributeError -> fallback to legacy. + # Unfortunately, we can catch AttributeError exception from `value_from_object` function itself. + # Parsing exception string is an overkill here, that's why we check for attribute existence + + if hasattr(self, 'value_from_object'): + value = self.value_from_object(obj) + else: # fallback for legacy django versions + value = self._get_val_from_obj(obj) + + return self.get_prep_value(value) + + def parse_cloudinary_resource(self, value): + m = re.match(CLOUDINARY_FIELD_DB_RE, value) + resource_type = m.group('resource_type') or self.resource_type + upload_type = m.group('type') or self.type + return CloudinaryResource( + type=upload_type, + resource_type=resource_type, + version=m.group('version'), + public_id=m.group('public_id'), + format=m.group('format') + ) + + def from_db_value(self, value, expression, connection, context): + if value is None: + return value + return self.parse_cloudinary_resource(value) + + def to_python(self, value): + if isinstance(value, CloudinaryResource): + return value + elif isinstance(value, UploadedFile): + return value + elif value is None: + return value + else: + return self.parse_cloudinary_resource(value) + + def upload_options_with_filename(self, model_instance, filename): + return self.upload_options(model_instance) + + def upload_options(self, model_instance): + return {} + + def pre_save(self, model_instance, add): + value = super(CloudinaryField, self).pre_save(model_instance, add) + if isinstance(value, UploadedFile): + options = {"type": self.type, "resource_type": self.resource_type} + options.update(self.upload_options_with_filename(model_instance, value.name)) + instance_value = uploader.upload_resource(value, **options) + setattr(model_instance, self.attname, instance_value) + if self.width_field: + setattr(model_instance, self.width_field, instance_value.metadata['width']) + if self.height_field: + setattr(model_instance, self.height_field, instance_value.metadata['height']) + return self.get_prep_value(instance_value) + else: + return value + + def get_prep_value(self, value): + if not value: + return self.get_default() + if isinstance(value, CloudinaryResource): + return value.get_prep_value() + else: + return value + + def formfield(self, **kwargs): + options = {"type": self.type, "resource_type": self.resource_type} + options.update(kwargs.pop('options', {})) + defaults = {'form_class': self.default_form_class, 'options': options, 'autosave': False} + defaults.update(kwargs) + return super(CloudinaryField, self).formfield(**defaults) diff --git a/lib/cloudinary/poster/__init__.py b/lib/cloudinary/poster/__init__.py new file mode 100644 index 00000000..9110fa42 --- /dev/null +++ b/lib/cloudinary/poster/__init__.py @@ -0,0 +1,34 @@ +# MIT licensed code copied from https://bitbucket.org/chrisatlee/poster +# +# Copyright (c) 2011 Chris AtLee +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +"""poster module + +Support for streaming HTTP uploads, and multipart/form-data encoding + +```poster.version``` is a 3-tuple of integers representing the version number. +New releases of poster will always have a version number that compares greater +than an older version of poster. +New in version 0.6.""" + +import cloudinary.poster.streaminghttp +import cloudinary.poster.encode + +version = (0, 8, 2) # Thanks JP! diff --git a/lib/cloudinary/poster/encode.py b/lib/cloudinary/poster/encode.py new file mode 100644 index 00000000..4900eee4 --- /dev/null +++ b/lib/cloudinary/poster/encode.py @@ -0,0 +1,447 @@ +# MIT licensed code copied from https://bitbucket.org/chrisatlee/poster +"""multipart/form-data encoding module + +This module provides functions that faciliate encoding name/value pairs +as multipart/form-data suitable for a HTTP POST or PUT request. + +multipart/form-data is the standard way to upload files over HTTP""" + +__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam', + 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers', + 'multipart_encode'] + +try: + from io import UnsupportedOperation +except ImportError: + UnsupportedOperation = None + +try: + import uuid + def gen_boundary(): + """Returns a random string to use as the boundary for a message""" + return uuid.uuid4().hex +except ImportError: + import random, sha + def gen_boundary(): + """Returns a random string to use as the boundary for a message""" + bits = random.getrandbits(160) + return sha.new(str(bits)).hexdigest() + +import re, os, mimetypes +from cloudinary.compat import (PY3, string_types, to_bytes, to_string, + to_bytearray, quote_plus, advance_iterator) +try: + from email.header import Header +except ImportError: + # Python 2.4 + from email.Header import Header + +if PY3: + def encode_and_quote(data): + if data is None: + return None + return quote_plus(to_bytes(data)) + +else: + def encode_and_quote(data): + """If ``data`` is unicode, return quote_plus(data.encode("utf-8")) otherwise return quote_plus(data)""" + if data is None: + return None + + if isinstance(data, unicode): + data = data.encode("utf-8") + return quote_plus(data) + +if PY3: + def _strify(s): + if s is None: + return None + elif isinstance(s, bytes): + return s + else: + try: + return to_bytes(s) + except AttributeError: + return to_bytes(str(s)) +else: + def _strify(s): + """If s is a unicode string, encode it to UTF-8 and return the results, otherwise return str(s), or None if s is None""" + if s is None: + return None + if isinstance(s, unicode): + return s.encode("utf-8") + return str(s) + +class MultipartParam(object): + """Represents a single parameter in a multipart/form-data request + + ``name`` is the name of this parameter. + + If ``value`` is set, it must be a string or unicode object to use as the + data for this parameter. + + If ``filename`` is set, it is what to say that this parameter's filename + is. Note that this does not have to be the actual filename any local file. + + If ``filetype`` is set, it is used as the Content-Type for this parameter. + If unset it defaults to "text/plain; charset=utf8" + + If ``filesize`` is set, it specifies the length of the file ``fileobj`` + + If ``fileobj`` is set, it must be a file-like object that supports + .read(). + + Both ``value`` and ``fileobj`` must not be set, doing so will + raise a ValueError assertion. + + If ``fileobj`` is set, and ``filesize`` is not specified, then + the file's size will be determined first by stat'ing ``fileobj``'s + file descriptor, and if that fails, by seeking to the end of the file, + recording the current position as the size, and then by seeking back to the + beginning of the file. + + ``cb`` is a callable which will be called from iter_encode with (self, + current, total), representing the current parameter, current amount + transferred, and the total size. + """ + def __init__(self, name, value=None, filename=None, filetype=None, + filesize=None, fileobj=None, cb=None): + self.name = Header(name).encode() + self.value = _strify(value) + if filename is None: + self.filename = None + else: + if PY3: + byte_filename = filename.encode("ascii", "xmlcharrefreplace") + self.filename = to_string(byte_filename) + encoding = 'unicode_escape' + else: + if isinstance(filename, unicode): + # Encode with XML entities + self.filename = filename.encode("ascii", "xmlcharrefreplace") + else: + self.filename = str(filename) + encoding = 'string_escape' + self.filename = self.filename.encode(encoding).replace(to_bytes('"'), to_bytes('\\"')) + self.filetype = _strify(filetype) + + self.filesize = filesize + self.fileobj = fileobj + self.cb = cb + + if self.value is not None and self.fileobj is not None: + raise ValueError("Only one of value or fileobj may be specified") + + if fileobj is not None and filesize is None: + # Try and determine the file size + try: + self.filesize = os.fstat(fileobj.fileno()).st_size + except (OSError, AttributeError, UnsupportedOperation): + try: + fileobj.seek(0, 2) + self.filesize = fileobj.tell() + fileobj.seek(0) + except: + raise ValueError("Could not determine filesize") + + def __cmp__(self, other): + attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj'] + myattrs = [getattr(self, a) for a in attrs] + oattrs = [getattr(other, a) for a in attrs] + return cmp(myattrs, oattrs) + + def reset(self): + if self.fileobj is not None: + self.fileobj.seek(0) + elif self.value is None: + raise ValueError("Don't know how to reset this parameter") + + @classmethod + def from_file(cls, paramname, filename): + """Returns a new MultipartParam object constructed from the local + file at ``filename``. + + ``filesize`` is determined by os.path.getsize(``filename``) + + ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] + + ``filename`` is set to os.path.basename(``filename``) + """ + + return cls(paramname, filename=os.path.basename(filename), + filetype=mimetypes.guess_type(filename)[0], + filesize=os.path.getsize(filename), + fileobj=open(filename, "rb")) + + @classmethod + def from_params(cls, params): + """Returns a list of MultipartParam objects from a sequence of + name, value pairs, MultipartParam instances, + or from a mapping of names to values + + The values may be strings or file objects, or MultipartParam objects. + MultipartParam object names must match the given names in the + name,value pairs or mapping, if applicable.""" + if hasattr(params, 'items'): + params = params.items() + + retval = [] + for item in params: + if isinstance(item, cls): + retval.append(item) + continue + name, value = item + if isinstance(value, cls): + assert value.name == name + retval.append(value) + continue + if hasattr(value, 'read'): + # Looks like a file object + filename = getattr(value, 'name', None) + if filename is not None: + filetype = mimetypes.guess_type(filename)[0] + else: + filetype = None + + retval.append(cls(name=name, filename=filename, + filetype=filetype, fileobj=value)) + else: + retval.append(cls(name, value)) + return retval + + def encode_hdr(self, boundary): + """Returns the header of the encoding of this parameter""" + boundary = encode_and_quote(boundary) + + headers = ["--%s" % boundary] + + if self.filename: + disposition = 'form-data; name="%s"; filename="%s"' % (self.name, + to_string(self.filename)) + else: + disposition = 'form-data; name="%s"' % self.name + + headers.append("Content-Disposition: %s" % disposition) + + if self.filetype: + filetype = to_string(self.filetype) + else: + filetype = "text/plain; charset=utf-8" + + headers.append("Content-Type: %s" % filetype) + + headers.append("") + headers.append("") + + return "\r\n".join(headers) + + def encode(self, boundary): + """Returns the string encoding of this parameter""" + if self.value is None: + value = self.fileobj.read() + else: + value = self.value + + if re.search(to_bytes("^--%s$" % re.escape(boundary)), value, re.M): + raise ValueError("boundary found in encoded string") + + return to_bytes(self.encode_hdr(boundary)) + value + b"\r\n" + + def iter_encode(self, boundary, blocksize=4096): + """Yields the encoding of this parameter + If self.fileobj is set, then blocks of ``blocksize`` bytes are read and + yielded.""" + total = self.get_size(boundary) + current = 0 + if self.value is not None: + block = self.encode(boundary) + current += len(block) + yield block + if self.cb: + self.cb(self, current, total) + else: + block = to_bytes(self.encode_hdr(boundary)) + current += len(block) + yield block + if self.cb: + self.cb(self, current, total) + last_block = to_bytearray("") + encoded_boundary = "--%s" % encode_and_quote(boundary) + boundary_exp = re.compile(to_bytes("^%s$" % re.escape(encoded_boundary)), + re.M) + while True: + block = self.fileobj.read(blocksize) + if not block: + current += 2 + yield to_bytes("\r\n") + if self.cb: + self.cb(self, current, total) + break + last_block += block + if boundary_exp.search(last_block): + raise ValueError("boundary found in file data") + last_block = last_block[-len(to_bytes(encoded_boundary))-2:] + current += len(block) + yield block + if self.cb: + self.cb(self, current, total) + + def get_size(self, boundary): + """Returns the size in bytes that this param will be when encoded + with the given boundary.""" + if self.filesize is not None: + valuesize = self.filesize + else: + valuesize = len(self.value) + + return len(self.encode_hdr(boundary)) + 2 + valuesize + +def encode_string(boundary, name, value): + """Returns ``name`` and ``value`` encoded as a multipart/form-data + variable. ``boundary`` is the boundary string used throughout + a single request to separate variables.""" + + return MultipartParam(name, value).encode(boundary) + +def encode_file_header(boundary, paramname, filesize, filename=None, + filetype=None): + """Returns the leading data for a multipart/form-data field that contains + file data. + + ``boundary`` is the boundary string used throughout a single request to + separate variables. + + ``paramname`` is the name of the variable in this request. + + ``filesize`` is the size of the file data. + + ``filename`` if specified is the filename to give to this field. This + field is only useful to the server for determining the original filename. + + ``filetype`` if specified is the MIME type of this file. + + The actual file data should be sent after this header has been sent. + """ + + return MultipartParam(paramname, filesize=filesize, filename=filename, + filetype=filetype).encode_hdr(boundary) + +def get_body_size(params, boundary): + """Returns the number of bytes that the multipart/form-data encoding + of ``params`` will be.""" + size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) + return size + len(boundary) + 6 + +def get_headers(params, boundary): + """Returns a dictionary with Content-Type and Content-Length headers + for the multipart/form-data encoding of ``params``.""" + headers = {} + boundary = quote_plus(boundary) + headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary + headers['Content-Length'] = str(get_body_size(params, boundary)) + return headers + +class multipart_yielder: + def __init__(self, params, boundary, cb): + self.params = params + self.boundary = boundary + self.cb = cb + + self.i = 0 + self.p = None + self.param_iter = None + self.current = 0 + self.total = get_body_size(params, boundary) + + def __iter__(self): + return self + + def __next__(self): + return self.next() + + def next(self): + """generator function to yield multipart/form-data representation + of parameters""" + if self.param_iter is not None: + try: + block = advance_iterator(self.param_iter) + self.current += len(block) + if self.cb: + self.cb(self.p, self.current, self.total) + return block + except StopIteration: + self.p = None + self.param_iter = None + + if self.i is None: + raise StopIteration + elif self.i >= len(self.params): + self.param_iter = None + self.p = None + self.i = None + block = to_bytes("--%s--\r\n" % self.boundary) + self.current += len(block) + if self.cb: + self.cb(self.p, self.current, self.total) + return block + + self.p = self.params[self.i] + self.param_iter = self.p.iter_encode(self.boundary) + self.i += 1 + return advance_iterator(self) + + def reset(self): + self.i = 0 + self.current = 0 + for param in self.params: + param.reset() + +def multipart_encode(params, boundary=None, cb=None): + """Encode ``params`` as multipart/form-data. + + ``params`` should be a sequence of (name, value) pairs or MultipartParam + objects, or a mapping of names to values. + Values are either strings parameter values, or file-like objects to use as + the parameter value. The file-like objects must support .read() and either + .fileno() or both .seek() and .tell(). + + If ``boundary`` is set, then it as used as the MIME boundary. Otherwise + a randomly generated boundary will be used. In either case, if the + boundary string appears in the parameter values a ValueError will be + raised. + + If ``cb`` is set, it should be a callback which will get called as blocks + of data are encoded. It will be called with (param, current, total), + indicating the current parameter being encoded, the current amount encoded, + and the total amount to encode. + + Returns a tuple of `datagen`, `headers`, where `datagen` is a + generator that will yield blocks of data that make up the encoded + parameters, and `headers` is a dictionary with the assoicated + Content-Type and Content-Length headers. + + Examples: + + >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] ) + >>> s = "".join(datagen) + >>> assert "value2" in s and "value1" in s + + >>> p = MultipartParam("key", "value2") + >>> datagen, headers = multipart_encode( [("key", "value1"), p] ) + >>> s = "".join(datagen) + >>> assert "value2" in s and "value1" in s + + >>> datagen, headers = multipart_encode( {"key": "value1"} ) + >>> s = "".join(datagen) + >>> assert "value2" not in s and "value1" in s + + """ + if boundary is None: + boundary = gen_boundary() + else: + boundary = quote_plus(boundary) + + headers = get_headers(params, boundary) + params = MultipartParam.from_params(params) + + return multipart_yielder(params, boundary, cb), headers diff --git a/lib/cloudinary/poster/streaminghttp.py b/lib/cloudinary/poster/streaminghttp.py new file mode 100644 index 00000000..d8af5212 --- /dev/null +++ b/lib/cloudinary/poster/streaminghttp.py @@ -0,0 +1,201 @@ +# MIT licensed code copied from https://bitbucket.org/chrisatlee/poster +"""Streaming HTTP uploads module. + +This module extends the standard httplib and urllib2 objects so that +iterable objects can be used in the body of HTTP requests. + +In most cases all one should have to do is call :func:`register_openers()` +to register the new streaming http handlers which will take priority over +the default handlers, and then you can use iterable objects in the body +of HTTP requests. + +**N.B.** You must specify a Content-Length header if using an iterable object +since there is no way to determine in advance the total size that will be +yielded, and there is no way to reset an interator. + +Example usage: + +>>> from StringIO import StringIO +>>> import urllib2, poster.streaminghttp + +>>> opener = poster.streaminghttp.register_openers() + +>>> s = "Test file data" +>>> f = StringIO(s) + +>>> req = urllib2.Request("http://localhost:5000", f, +... {'Content-Length': str(len(s))}) +""" + +import sys, socket +from cloudinary.compat import httplib, urllib2, NotConnected + +__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler', + 'StreamingHTTPHandler', 'register_openers'] + +if hasattr(httplib, 'HTTPS'): + __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection']) + +class _StreamingHTTPMixin: + """Mixin class for HTTP and HTTPS connections that implements a streaming + send method.""" + def send(self, value): + """Send ``value`` to the server. + + ``value`` can be a string object, a file-like object that supports + a .read() method, or an iterable object that supports a .next() + method. + """ + # Based on python 2.6's httplib.HTTPConnection.send() + if self.sock is None: + if self.auto_open: + self.connect() + else: + raise NotConnected() + + # send the data to the server. if we get a broken pipe, then close + # the socket. we want to reconnect when somebody tries to send again. + # + # NOTE: we DO propagate the error, though, because we cannot simply + # ignore the error... the caller will know if they can retry. + if self.debuglevel > 0: + print("send:", repr(value)) + try: + blocksize = 8192 + if hasattr(value, 'read') : + if hasattr(value, 'seek'): + value.seek(0) + if self.debuglevel > 0: + print("sendIng a read()able") + data = value.read(blocksize) + while data: + self.sock.sendall(data) + data = value.read(blocksize) + elif hasattr(value, 'next'): + if hasattr(value, 'reset'): + value.reset() + if self.debuglevel > 0: + print("sendIng an iterable") + for data in value: + self.sock.sendall(data) + else: + self.sock.sendall(value) + except socket.error: + e = sys.exc_info()[1] + if e[0] == 32: # Broken pipe + self.close() + raise + +class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection): + """Subclass of `httplib.HTTPConnection` that overrides the `send()` method + to support iterable body objects""" + +class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler): + """Subclass of `urllib2.HTTPRedirectHandler` that overrides the + `redirect_request` method to properly handle redirected POST requests + + This class is required because python 2.5's HTTPRedirectHandler does + not remove the Content-Type or Content-Length headers when requesting + the new resource, but the body of the original request is not preserved. + """ + + handler_order = urllib2.HTTPRedirectHandler.handler_order - 1 + + # From python2.6 urllib2's HTTPRedirectHandler + def redirect_request(self, req, fp, code, msg, headers, newurl): + """Return a Request or None in response to a redirect. + + This is called by the http_error_30x methods when a + redirection response is received. If a redirection should + take place, return a new Request to allow http_error_30x to + perform the redirect. Otherwise, raise HTTPError if no-one + else should try to handle this url. Return None if you can't + but another Handler might. + """ + m = req.get_method() + if (code in (301, 302, 303, 307) and m in ("GET", "HEAD") + or code in (301, 302, 303) and m == "POST"): + # Strictly (according to RFC 2616), 301 or 302 in response + # to a POST MUST NOT cause a redirection without confirmation + # from the user (of urllib2, in this case). In practice, + # essentially all clients do redirect in this case, so we + # do the same. + # be conciliant with URIs containing a space + newurl = newurl.replace(' ', '%20') + newheaders = dict((k, v) for k, v in req.headers.items() + if k.lower() not in ( + "content-length", "content-type") + ) + return urllib2.Request(newurl, + headers=newheaders, + origin_req_host=req.get_origin_req_host(), + unverifiable=True) + else: + raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp) + +class StreamingHTTPHandler(urllib2.HTTPHandler): + """Subclass of `urllib2.HTTPHandler` that uses + StreamingHTTPConnection as its http connection class.""" + + handler_order = urllib2.HTTPHandler.handler_order - 1 + + def http_open(self, req): + """Open a StreamingHTTPConnection for the given request""" + return self.do_open(StreamingHTTPConnection, req) + + def http_request(self, req): + """Handle a HTTP request. Make sure that Content-Length is specified + if we're using an interable value""" + # Make sure that if we're using an iterable object as the request + # body, that we've also specified Content-Length + if req.has_data(): + data = req.get_data() + if hasattr(data, 'read') or hasattr(data, 'next'): + if not req.has_header('Content-length'): + raise ValueError( + "No Content-Length specified for iterable body") + return urllib2.HTTPHandler.do_request_(self, req) + +if hasattr(httplib, 'HTTPS'): + class StreamingHTTPSConnection(_StreamingHTTPMixin, + httplib.HTTPSConnection): + """Subclass of `httplib.HTTSConnection` that overrides the `send()` + method to support iterable body objects""" + + class StreamingHTTPSHandler(urllib2.HTTPSHandler): + """Subclass of `urllib2.HTTPSHandler` that uses + StreamingHTTPSConnection as its http connection class.""" + + handler_order = urllib2.HTTPSHandler.handler_order - 1 + + def https_open(self, req): + return self.do_open(StreamingHTTPSConnection, req) + + def https_request(self, req): + # Make sure that if we're using an iterable object as the request + # body, that we've also specified Content-Length + if req.has_data(): + data = req.get_data() + if hasattr(data, 'read') or hasattr(data, 'next'): + if not req.has_header('Content-length'): + raise ValueError( + "No Content-Length specified for iterable body") + return urllib2.HTTPSHandler.do_request_(self, req) + + +def get_handlers(): + handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler] + if hasattr(httplib, "HTTPS"): + handlers.append(StreamingHTTPSHandler) + return handlers + +def register_openers(): + """Register the streaming http handlers in the global urllib2 default + opener object. + + Returns the created OpenerDirector object.""" + opener = urllib2.build_opener(*get_handlers()) + + urllib2.install_opener(opener) + + return opener diff --git a/lib/cloudinary/search.py b/lib/cloudinary/search.py new file mode 100644 index 00000000..2decef84 --- /dev/null +++ b/lib/cloudinary/search.py @@ -0,0 +1,59 @@ +import json +from copy import deepcopy +from . import api + + +class Search: + """Build and execute a search query.""" + def __init__(self): + self.query = {} + + def expression(self, value): + """Specify the search query expression.""" + self.query["expression"] = value + return self + + def max_results(self, value): + """Set the max results to return""" + self.query["max_results"] = value + return self + + def next_cursor(self, value): + """Get next page in the query using the ``next_cursor`` value from a previous invocation.""" + self.query["next_cursor"] = value + return self + + def sort_by(self, field_name, direction=None): + """Add a field to sort results by. If not provided, direction is ``desc``.""" + if direction is None: + direction = 'desc' + self._add("sort_by", {field_name: direction}) + return self + + def aggregate(self, value): + """Aggregate field.""" + self._add("aggregate", value) + return self + + def with_field(self, value): + """Request an additional field in the result set.""" + self._add("with_field", value) + return self + + def to_json(self): + return json.dumps(self.query) + + def execute(self, **options): + """Execute the search and return results.""" + options["content_type"] = 'application/json' + uri = ['resources','search'] + return api.call_json_api('post', uri, self.as_dict(), **options) + + def _add(self, name, value): + if name not in self.query: + self.query[name] = [] + self.query[name].append(value) + return self + + def as_dict(self): + return deepcopy(self.query) \ No newline at end of file diff --git a/lib/cloudinary/static/html/cloudinary_cors.html b/lib/cloudinary/static/html/cloudinary_cors.html new file mode 100644 index 00000000..14ce4206 --- /dev/null +++ b/lib/cloudinary/static/html/cloudinary_cors.html @@ -0,0 +1,43 @@ + + + + + + + + + + diff --git a/lib/cloudinary/static/js/canvas-to-blob.min.js b/lib/cloudinary/static/js/canvas-to-blob.min.js new file mode 100644 index 00000000..97fc875b --- /dev/null +++ b/lib/cloudinary/static/js/canvas-to-blob.min.js @@ -0,0 +1,2 @@ +!function(t){"use strict";var e=t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype,o=t.Blob&&function(){try{return Boolean(new Blob)}catch(t){return!1}}(),n=o&&t.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(t){return!1}}(),r=t.BlobBuilder||t.WebKitBlobBuilder||t.MozBlobBuilder||t.MSBlobBuilder,a=/^data:((.*?)(;charset=.*?)?)(;base64)?,/,i=(o||r)&&t.atob&&t.ArrayBuffer&&t.Uint8Array&&function(t){var e,i,l,u,c,f,b,d,B;if(!(e=t.match(a)))throw new Error("invalid data URI");for(i=e[2]?e[1]:"text/plain"+(e[3]||";charset=US-ASCII"),l=!!e[4],u=t.slice(e[0].length),c=l?atob(u):decodeURIComponent(u),f=new ArrayBuffer(c.length),b=new Uint8Array(f),d=0;d true + * + #isObject([1, 2, 3]); + * // => true + * + #isObject(1); + * // => false + */ + isObject = function(value) { + var type; + type = typeof value; + return !!value && (type === 'object' || type === 'function'); + }; + funcTag = '[object Function]'; + + /** + * Checks if `value` is classified as a `Function` object. + * @function Util.isFunction + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * function Foo(){}; + * isFunction(Foo); + * // => true + * + * isFunction(/abc/); + * // => false + */ + isFunction = function(value) { + return isObject(value) && objToString.call(value) === funcTag; + }; + + /*********** lodash functions */ + + /** Used to match words to create compound words. */ + reWords = (function() { + var lower, upper; + upper = '[A-Z]'; + lower = '[a-z]+'; + return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); + })(); + + /** + * Convert string to camelCase + * @function Util.camelCase + * @param {string} string - the string to convert + * @return {string} in camelCase format + */ + camelCase = function(source) { + var i, word, words; + words = source.match(reWords); + words = (function() { + var j, len, results; + results = []; + for (i = j = 0, len = words.length; j < len; i = ++j) { + word = words[i]; + word = word.toLocaleLowerCase(); + if (i) { + results.push(word.charAt(0).toLocaleUpperCase() + word.slice(1)); + } else { + results.push(word); + } + } + return results; + })(); + return words.join(''); + }; + + /** + * Convert string to snake_case + * @function Util.snakeCase + * @param {string} string - the string to convert + * @return {string} in snake_case format + */ + snakeCase = function(source) { + var i, word, words; + words = source.match(reWords); + words = (function() { + var j, len, results; + results = []; + for (i = j = 0, len = words.length; j < len; i = ++j) { + word = words[i]; + results.push(word.toLocaleLowerCase()); + } + return results; + })(); + return words.join('_'); + }; + convertKeys = function(source, converter) { + var key, result, value; + if (converter == null) { + converter = Util.identity; + } + result = {}; + for (key in source) { + value = source[key]; + key = converter(key); + if (!Util.isEmpty(key)) { + result[key] = value; + } + } + return result; + }; + + /** + * Create a copy of the source object with all keys in camelCase + * @function Util.withCamelCaseKeys + * @param {Object} value - the object to copy + * @return {Object} a new object + */ + withCamelCaseKeys = function(source) { + return convertKeys(source, Util.camelCase); + }; + + /** + * Create a copy of the source object with all keys in snake_case + * @function Util.withSnakeCaseKeys + * @param {Object} value - the object to copy + * @return {Object} a new object + */ + withSnakeCaseKeys = function(source) { + return convertKeys(source, Util.snakeCase); + }; + base64Encode = typeof btoa !== 'undefined' && isFunction(btoa) ? btoa : typeof Buffer !== 'undefined' && isFunction(Buffer) ? function(input) { + if (!(input instanceof Buffer)) { + input = new Buffer.from(String(input), 'binary'); + } + return input.toString('base64'); + } : function(input) { + throw new Error("No base64 encoding function found"); + }; + + /** + * Returns the Base64-decoded version of url.
+ * This method delegates to `btoa` if present. Otherwise it tries `Buffer`. + * @function Util.base64EncodeURL + * @param {string} url - the url to encode. the value is URIdecoded and then re-encoded before converting to base64 representation + * @return {string} the base64 representation of the URL + */ + base64EncodeURL = function(input) { + var error1, ignore; + try { + input = decodeURI(input); + } catch (error1) { + ignore = error1; + } + input = encodeURI(input); + return base64Encode(input); + }; + BaseUtil = { + allStrings: allStrings, + camelCase: camelCase, + convertKeys: convertKeys, + defaults: defaults, + snakeCase: snakeCase, + without: without, + isFunction: isFunction, + isNumberLike: isNumberLike, + smartEscape: smartEscape, + withCamelCaseKeys: withCamelCaseKeys, + withSnakeCaseKeys: withSnakeCaseKeys, + base64EncodeURL: base64EncodeURL + }; + + /** + * Includes utility methods and lodash / jQuery shims + */ + + /** + * Get data from the DOM element. + * + * This method will use jQuery's `data()` method if it is available, otherwise it will get the `data-` attribute + * @param {Element} element - the element to get the data from + * @param {string} name - the name of the data item + * @returns the value associated with the `name` + * @function Util.getData + */ + getData = function(element, name) { + return jQuery(element).data(name); + }; + + /** + * Set data in the DOM element. + * + * This method will use jQuery's `data()` method if it is available, otherwise it will set the `data-` attribute + * @function Util.setData + * @param {Element} element - the element to set the data in + * @param {string} name - the name of the data item + * @param {*} value - the value to be set + * + */ + setData = function(element, name, value) { + return jQuery(element).data(name, value); + }; + + /** + * Get attribute from the DOM element. + * + * This method will use jQuery's `attr()` method if it is available, otherwise it will get the attribute directly + * @function Util.getAttribute + * @param {Element} element - the element to set the attribute for + * @param {string} name - the name of the attribute + * @returns {*} the value of the attribute + * + */ + getAttribute = function(element, name) { + return jQuery(element).attr(name); + }; + + /** + * Set attribute in the DOM element. + * + * This method will use jQuery's `attr()` method if it is available, otherwise it will set the attribute directly + * @function Util.setAttribute + * @param {Element} element - the element to set the attribute for + * @param {string} name - the name of the attribute + * @param {*} value - the value to be set + */ + setAttribute = function(element, name, value) { + return jQuery(element).attr(name, value); + }; + + /** + * Remove an attribute in the DOM element. + * + * @function Util.removeAttribute + * @param {Element} element - the element to set the attribute for + * @param {string} name - the name of the attribute + */ + removeAttribute = function(element, name) { + return jQuery(element).removeAttr(name); + }; + + /** + * Set a group of attributes to the element + * @function Util.setAttributes + * @param {Element} element - the element to set the attributes for + * @param {Object} attributes - a hash of attribute names and values + */ + setAttributes = function(element, attributes) { + return jQuery(element).attr(attributes); + }; + + /** + * Checks if element has a css class + * @function Util.hasClass + * @param {Element} element - the element to check + * @param {string} name - the class name + @returns {boolean} true if the element has the class + */ + hasClass = function(element, name) { + return jQuery(element).hasClass(name); + }; + + /** + * Add class to the element + * @function Util.addClass + * @param {Element} element - the element + * @param {string} name - the class name to add + */ + addClass = function(element, name) { + return jQuery(element).addClass(name); + }; + width = function(element) { + return jQuery(element).width(); + }; + + /** + * Returns true if item is empty: + *
    + *
  • item is null or undefined
  • + *
  • item is an array or string of length 0
  • + *
  • item is an object with no keys
  • + *
+ * @function Util.isEmpty + * @param item + * @returns {boolean} true if item is empty + */ + isEmpty = function(item) { + return (item == null) || (jQuery.isArray(item) || Util.isString(item)) && item.length === 0 || (jQuery.isPlainObject(item) && jQuery.isEmptyObject(item)); + }; + + /** + * Returns true if item is a string + * @param item + * @returns {boolean} true if item is a string + */ + isString = function(item) { + return typeof item === 'string' || (item != null ? item.toString() : void 0) === '[object String]'; + }; + + /** + * Recursively assign source properties to destination + * @function Util.merge + * @param {Object} destination - the object to assign to + * @param {...Object} [sources] The source objects. + */ + merge = function() { + var args, i; + args = (function() { + var j, len, results; + results = []; + for (j = 0, len = arguments.length; j < len; j++) { + i = arguments[j]; + results.push(i); + } + return results; + }).apply(this, arguments); + args.unshift(true); + return jQuery.extend.apply(this, args); + }; + + /** + * Creates a new array from the parameter with "falsey" values removed + * @function Util.compact + * @param {Array} array - the array to remove values from + * @return {Array} a new array without falsey values + */ + compact = function(arr) { + var item, j, len, results; + results = []; + for (j = 0, len = arr.length; j < len; j++) { + item = arr[j]; + if (item) { + results.push(item); + } + } + return results; + }; + + /** + * Create a new copy of the given object, including all internal objects. + * @function Util.cloneDeep + * @param {Object} value - the object to clone + * @return {Object} a new deep copy of the object + */ + cloneDeep = function() { + var args; + args = jQuery.makeArray(arguments); + args.unshift({}); + args.unshift(true); + return jQuery.extend.apply(this, args); + }; + + /** + * Check if a given item is included in the given array + * @function Util.contains + * @param {Array} array - the array to search in + * @param {*} item - the item to search for + * @return {boolean} true if the item is included in the array + */ + contains = function(arr, item) { + var i, j, len; + for (j = 0, len = arr.length; j < len; j++) { + i = arr[j]; + if (i === item) { + return true; + } + } + return false; + }; + + /** + * Returns values in the given array that are not included in the other array + * @function Util.difference + * @param {Array} arr - the array to select from + * @param {Array} values - values to filter from arr + * @return {Array} the filtered values + */ + difference = function(arr, values) { + var item, j, len, results; + results = []; + for (j = 0, len = arr.length; j < len; j++) { + item = arr[j]; + if (!contains(values, item)) { + results.push(item); + } + } + return results; + }; + + /** + * Returns a list of all the function names in obj + * @function Util.functions + * @param {Object} object - the object to inspect + * @return {Array} a list of functions of object + */ + functions = function(object) { + var i, results; + results = []; + for (i in object) { + if (jQuery.isFunction(object[i])) { + results.push(i); + } + } + return results; + }; + + /** + * Returns the provided value. This functions is used as a default predicate function. + * @function Util.identity + * @param {*} value + * @return {*} the provided value + */ + identity = function(value) { + return value; + }; + + /** + * @class Util + */ + Util = jQuery.extend(BaseUtil, { + hasClass: hasClass, + addClass: addClass, + getAttribute: getAttribute, + setAttribute: setAttribute, + removeAttribute: removeAttribute, + setAttributes: setAttributes, + getData: getData, + setData: setData, + width: width, + isString: isString, + isArray: jQuery.isArray, + isEmpty: isEmpty, + + /** + * Assign source properties to destination. + * If the property is an object it is assigned as a whole, overriding the destination object. + * @function Util.assign + * @param {Object} destination - the object to assign to + */ + assign: jQuery.extend, + merge: merge, + cloneDeep: cloneDeep, + compact: compact, + contains: contains, + difference: difference, + functions: functions, + identity: identity, + isPlainObject: jQuery.isPlainObject, + + /** + * Remove leading or trailing spaces from text + * @function Util.trim + * @param {string} text + * @return {string} the `text` without leading or trailing spaces + */ + trim: jQuery.trim + }); + + /** + * UTF8 encoder + * + */ + utf8_encode = function(argString) { + var c1, enc, end, n, start, string, stringl, utftext; + if (argString === null || typeof argString === 'undefined') { + return ''; + } + string = argString + ''; + utftext = ''; + start = void 0; + end = void 0; + stringl = 0; + start = end = 0; + stringl = string.length; + n = 0; + while (n < stringl) { + c1 = string.charCodeAt(n); + enc = null; + if (c1 < 128) { + end++; + } else if (c1 > 127 && c1 < 2048) { + enc = String.fromCharCode(c1 >> 6 | 192, c1 & 63 | 128); + } else { + enc = String.fromCharCode(c1 >> 12 | 224, c1 >> 6 & 63 | 128, c1 & 63 | 128); + } + if (enc !== null) { + if (end > start) { + utftext += string.slice(start, end); + } + utftext += enc; + start = end = n + 1; + } + n++; + } + if (end > start) { + utftext += string.slice(start, stringl); + } + return utftext; + }; + + /** + * CRC32 calculator + * Depends on 'utf8_encode' + */ + crc32 = function(str) { + var crc, i, iTop, table, x, y; + str = utf8_encode(str); + table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'; + crc = 0; + x = 0; + y = 0; + crc = crc ^ -1; + i = 0; + iTop = str.length; + while (i < iTop) { + y = (crc ^ str.charCodeAt(i)) & 0xFF; + x = '0x' + table.substr(y * 9, 8); + crc = crc >>> 8 ^ x; + i++; + } + crc = crc ^ -1; + if (crc < 0) { + crc += 4294967296; + } + return crc; + }; + Layer = (function() { + + /** + * Layer + * @constructor Layer + * @param {Object} options - layer parameters + */ + function Layer(options) { + this.options = {}; + if (options != null) { + ["resourceType", "type", "publicId", "format"].forEach((function(_this) { + return function(key) { + var ref; + return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)]; + }; + })(this)); + } + } + + Layer.prototype.resourceType = function(value) { + this.options.resourceType = value; + return this; + }; + + Layer.prototype.type = function(value) { + this.options.type = value; + return this; + }; + + Layer.prototype.publicId = function(value) { + this.options.publicId = value; + return this; + }; + + + /** + * Get the public ID, formatted for layer parameter + * @function Layer#getPublicId + * @return {String} public ID + */ + + Layer.prototype.getPublicId = function() { + var ref; + return (ref = this.options.publicId) != null ? ref.replace(/\//g, ":") : void 0; + }; + + + /** + * Get the public ID, with format if present + * @function Layer#getFullPublicId + * @return {String} public ID + */ + + Layer.prototype.getFullPublicId = function() { + if (this.options.format != null) { + return this.getPublicId() + "." + this.options.format; + } else { + return this.getPublicId(); + } + }; + + Layer.prototype.format = function(value) { + this.options.format = value; + return this; + }; + + + /** + * generate the string representation of the layer + * @function Layer#toString + */ + + Layer.prototype.toString = function() { + var components; + components = []; + if (this.options.publicId == null) { + throw "Must supply publicId"; + } + if (!(this.options.resourceType === "image")) { + components.push(this.options.resourceType); + } + if (!(this.options.type === "upload")) { + components.push(this.options.type); + } + components.push(this.getFullPublicId()); + return Util.compact(components).join(":"); + }; + + return Layer; + + })(); + FetchLayer = (function(superClass) { + extend(FetchLayer, superClass); + + + /** + * @constructor FetchLayer + * @param {Object|string} options - layer parameters or a url + * @param {string} options.url the url of the image to fetch + */ + + function FetchLayer(options) { + FetchLayer.__super__.constructor.call(this, options); + if (Util.isString(options)) { + this.options.url = options; + } else if (options != null ? options.url : void 0) { + this.options.url = options.url; + } + } + + FetchLayer.prototype.url = function(url) { + this.options.url = url; + return this; + }; + + + /** + * generate the string representation of the layer + * @function FetchLayer#toString + * @return {String} + */ + + FetchLayer.prototype.toString = function() { + return "fetch:" + (cloudinary.Util.base64EncodeURL(this.options.url)); + }; + + return FetchLayer; + + })(Layer); + TextLayer = (function(superClass) { + extend(TextLayer, superClass); + + + /** + * @constructor TextLayer + * @param {Object} options - layer parameters + */ + + function TextLayer(options) { + var keys; + TextLayer.__super__.constructor.call(this, options); + keys = ["resourceType", "resourceType", "fontFamily", "fontSize", "fontWeight", "fontStyle", "textDecoration", "textAlign", "stroke", "letterSpacing", "lineSpacing", "text"]; + if (options != null) { + keys.forEach((function(_this) { + return function(key) { + var ref; + return _this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)]; + }; + })(this)); + } + this.options.resourceType = "text"; + } + + TextLayer.prototype.resourceType = function(resourceType) { + throw "Cannot modify resourceType for text layers"; + }; + + TextLayer.prototype.type = function(type) { + throw "Cannot modify type for text layers"; + }; + + TextLayer.prototype.format = function(format) { + throw "Cannot modify format for text layers"; + }; + + TextLayer.prototype.fontFamily = function(fontFamily) { + this.options.fontFamily = fontFamily; + return this; + }; + + TextLayer.prototype.fontSize = function(fontSize) { + this.options.fontSize = fontSize; + return this; + }; + + TextLayer.prototype.fontWeight = function(fontWeight) { + this.options.fontWeight = fontWeight; + return this; + }; + + TextLayer.prototype.fontStyle = function(fontStyle) { + this.options.fontStyle = fontStyle; + return this; + }; + + TextLayer.prototype.textDecoration = function(textDecoration) { + this.options.textDecoration = textDecoration; + return this; + }; + + TextLayer.prototype.textAlign = function(textAlign) { + this.options.textAlign = textAlign; + return this; + }; + + TextLayer.prototype.stroke = function(stroke) { + this.options.stroke = stroke; + return this; + }; + + TextLayer.prototype.letterSpacing = function(letterSpacing) { + this.options.letterSpacing = letterSpacing; + return this; + }; + + TextLayer.prototype.lineSpacing = function(lineSpacing) { + this.options.lineSpacing = lineSpacing; + return this; + }; + + TextLayer.prototype.text = function(text) { + this.options.text = text; + return this; + }; + + + /** + * generate the string representation of the layer + * @function TextLayer#toString + * @return {String} + */ + + TextLayer.prototype.toString = function() { + var components, hasPublicId, hasStyle, publicId, re, res, start, style, text, textSource; + style = this.textStyleIdentifier(); + if (this.options.publicId != null) { + publicId = this.getFullPublicId(); + } + if (this.options.text != null) { + hasPublicId = !Util.isEmpty(publicId); + hasStyle = !Util.isEmpty(style); + if (hasPublicId && hasStyle || !hasPublicId && !hasStyle) { + throw "Must supply either style parameters or a public_id when providing text parameter in a text overlay/underlay, but not both!"; + } + re = /\$\([a-zA-Z]\w*\)/g; + start = 0; + textSource = Util.smartEscape(this.options.text, /[,\/]/g); + text = ""; + while (res = re.exec(textSource)) { + text += Util.smartEscape(textSource.slice(start, res.index)); + text += res[0]; + start = res.index + res[0].length; + } + text += Util.smartEscape(textSource.slice(start)); + } + components = [this.options.resourceType, style, publicId, text]; + return Util.compact(components).join(":"); + }; + + TextLayer.prototype.textStyleIdentifier = function() { + var components; + components = []; + if (this.options.fontWeight !== "normal") { + components.push(this.options.fontWeight); + } + if (this.options.fontStyle !== "normal") { + components.push(this.options.fontStyle); + } + if (this.options.textDecoration !== "none") { + components.push(this.options.textDecoration); + } + components.push(this.options.textAlign); + if (this.options.stroke !== "none") { + components.push(this.options.stroke); + } + if (!(Util.isEmpty(this.options.letterSpacing) && !Util.isNumberLike(this.options.letterSpacing))) { + components.push("letter_spacing_" + this.options.letterSpacing); + } + if (!(Util.isEmpty(this.options.lineSpacing) && !Util.isNumberLike(this.options.lineSpacing))) { + components.push("line_spacing_" + this.options.lineSpacing); + } + if (!Util.isEmpty(Util.compact(components))) { + if (Util.isEmpty(this.options.fontFamily)) { + throw "Must supply fontFamily. " + components; + } + if (Util.isEmpty(this.options.fontSize) && !Util.isNumberLike(this.options.fontSize)) { + throw "Must supply fontSize."; + } + } + components.unshift(this.options.fontFamily, this.options.fontSize); + components = Util.compact(components).join("_"); + return components; + }; + + return TextLayer; + + })(Layer); + SubtitlesLayer = (function(superClass) { + extend(SubtitlesLayer, superClass); + + + /** + * Represent a subtitles layer + * @constructor SubtitlesLayer + * @param {Object} options - layer parameters + */ + + function SubtitlesLayer(options) { + SubtitlesLayer.__super__.constructor.call(this, options); + this.options.resourceType = "subtitles"; + } + + return SubtitlesLayer; + + })(TextLayer); + + /** + * Transformation parameters + * Depends on 'util', 'transformation' + */ + Param = (function() { + + /** + * Represents a single parameter + * @class Param + * @param {string} name - The name of the parameter in snake_case + * @param {string} shortName - The name of the serialized form of the parameter. + * If a value is not provided, the parameter will not be serialized. + * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called + * @ignore + */ + function Param(name, shortName, process) { + if (process == null) { + process = cloudinary.Util.identity; + } + + /** + * The name of the parameter in snake_case + * @member {string} Param#name + */ + this.name = name; + + /** + * The name of the serialized form of the parameter + * @member {string} Param#shortName + */ + this.shortName = shortName; + + /** + * Manipulate origValue when value is called + * @member {function} Param#process + */ + this.process = process; + } + + + /** + * Set a (unprocessed) value for this parameter + * @function Param#set + * @param {*} origValue - the value of the parameter + * @return {Param} self for chaining + */ + + Param.prototype.set = function(origValue) { + this.origValue = origValue; + return this; + }; + + + /** + * Generate the serialized form of the parameter + * @function Param#serialize + * @return {string} the serialized form of the parameter + */ + + Param.prototype.serialize = function() { + var val, valid; + val = this.value(); + valid = cloudinary.Util.isArray(val) || cloudinary.Util.isPlainObject(val) || cloudinary.Util.isString(val) ? !cloudinary.Util.isEmpty(val) : val != null; + if ((this.shortName != null) && valid) { + return this.shortName + "_" + val; + } else { + return ''; + } + }; + + + /** + * Return the processed value of the parameter + * @function Param#value + */ + + Param.prototype.value = function() { + return this.process(this.origValue); + }; + + Param.norm_color = function(value) { + return value != null ? value.replace(/^#/, 'rgb:') : void 0; + }; + + Param.prototype.build_array = function(arg) { + if (arg == null) { + arg = []; + } + if (cloudinary.Util.isArray(arg)) { + return arg; + } else { + return [arg]; + } + }; + + + /** + * Covert value to video codec string. + * + * If the parameter is an object, + * @param {(string|Object)} param - the video codec as either a String or a Hash + * @return {string} the video codec string in the format codec:profile:level + * @example + * vc_[ :profile : [level]] + * or + { codec: 'h264', profile: 'basic', level: '3.1' } + * @ignore + */ + + Param.process_video_params = function(param) { + var video; + switch (param.constructor) { + case Object: + video = ""; + if ('codec' in param) { + video = param['codec']; + if ('profile' in param) { + video += ":" + param['profile']; + if ('level' in param) { + video += ":" + param['level']; + } + } + } + return video; + case String: + return param; + default: + return null; + } + }; + + return Param; + + })(); + ArrayParam = (function(superClass) { + extend(ArrayParam, superClass); + + + /** + * A parameter that represents an array + * @param {string} name - The name of the parameter in snake_case + * @param {string} shortName - The name of the serialized form of the parameter + * If a value is not provided, the parameter will not be serialized. + * @param {string} [sep='.'] - The separator to use when joining the array elements together + * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called + * @class ArrayParam + * @extends Param + * @ignore + */ + + function ArrayParam(name, shortName, sep, process) { + if (sep == null) { + sep = '.'; + } + this.sep = sep; + ArrayParam.__super__.constructor.call(this, name, shortName, process); + } + + ArrayParam.prototype.serialize = function() { + var arrayValue, flat, t; + if (this.shortName != null) { + arrayValue = this.value(); + if (cloudinary.Util.isEmpty(arrayValue)) { + return ''; + } else if (cloudinary.Util.isString(arrayValue)) { + return this.shortName + "_" + arrayValue; + } else { + flat = (function() { + var j, len, results; + results = []; + for (j = 0, len = arrayValue.length; j < len; j++) { + t = arrayValue[j]; + if (cloudinary.Util.isFunction(t.serialize)) { + results.push(t.serialize()); + } else { + results.push(t); + } + } + return results; + })(); + return this.shortName + "_" + (flat.join(this.sep)); + } + } else { + return ''; + } + }; + + ArrayParam.prototype.value = function() { + var j, len, ref, results, v; + if (cloudinary.Util.isArray(this.origValue)) { + ref = this.origValue; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + v = ref[j]; + results.push(this.process(v)); + } + return results; + } else { + return this.process(this.origValue); + } + }; + + ArrayParam.prototype.set = function(origValue) { + if ((origValue == null) || cloudinary.Util.isArray(origValue)) { + return ArrayParam.__super__.set.call(this, origValue); + } else { + return ArrayParam.__super__.set.call(this, [origValue]); + } + }; + + return ArrayParam; + + })(Param); + TransformationParam = (function(superClass) { + extend(TransformationParam, superClass); + + + /** + * A parameter that represents a transformation + * @param {string} name - The name of the parameter in snake_case + * @param {string} [shortName='t'] - The name of the serialized form of the parameter + * @param {string} [sep='.'] - The separator to use when joining the array elements together + * @param {function} [process=cloudinary.Util.identity ] - Manipulate origValue when value is called + * @class TransformationParam + * @extends Param + * @ignore + */ + + function TransformationParam(name, shortName, sep, process) { + if (shortName == null) { + shortName = "t"; + } + if (sep == null) { + sep = '.'; + } + this.sep = sep; + TransformationParam.__super__.constructor.call(this, name, shortName, process); + } + + TransformationParam.prototype.serialize = function() { + var joined, result, t; + if (cloudinary.Util.isEmpty(this.value())) { + return ''; + } else if (cloudinary.Util.allStrings(this.value())) { + joined = this.value().join(this.sep); + if (!cloudinary.Util.isEmpty(joined)) { + return this.shortName + "_" + joined; + } else { + return ''; + } + } else { + result = (function() { + var j, len, ref, results; + ref = this.value(); + results = []; + for (j = 0, len = ref.length; j < len; j++) { + t = ref[j]; + if (t != null) { + if (cloudinary.Util.isString(t) && !cloudinary.Util.isEmpty(t)) { + results.push(this.shortName + "_" + t); + } else if (cloudinary.Util.isFunction(t.serialize)) { + results.push(t.serialize()); + } else if (cloudinary.Util.isPlainObject(t) && !cloudinary.Util.isEmpty(t)) { + results.push(new Transformation(t).serialize()); + } else { + results.push(void 0); + } + } + } + return results; + }).call(this); + return cloudinary.Util.compact(result); + } + }; + + TransformationParam.prototype.set = function(origValue1) { + this.origValue = origValue1; + if (cloudinary.Util.isArray(this.origValue)) { + return TransformationParam.__super__.set.call(this, this.origValue); + } else { + return TransformationParam.__super__.set.call(this, [this.origValue]); + } + }; + + return TransformationParam; + + })(Param); + RangeParam = (function(superClass) { + extend(RangeParam, superClass); + + + /** + * A parameter that represents a range + * @param {string} name - The name of the parameter in snake_case + * @param {string} shortName - The name of the serialized form of the parameter + * If a value is not provided, the parameter will not be serialized. + * @param {function} [process=norm_range_value ] - Manipulate origValue when value is called + * @class RangeParam + * @extends Param + * @ignore + */ + + function RangeParam(name, shortName, process) { + if (process == null) { + process = this.norm_range_value; + } + RangeParam.__super__.constructor.call(this, name, shortName, process); + } + + RangeParam.norm_range_value = function(value) { + var modifier, offset; + offset = String(value).match(new RegExp('^' + offset_any_pattern + '$')); + if (offset) { + modifier = offset[5] != null ? 'p' : ''; + value = (offset[1] || offset[4]) + modifier; + } + return value; + }; + + return RangeParam; + + })(Param); + RawParam = (function(superClass) { + extend(RawParam, superClass); + + function RawParam(name, shortName, process) { + if (process == null) { + process = cloudinary.Util.identity; + } + RawParam.__super__.constructor.call(this, name, shortName, process); + } + + RawParam.prototype.serialize = function() { + return this.value(); + }; + + return RawParam; + + })(Param); + LayerParam = (function(superClass) { + var LAYER_KEYWORD_PARAMS; + + extend(LayerParam, superClass); + + function LayerParam() { + return LayerParam.__super__.constructor.apply(this, arguments); + } + + LayerParam.prototype.value = function() { + var layerOptions, result; + layerOptions = this.origValue; + if (cloudinary.Util.isPlainObject(layerOptions)) { + layerOptions = Util.withCamelCaseKeys(layerOptions); + if (layerOptions.resourceType === "text" || (layerOptions.text != null)) { + result = new cloudinary.TextLayer(layerOptions).toString(); + } else if (layerOptions.resourceType === "subtitles") { + result = new cloudinary.SubtitlesLayer(layerOptions).toString(); + } else if (layerOptions.resourceType === "fetch" || (layerOptions.url != null)) { + result = new cloudinary.FetchLayer(layerOptions).toString(); + } else { + result = new cloudinary.Layer(layerOptions).toString(); + } + } else if (/^fetch:.+/.test(layerOptions)) { + result = new FetchLayer(layerOptions.substr(6)).toString(); + } else { + result = layerOptions; + } + return result; + }; + + LAYER_KEYWORD_PARAMS = [["font_weight", "normal"], ["font_style", "normal"], ["text_decoration", "none"], ["text_align", null], ["stroke", "none"], ["letter_spacing", null], ["line_spacing", null]]; + + LayerParam.prototype.textStyle = function(layer) { + return (new cloudinary.TextLayer(layer)).textStyleIdentifier(); + }; + + return LayerParam; + + })(Param); + ExpressionParam = (function(superClass) { + extend(ExpressionParam, superClass); + + function ExpressionParam() { + return ExpressionParam.__super__.constructor.apply(this, arguments); + } + + ExpressionParam.prototype.serialize = function() { + return Expression.normalize(ExpressionParam.__super__.serialize.call(this)); + }; + + return ExpressionParam; + + })(Param); + parameters = {}; + parameters.Param = Param; + parameters.ArrayParam = ArrayParam; + parameters.RangeParam = RangeParam; + parameters.RawParam = RawParam; + parameters.TransformationParam = TransformationParam; + parameters.LayerParam = LayerParam; + parameters.ExpressionParam = ExpressionParam; + Expression = (function() { + + /** + * @internal + */ + var faceCount; + + Expression.OPERATORS = { + "=": 'eq', + "!=": 'ne', + "<": 'lt', + ">": 'gt', + "<=": 'lte', + ">=": 'gte', + "&&": 'and', + "||": 'or', + "*": "mul", + "/": "div", + "+": "add", + "-": "sub" + }; + + + /** + * @internal + */ + + Expression.PREDEFINED_VARS = { + "aspect_ratio": "ar", + "aspectRatio": "ar", + "current_page": "cp", + "currentPage": "cp", + "face_count": "fc", + "faceCount": "fc", + "height": "h", + "initial_aspect_ratio": "iar", + "initial_height": "ih", + "initial_width": "iw", + "initialAspectRatio": "iar", + "initialHeight": "ih", + "initialWidth": "iw", + "page_count": "pc", + "page_x": "px", + "page_y": "py", + "pageCount": "pc", + "pageX": "px", + "pageY": "py", + "tags": "tags", + "width": "w" + }; + + + /** + * @internal + */ + + Expression.BOUNDRY = "[ _]+"; + + + /** + * Represents a transformation expression + * @param {string} expressionStr - a expression in string format + * @class Expression + * + */ + + function Expression(expressionStr) { + + /** + * @protected + * @inner Expression-expressions + */ + this.expressions = []; + if (expressionStr != null) { + this.expressions.push(Expression.normalize(expressionStr)); + } + } + + + /** + * Convenience constructor method + * @function Expression.new + */ + + Expression["new"] = function(expressionStr) { + return new this(expressionStr); + }; + + + /** + * Normalize a string expression + * @function Cloudinary#normalize + * @param {string} expression a expression, e.g. "w gt 100", "width_gt_100", "width > 100" + * @return {string} the normalized form of the value expression, e.g. "w_gt_100" + */ + + Expression.normalize = function(expression) { + var operators, pattern, replaceRE; + if (expression == null) { + return expression; + } + expression = String(expression); + operators = "\\|\\||>=|<=|&&|!=|>|=|<|/|-|\\+|\\*"; + pattern = "((" + operators + ")(?=[ _])|" + Object.keys(Expression.PREDEFINED_VARS).join("|") + ")"; + replaceRE = new RegExp(pattern, "g"); + expression = expression.replace(replaceRE, function(match) { + return Expression.OPERATORS[match] || Expression.PREDEFINED_VARS[match]; + }); + return expression.replace(/[ _]+/g, '_'); + }; + + + /** + * Serialize the expression + * @return {string} the expression as a string + */ + + Expression.prototype.serialize = function() { + return Expression.normalize(this.expressions.join("_")); + }; + + Expression.prototype.toString = function() { + return this.serialize(); + }; + + + /** + * Get the parent transformation of this expression + * @return Transformation + */ + + Expression.prototype.getParent = function() { + return this.parent; + }; + + + /** + * Set the parent transformation of this expression + * @param {Transformation} the parent transformation + * @return {Expression} this expression + */ + + Expression.prototype.setParent = function(parent) { + this.parent = parent; + return this; + }; + + + /** + * Add a expression + * @function Expression#predicate + * @internal + */ + + Expression.prototype.predicate = function(name, operator, value) { + if (Expression.OPERATORS[operator] != null) { + operator = Expression.OPERATORS[operator]; + } + this.expressions.push(name + "_" + operator + "_" + value); + return this; + }; + + + /** + * @function Expression#and + */ + + Expression.prototype.and = function() { + this.expressions.push("and"); + return this; + }; + + + /** + * @function Expression#or + */ + + Expression.prototype.or = function() { + this.expressions.push("or"); + return this; + }; + + + /** + * Conclude expression + * @function Expression#then + * @return {Transformation} the transformation this expression is defined for + */ + + Expression.prototype.then = function() { + return this.getParent()["if"](this.toString()); + }; + + + /** + * @function Expression#height + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Expression} this expression + */ + + Expression.prototype.height = function(operator, value) { + return this.predicate("h", operator, value); + }; + + + /** + * @function Expression#width + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Expression} this expression + */ + + Expression.prototype.width = function(operator, value) { + return this.predicate("w", operator, value); + }; + + + /** + * @function Expression#aspectRatio + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Expression} this expression + */ + + Expression.prototype.aspectRatio = function(operator, value) { + return this.predicate("ar", operator, value); + }; + + + /** + * @function Expression#pages + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Expression} this expression + */ + + Expression.prototype.pageCount = function(operator, value) { + return this.predicate("pc", operator, value); + }; + + + /** + * @function Expression#faces + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Expression} this expression + */ + + Expression.prototype.faceCount = function(operator, value) { + return this.predicate("fc", operator, value); + }; + + Expression.prototype.value = function(value) { + this.expressions.push(value); + return this; + }; + + + /** + */ + + Expression.variable = function(name, value) { + return new this(name).value(value); + }; + + + /** + * @returns a new expression with the predefined variable "width" + * @function Expression.width + */ + + Expression.width = function() { + return new this("width"); + }; + + + /** + * @returns a new expression with the predefined variable "height" + * @function Expression.height + */ + + Expression.height = function() { + return new this("height"); + }; + + + /** + * @returns a new expression with the predefined variable "initialWidth" + * @function Expression.initialWidth + */ + + Expression.initialWidth = function() { + return new this("initialWidth"); + }; + + + /** + * @returns a new expression with the predefined variable "initialHeight" + * @function Expression.initialHeight + */ + + Expression.initialHeight = function() { + return new this("initialHeight"); + }; + + + /** + * @returns a new expression with the predefined variable "aspectRatio" + * @function Expression.aspectRatio + */ + + Expression.aspectRatio = function() { + return new this("aspectRatio"); + }; + + + /** + * @returns a new expression with the predefined variable "initialAspectRatio" + * @function Expression.initialAspectRatio + */ + + Expression.initialAspectRatio = function() { + return new this("initialAspectRatio"); + }; + + + /** + * @returns a new expression with the predefined variable "pageCount" + * @function Expression.pageCount + */ + + Expression.pageCount = function() { + return new this("pageCount"); + }; + + + /** + * @returns a new expression with the predefined variable "faceCount" + * @function Expression.faceCount + */ + + faceCount = function() { + return new this("faceCount"); + }; + + + /** + * @returns a new expression with the predefined variable "currentPage" + * @function Expression.currentPage + */ + + Expression.currentPage = function() { + return new this("currentPage"); + }; + + + /** + * @returns a new expression with the predefined variable "tags" + * @function Expression.tags + */ + + Expression.tags = function() { + return new this("tags"); + }; + + + /** + * @returns a new expression with the predefined variable "pageX" + * @function Expression.pageX + */ + + Expression.pageX = function() { + return new this("pageX"); + }; + + + /** + * @returns a new expression with the predefined variable "pageY" + * @function Expression.pageY + */ + + Expression.pageY = function() { + return new this("pageY"); + }; + + return Expression; + + })(); + Condition = (function(superClass) { + extend(Condition, superClass); + + + /** + * Represents a transformation condition + * @param {string} conditionStr - a condition in string format + * @class Condition + * @example + * // normally this class is not instantiated directly + * var tr = cloudinary.Transformation.new() + * .if().width( ">", 1000).and().aspectRatio("<", "3:4").then() + * .width(1000) + * .crop("scale") + * .else() + * .width(500) + * .crop("scale") + * + * var tr = cloudinary.Transformation.new() + * .if("w > 1000 and aspectRatio < 3:4") + * .width(1000) + * .crop("scale") + * .else() + * .width(500) + * .crop("scale") + * + */ + + function Condition(conditionStr) { + Condition.__super__.constructor.call(this, conditionStr); + } + + + /** + * @function Condition#height + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Condition} this condition + */ + + Condition.prototype.height = function(operator, value) { + return this.predicate("h", operator, value); + }; + + + /** + * @function Condition#width + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Condition} this condition + */ + + Condition.prototype.width = function(operator, value) { + return this.predicate("w", operator, value); + }; + + + /** + * @function Condition#aspectRatio + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Condition} this condition + */ + + Condition.prototype.aspectRatio = function(operator, value) { + return this.predicate("ar", operator, value); + }; + + + /** + * @function Condition#pages + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Condition} this condition + */ + + Condition.prototype.pageCount = function(operator, value) { + return this.predicate("pc", operator, value); + }; + + + /** + * @function Condition#faces + * @param {string} operator the comparison operator (e.g. "<", "lt") + * @param {string|number} value the right hand side value + * @return {Condition} this condition + */ + + Condition.prototype.faceCount = function(operator, value) { + return this.predicate("fc", operator, value); + }; + + return Condition; + + })(Expression); + + /** + * Cloudinary configuration class + * Depends on 'utils' + */ + Configuration = (function() { + + /** + * Defaults configuration. + */ + var DEFAULT_CONFIGURATION_PARAMS, ref; + + DEFAULT_CONFIGURATION_PARAMS = { + responsive_class: 'cld-responsive', + responsive_use_breakpoints: true, + round_dpr: true, + secure: (typeof window !== "undefined" && window !== null ? (ref = window.location) != null ? ref.protocol : void 0 : void 0) === 'https:' + }; + + Configuration.CONFIG_PARAMS = ["api_key", "api_secret", "callback", "cdn_subdomain", "cloud_name", "cname", "private_cdn", "protocol", "resource_type", "responsive", "responsive_class", "responsive_use_breakpoints", "responsive_width", "round_dpr", "secure", "secure_cdn_subdomain", "secure_distribution", "shorten", "type", "upload_preset", "url_suffix", "use_root_path", "version"]; + + + /** + * Cloudinary configuration class + * @constructor Configuration + * @param {Object} options - configuration parameters + */ + + function Configuration(options) { + if (options == null) { + options = {}; + } + this.configuration = Util.cloneDeep(options); + Util.defaults(this.configuration, DEFAULT_CONFIGURATION_PARAMS); + } + + + /** + * Initialize the configuration. + * The function first tries to retrieve the configuration form the environment and then from the document. + * @function Configuration#init + * @return {Configuration} returns this for chaining + * @see fromDocument + * @see fromEnvironment + */ + + Configuration.prototype.init = function() { + this.fromEnvironment(); + this.fromDocument(); + return this; + }; + + + /** + * Set a new configuration item + * @function Configuration#set + * @param {string} name - the name of the item to set + * @param {*} value - the value to be set + * @return {Configuration} + * + */ + + Configuration.prototype.set = function(name, value) { + this.configuration[name] = value; + return this; + }; + + + /** + * Get the value of a configuration item + * @function Configuration#get + * @param {string} name - the name of the item to set + * @return {*} the configuration item + */ + + Configuration.prototype.get = function(name) { + return this.configuration[name]; + }; + + Configuration.prototype.merge = function(config) { + if (config == null) { + config = {}; + } + Util.assign(this.configuration, Util.cloneDeep(config)); + return this; + }; + + + /** + * Initialize Cloudinary from HTML meta tags. + * @function Configuration#fromDocument + * @return {Configuration} + * @example + * + */ + + Configuration.prototype.fromDocument = function() { + var el, j, len, meta_elements; + meta_elements = typeof document !== "undefined" && document !== null ? document.querySelectorAll('meta[name^="cloudinary_"]') : void 0; + if (meta_elements) { + for (j = 0, len = meta_elements.length; j < len; j++) { + el = meta_elements[j]; + this.configuration[el.getAttribute('name').replace('cloudinary_', '')] = el.getAttribute('content'); + } + } + return this; + }; + + + /** + * Initialize Cloudinary from the `CLOUDINARY_URL` environment variable. + * + * This function will only run under Node.js environment. + * @function Configuration#fromEnvironment + * @requires Node.js + */ + + Configuration.prototype.fromEnvironment = function() { + var cloudinary_url, j, k, len, query, ref1, ref2, ref3, uri, uriRegex, v, value; + cloudinary_url = typeof process !== "undefined" && process !== null ? (ref1 = process.env) != null ? ref1.CLOUDINARY_URL : void 0 : void 0; + if (cloudinary_url != null) { + uriRegex = /cloudinary:\/\/(?:(\w+)(?:\:([\w-]+))?@)?([\w\.-]+)(?:\/([^?]*))?(?:\?(.+))?/; + uri = uriRegex.exec(cloudinary_url); + if (uri) { + if (uri[3] != null) { + this.configuration['cloud_name'] = uri[3]; + } + if (uri[1] != null) { + this.configuration['api_key'] = uri[1]; + } + if (uri[2] != null) { + this.configuration['api_secret'] = uri[2]; + } + if (uri[4] != null) { + this.configuration['private_cdn'] = uri[4] != null; + } + if (uri[4] != null) { + this.configuration['secure_distribution'] = uri[4]; + } + query = uri[5]; + if (query != null) { + ref2 = query.split('&'); + for (j = 0, len = ref2.length; j < len; j++) { + value = ref2[j]; + ref3 = value.split('='), k = ref3[0], v = ref3[1]; + if (v == null) { + v = true; + } + this.configuration[k] = v; + } + } + } + } + return this; + }; + + + /** + * Create or modify the Cloudinary client configuration + * + * Warning: `config()` returns the actual internal configuration object. modifying it will change the configuration. + * + * This is a backward compatibility method. For new code, use get(), merge() etc. + * @function Configuration#config + * @param {hash|string|boolean} new_config + * @param {string} new_value + * @returns {*} configuration, or value + * + * @see {@link fromEnvironment} for initialization using environment variables + * @see {@link fromDocument} for initialization using HTML meta tags + */ + + Configuration.prototype.config = function(new_config, new_value) { + switch (false) { + case new_value === void 0: + this.set(new_config, new_value); + return this.configuration; + case !Util.isString(new_config): + return this.get(new_config); + case !Util.isPlainObject(new_config): + this.merge(new_config); + return this.configuration; + default: + return this.configuration; + } + }; + + + /** + * Returns a copy of the configuration parameters + * @function Configuration#toOptions + * @returns {Object} a key:value collection of the configuration parameters + */ + + Configuration.prototype.toOptions = function() { + return Util.cloneDeep(this.configuration); + }; + + return Configuration; + + })(); + + /** + * TransformationBase + * Depends on 'configuration', 'parameters','util' + * @internal + */ + TransformationBase = (function() { + var VAR_NAME_RE, lastArgCallback, processVar; + + VAR_NAME_RE = /^\$[a-zA-Z0-9]+$/; + + TransformationBase.prototype.trans_separator = '/'; + + TransformationBase.prototype.param_separator = ','; + + lastArgCallback = function(args) { + var callback; + callback = args != null ? args[args.length - 1] : void 0; + if (Util.isFunction(callback)) { + return callback; + } else { + return void 0; + } + }; + + + /** + * The base class for transformations. + * Members of this class are documented as belonging to the {@link Transformation} class for convenience. + * @class TransformationBase + */ + + function TransformationBase(options) { + var parent, trans; + if (options == null) { + options = {}; + } + + /** @private */ + parent = void 0; + + /** @private */ + trans = {}; + + /** + * Return an options object that can be used to create an identical Transformation + * @function Transformation#toOptions + * @return {Object} Returns a plain object representing this transformation + */ + this.toOptions || (this.toOptions = function(withChain) { + var key, list, opt, ref, ref1, tr, value; + if (withChain == null) { + withChain = true; + } + opt = {}; + for (key in trans) { + value = trans[key]; + opt[key] = value.origValue; + } + ref = this.otherOptions; + for (key in ref) { + value = ref[key]; + if (value !== void 0) { + opt[key] = value; + } + } + if (withChain && !Util.isEmpty(this.chained)) { + list = (function() { + var j, len, ref1, results; + ref1 = this.chained; + results = []; + for (j = 0, len = ref1.length; j < len; j++) { + tr = ref1[j]; + results.push(tr.toOptions()); + } + return results; + }).call(this); + list.push(opt); + opt = {}; + ref1 = this.otherOptions; + for (key in ref1) { + value = ref1[key]; + if (value !== void 0) { + opt[key] = value; + } + } + opt.transformation = list; + } + return opt; + }); + + /** + * Set a parent for this object for chaining purposes. + * + * @function Transformation#setParent + * @param {Object} object - the parent to be assigned to + * @returns {Transformation} Returns this instance for chaining purposes. + */ + this.setParent || (this.setParent = function(object) { + parent = object; + if (object != null) { + this.fromOptions(typeof object.toOptions === "function" ? object.toOptions() : void 0); + } + return this; + }); + + /** + * Returns the parent of this object in the chain + * @function Transformation#getParent + * @protected + * @return {Object} Returns the parent of this object if there is any + */ + this.getParent || (this.getParent = function() { + return parent; + }); + + /** @protected */ + this.param || (this.param = function(value, name, abbr, defaultValue, process) { + if (process == null) { + if (Util.isFunction(defaultValue)) { + process = defaultValue; + } else { + process = Util.identity; + } + } + trans[name] = new Param(name, abbr, process).set(value); + return this; + }); + + /** @protected */ + this.rawParam || (this.rawParam = function(value, name, abbr, defaultValue, process) { + if (process == null) { + process = Util.identity; + } + process = lastArgCallback(arguments); + trans[name] = new RawParam(name, abbr, process).set(value); + return this; + }); + + /** @protected */ + this.rangeParam || (this.rangeParam = function(value, name, abbr, defaultValue, process) { + if (process == null) { + process = Util.identity; + } + process = lastArgCallback(arguments); + trans[name] = new RangeParam(name, abbr, process).set(value); + return this; + }); + + /** @protected */ + this.arrayParam || (this.arrayParam = function(value, name, abbr, sep, defaultValue, process) { + if (sep == null) { + sep = ":"; + } + if (defaultValue == null) { + defaultValue = []; + } + if (process == null) { + process = Util.identity; + } + process = lastArgCallback(arguments); + trans[name] = new ArrayParam(name, abbr, sep, process).set(value); + return this; + }); + + /** @protected */ + this.transformationParam || (this.transformationParam = function(value, name, abbr, sep, defaultValue, process) { + if (sep == null) { + sep = "."; + } + if (process == null) { + process = Util.identity; + } + process = lastArgCallback(arguments); + trans[name] = new TransformationParam(name, abbr, sep, process).set(value); + return this; + }); + this.layerParam || (this.layerParam = function(value, name, abbr) { + trans[name] = new LayerParam(name, abbr).set(value); + return this; + }); + + /** + * Get the value associated with the given name. + * @function Transformation#getValue + * @param {string} name - the name of the parameter + * @return {*} the processed value associated with the given name + * @description Use {@link get}.origValue for the value originally provided for the parameter + */ + this.getValue || (this.getValue = function(name) { + var ref, ref1; + return (ref = (ref1 = trans[name]) != null ? ref1.value() : void 0) != null ? ref : this.otherOptions[name]; + }); + + /** + * Get the parameter object for the given parameter name + * @function Transformation#get + * @param {string} name the name of the transformation parameter + * @returns {Param} the param object for the given name, or undefined + */ + this.get || (this.get = function(name) { + return trans[name]; + }); + + /** + * Remove a transformation option from the transformation. + * @function Transformation#remove + * @param {string} name - the name of the option to remove + * @return {*} Returns the option that was removed or null if no option by that name was found. The type of the + * returned value depends on the value. + */ + this.remove || (this.remove = function(name) { + var temp; + switch (false) { + case trans[name] == null: + temp = trans[name]; + delete trans[name]; + return temp.origValue; + case this.otherOptions[name] == null: + temp = this.otherOptions[name]; + delete this.otherOptions[name]; + return temp; + default: + return null; + } + }); + + /** + * Return an array of all the keys (option names) in the transformation. + * @return {Array} the keys in snakeCase format + */ + this.keys || (this.keys = function() { + var key; + return ((function() { + var results; + results = []; + for (key in trans) { + if (key != null) { + results.push(key.match(VAR_NAME_RE) ? key : Util.snakeCase(key)); + } + } + return results; + })()).sort(); + }); + + /** + * Returns a plain object representation of the transformation. Values are processed. + * @function Transformation#toPlainObject + * @return {Object} the transformation options as plain object + */ + this.toPlainObject || (this.toPlainObject = function() { + var hash, key, list, tr; + hash = {}; + for (key in trans) { + hash[key] = trans[key].value(); + if (Util.isPlainObject(hash[key])) { + hash[key] = Util.cloneDeep(hash[key]); + } + } + if (!Util.isEmpty(this.chained)) { + list = (function() { + var j, len, ref, results; + ref = this.chained; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + tr = ref[j]; + results.push(tr.toPlainObject()); + } + return results; + }).call(this); + list.push(hash); + hash = { + transformation: list + }; + } + return hash; + }); + + /** + * Complete the current transformation and chain to a new one. + * In the URL, transformations are chained together by slashes. + * @function Transformation#chain + * @return {Transformation} Returns this transformation for chaining + * @example + * var tr = cloudinary.Transformation.new(); + * tr.width(10).crop('fit').chain().angle(15).serialize() + * // produces "c_fit,w_10/a_15" + */ + this.chain || (this.chain = function() { + var names, tr; + names = Object.getOwnPropertyNames(trans); + if (names.length !== 0) { + tr = new this.constructor(this.toOptions(false)); + this.resetTransformations(); + this.chained.push(tr); + } + return this; + }); + this.resetTransformations || (this.resetTransformations = function() { + trans = {}; + return this; + }); + this.otherOptions || (this.otherOptions = {}); + this.chained = []; + if (!Util.isEmpty(options)) { + this.fromOptions(options); + } + } + + + /** + * Merge the provided options with own's options + * @param {Object} [options={}] key-value list of options + * @returns {Transformation} Returns this instance for chaining + */ + + TransformationBase.prototype.fromOptions = function(options) { + var key, opt; + if (options instanceof TransformationBase) { + this.fromTransformation(options); + } else { + options || (options = {}); + if (Util.isString(options) || Util.isArray(options)) { + options = { + transformation: options + }; + } + options = Util.cloneDeep(options, function(value) { + if (value instanceof TransformationBase) { + return new value.constructor(value.toOptions()); + } + }); + if (options["if"]) { + this.set("if", options["if"]); + delete options["if"]; + } + for (key in options) { + opt = options[key]; + if (key.match(VAR_NAME_RE)) { + if (key !== '$attr') { + this.set('variable', key, opt); + } + } else { + this.set(key, opt); + } + } + } + return this; + }; + + TransformationBase.prototype.fromTransformation = function(other) { + var j, key, len, ref; + if (other instanceof TransformationBase) { + ref = other.keys(); + for (j = 0, len = ref.length; j < len; j++) { + key = ref[j]; + this.set(key, other.get(key).origValue); + } + } + return this; + }; + + + /** + * Set a parameter. + * The parameter name `key` is converted to + * @param {string} key - the name of the parameter + * @param {*} value - the value of the parameter + * @returns {Transformation} Returns this instance for chaining + */ + + TransformationBase.prototype.set = function() { + var camelKey, key, values; + key = arguments[0], values = 2 <= arguments.length ? slice.call(arguments, 1) : []; + camelKey = Util.camelCase(key); + if (Util.contains(Transformation.methods, camelKey)) { + this[camelKey].apply(this, values); + } else { + this.otherOptions[key] = values[0]; + } + return this; + }; + + TransformationBase.prototype.hasLayer = function() { + return this.getValue("overlay") || this.getValue("underlay"); + }; + + + /** + * Generate a string representation of the transformation. + * @function Transformation#serialize + * @return {string} Returns the transformation as a string + */ + + TransformationBase.prototype.serialize = function() { + var ifParam, j, len, paramList, ref, ref1, ref2, ref3, ref4, resultArray, t, tr, transformationList, transformationString, transformations, value, variables, vars; + resultArray = (function() { + var j, len, ref, results; + ref = this.chained; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + tr = ref[j]; + results.push(tr.serialize()); + } + return results; + }).call(this); + paramList = this.keys(); + transformations = (ref = this.get("transformation")) != null ? ref.serialize() : void 0; + ifParam = (ref1 = this.get("if")) != null ? ref1.serialize() : void 0; + variables = processVar((ref2 = this.get("variables")) != null ? ref2.value() : void 0); + paramList = Util.difference(paramList, ["transformation", "if", "variables"]); + vars = []; + transformationList = []; + for (j = 0, len = paramList.length; j < len; j++) { + t = paramList[j]; + if (t.match(VAR_NAME_RE)) { + vars.push(t + "_" + Expression.normalize((ref3 = this.get(t)) != null ? ref3.value() : void 0)); + } else { + transformationList.push((ref4 = this.get(t)) != null ? ref4.serialize() : void 0); + } + } + switch (false) { + case !Util.isString(transformations): + transformationList.push(transformations); + break; + case !Util.isArray(transformations): + resultArray = resultArray.concat(transformations); + } + transformationList = (function() { + var l, len1, results; + results = []; + for (l = 0, len1 = transformationList.length; l < len1; l++) { + value = transformationList[l]; + if (Util.isArray(value) && !Util.isEmpty(value) || !Util.isArray(value) && value) { + results.push(value); + } + } + return results; + })(); + transformationList = vars.sort().concat(variables).concat(transformationList.sort()); + if (ifParam === "if_end") { + transformationList.push(ifParam); + } else if (!Util.isEmpty(ifParam)) { + transformationList.unshift(ifParam); + } + transformationString = Util.compact(transformationList).join(this.param_separator); + if (!Util.isEmpty(transformationString)) { + resultArray.push(transformationString); + } + return Util.compact(resultArray).join(this.trans_separator); + }; + + + /** + * Provide a list of all the valid transformation option names + * @function Transformation#listNames + * @private + * @return {Array} a array of all the valid option names + */ + + TransformationBase.prototype.listNames = function() { + return Transformation.methods; + }; + + + /** + * Returns attributes for an HTML tag. + * @function Cloudinary.toHtmlAttributes + * @return PlainObject + */ + + TransformationBase.prototype.toHtmlAttributes = function() { + var attrName, height, j, key, len, options, ref, ref1, ref2, ref3, value; + options = {}; + ref = this.otherOptions; + for (key in ref) { + value = ref[key]; + if (!(!Util.contains(Transformation.PARAM_NAMES, Util.snakeCase(key)))) { + continue; + } + attrName = /^html_/.test(key) ? key.slice(5) : key; + options[attrName] = value; + } + ref1 = this.keys(); + for (j = 0, len = ref1.length; j < len; j++) { + key = ref1[j]; + if (/^html_/.test(key)) { + options[Util.camelCase(key.slice(5))] = this.getValue(key); + } + } + if (!(this.hasLayer() || this.getValue("angle") || Util.contains(["fit", "limit", "lfill"], this.getValue("crop")))) { + width = (ref2 = this.get("width")) != null ? ref2.origValue : void 0; + height = (ref3 = this.get("height")) != null ? ref3.origValue : void 0; + if (parseFloat(width) >= 1.0) { + if (options['width'] == null) { + options['width'] = width; + } + } + if (parseFloat(height) >= 1.0) { + if (options['height'] == null) { + options['height'] = height; + } + } + } + return options; + }; + + TransformationBase.prototype.isValidParamName = function(name) { + return Transformation.methods.indexOf(Util.camelCase(name)) >= 0; + }; + + + /** + * Delegate to the parent (up the call chain) to produce HTML + * @function Transformation#toHtml + * @return {string} HTML representation of the parent if possible. + * @example + * tag = cloudinary.ImageTag.new("sample", {cloud_name: "demo"}) + * // ImageTag {name: "img", publicId: "sample"} + * tag.toHtml() + * // + * tag.transformation().crop("fit").width(300).toHtml() + * // + */ + + TransformationBase.prototype.toHtml = function() { + var ref; + return (ref = this.getParent()) != null ? typeof ref.toHtml === "function" ? ref.toHtml() : void 0 : void 0; + }; + + TransformationBase.prototype.toString = function() { + return this.serialize(); + }; + + processVar = function(varArray) { + var j, len, name, ref, results, v; + if (Util.isArray(varArray)) { + results = []; + for (j = 0, len = varArray.length; j < len; j++) { + ref = varArray[j], name = ref[0], v = ref[1]; + results.push(name + "_" + (Expression.normalize(v))); + } + return results; + } else { + return varArray; + } + + /** + * Transformation Class methods. + * This is a list of the parameters defined in Transformation. + * Values are camelCased. + * @const Transformation.methods + * @private + * @ignore + * @type {Array} + */ + + /** + * Parameters that are filtered out before passing the options to an HTML tag. + * + * The list of parameters is a combination of `Transformation::methods` and `Configuration::CONFIG_PARAMS` + * @const {Array} Transformation.PARAM_NAMES + * @private + * @ignore + * @see toHtmlAttributes + */ + }; + + return TransformationBase; + + })(); + Transformation = (function(superClass) { + extend(Transformation, superClass); + + + /** + * Represents a single transformation. + * @class Transformation + * @example + * t = new cloudinary.Transformation(); + * t.angle(20).crop("scale").width("auto"); + * + * // or + * + * t = new cloudinary.Transformation( {angle: 20, crop: "scale", width: "auto"}); + */ + + function Transformation(options) { + if (options == null) { + options = {}; + } + Transformation.__super__.constructor.call(this, options); + this; + } + + + /** + * Convenience constructor + * @param {Object} options + * @return {Transformation} + * @example cl = cloudinary.Transformation.new( {angle: 20, crop: "scale", width: "auto"}) + */ + + Transformation["new"] = function(args) { + return new Transformation(args); + }; + + + /* + Transformation Parameters + */ + + Transformation.prototype.angle = function(value) { + return this.arrayParam(value, "angle", "a", ".", Expression.normalize); + }; + + Transformation.prototype.audioCodec = function(value) { + return this.param(value, "audio_codec", "ac"); + }; + + Transformation.prototype.audioFrequency = function(value) { + return this.param(value, "audio_frequency", "af"); + }; + + Transformation.prototype.aspectRatio = function(value) { + return this.param(value, "aspect_ratio", "ar", Expression.normalize); + }; + + Transformation.prototype.background = function(value) { + return this.param(value, "background", "b", Param.norm_color); + }; + + Transformation.prototype.bitRate = function(value) { + return this.param(value, "bit_rate", "br"); + }; + + Transformation.prototype.border = function(value) { + return this.param(value, "border", "bo", function(border) { + if (Util.isPlainObject(border)) { + border = Util.assign({}, { + color: "black", + width: 2 + }, border); + return border.width + "px_solid_" + (Param.norm_color(border.color)); + } else { + return border; + } + }); + }; + + Transformation.prototype.color = function(value) { + return this.param(value, "color", "co", Param.norm_color); + }; + + Transformation.prototype.colorSpace = function(value) { + return this.param(value, "color_space", "cs"); + }; + + Transformation.prototype.crop = function(value) { + return this.param(value, "crop", "c"); + }; + + Transformation.prototype.defaultImage = function(value) { + return this.param(value, "default_image", "d"); + }; + + Transformation.prototype.delay = function(value) { + return this.param(value, "delay", "dl"); + }; + + Transformation.prototype.density = function(value) { + return this.param(value, "density", "dn"); + }; + + Transformation.prototype.duration = function(value) { + return this.rangeParam(value, "duration", "du"); + }; + + Transformation.prototype.dpr = function(value) { + return this.param(value, "dpr", "dpr", (function(_this) { + return function(dpr) { + dpr = dpr.toString(); + if (dpr != null ? dpr.match(/^\d+$/) : void 0) { + return dpr + ".0"; + } else { + return Expression.normalize(dpr); + } + }; + })(this)); + }; + + Transformation.prototype.effect = function(value) { + return this.arrayParam(value, "effect", "e", ":", Expression.normalize); + }; + + Transformation.prototype["else"] = function() { + return this["if"]('else'); + }; + + Transformation.prototype.endIf = function() { + return this["if"]('end'); + }; + + Transformation.prototype.endOffset = function(value) { + return this.rangeParam(value, "end_offset", "eo"); + }; + + Transformation.prototype.fallbackContent = function(value) { + return this.param(value, "fallback_content"); + }; + + Transformation.prototype.fetchFormat = function(value) { + return this.param(value, "fetch_format", "f"); + }; + + Transformation.prototype.format = function(value) { + return this.param(value, "format"); + }; + + Transformation.prototype.flags = function(value) { + return this.arrayParam(value, "flags", "fl", "."); + }; + + Transformation.prototype.gravity = function(value) { + return this.param(value, "gravity", "g"); + }; + + Transformation.prototype.height = function(value) { + return this.param(value, "height", "h", (function(_this) { + return function() { + if (_this.getValue("crop") || _this.getValue("overlay") || _this.getValue("underlay")) { + return Expression.normalize(value); + } else { + return null; + } + }; + })(this)); + }; + + Transformation.prototype.htmlHeight = function(value) { + return this.param(value, "html_height"); + }; + + Transformation.prototype.htmlWidth = function(value) { + return this.param(value, "html_width"); + }; + + Transformation.prototype["if"] = function(value) { + var i, ifVal, j, ref, trIf, trRest; + if (value == null) { + value = ""; + } + switch (value) { + case "else": + this.chain(); + return this.param(value, "if", "if"); + case "end": + this.chain(); + for (i = j = ref = this.chained.length - 1; j >= 0; i = j += -1) { + ifVal = this.chained[i].getValue("if"); + if (ifVal === "end") { + break; + } else if (ifVal != null) { + trIf = Transformation["new"]()["if"](ifVal); + this.chained[i].remove("if"); + trRest = this.chained[i]; + this.chained[i] = Transformation["new"]().transformation([trIf, trRest]); + if (ifVal !== "else") { + break; + } + } + } + return this.param(value, "if", "if"); + case "": + return Condition["new"]().setParent(this); + default: + return this.param(value, "if", "if", function(value) { + return Condition["new"](value).toString(); + }); + } + }; + + Transformation.prototype.keyframeInterval = function(value) { + return this.param(value, "keyframe_interval", "ki"); + }; + + Transformation.prototype.offset = function(value) { + var end_o, ref, start_o; + ref = Util.isFunction(value != null ? value.split : void 0) ? value.split('..') : Util.isArray(value) ? value : [null, null], start_o = ref[0], end_o = ref[1]; + if (start_o != null) { + this.startOffset(start_o); + } + if (end_o != null) { + return this.endOffset(end_o); + } + }; + + Transformation.prototype.opacity = function(value) { + return this.param(value, "opacity", "o", Expression.normalize); + }; + + Transformation.prototype.overlay = function(value) { + return this.layerParam(value, "overlay", "l"); + }; + + Transformation.prototype.page = function(value) { + return this.param(value, "page", "pg"); + }; + + Transformation.prototype.poster = function(value) { + return this.param(value, "poster"); + }; + + Transformation.prototype.prefix = function(value) { + return this.param(value, "prefix", "p"); + }; + + Transformation.prototype.quality = function(value) { + return this.param(value, "quality", "q", Expression.normalize); + }; + + Transformation.prototype.radius = function(value) { + return this.param(value, "radius", "r", Expression.normalize); + }; + + Transformation.prototype.rawTransformation = function(value) { + return this.rawParam(value, "raw_transformation"); + }; + + Transformation.prototype.size = function(value) { + var height, ref; + if (Util.isFunction(value != null ? value.split : void 0)) { + ref = value.split('x'), width = ref[0], height = ref[1]; + this.width(width); + return this.height(height); + } + }; + + Transformation.prototype.sourceTypes = function(value) { + return this.param(value, "source_types"); + }; + + Transformation.prototype.sourceTransformation = function(value) { + return this.param(value, "source_transformation"); + }; + + Transformation.prototype.startOffset = function(value) { + return this.rangeParam(value, "start_offset", "so"); + }; + + Transformation.prototype.streamingProfile = function(value) { + return this.param(value, "streaming_profile", "sp"); + }; + + Transformation.prototype.transformation = function(value) { + return this.transformationParam(value, "transformation", "t"); + }; + + Transformation.prototype.underlay = function(value) { + return this.layerParam(value, "underlay", "u"); + }; + + Transformation.prototype.variable = function(name, value) { + return this.param(value, name, name); + }; + + Transformation.prototype.variables = function(values) { + return this.arrayParam(values, "variables"); + }; + + Transformation.prototype.videoCodec = function(value) { + return this.param(value, "video_codec", "vc", Param.process_video_params); + }; + + Transformation.prototype.videoSampling = function(value) { + return this.param(value, "video_sampling", "vs"); + }; + + Transformation.prototype.width = function(value) { + return this.param(value, "width", "w", (function(_this) { + return function() { + if (_this.getValue("crop") || _this.getValue("overlay") || _this.getValue("underlay")) { + return Expression.normalize(value); + } else { + return null; + } + }; + })(this)); + }; + + Transformation.prototype.x = function(value) { + return this.param(value, "x", "x", Expression.normalize); + }; + + Transformation.prototype.y = function(value) { + return this.param(value, "y", "y", Expression.normalize); + }; + + Transformation.prototype.zoom = function(value) { + return this.param(value, "zoom", "z", Expression.normalize); + }; + + return Transformation; + + })(TransformationBase); + + /** + * Transformation Class methods. + * This is a list of the parameters defined in Transformation. + * Values are camelCased. + */ + Transformation.methods || (Transformation.methods = Util.difference(Util.functions(Transformation.prototype), Util.functions(TransformationBase.prototype))); + + /** + * Parameters that are filtered out before passing the options to an HTML tag. + * + * The list of parameters is a combination of `Transformation::methods` and `Configuration::CONFIG_PARAMS` + */ + Transformation.PARAM_NAMES || (Transformation.PARAM_NAMES = ((function() { + var j, len, ref, results; + ref = Transformation.methods; + results = []; + for (j = 0, len = ref.length; j < len; j++) { + m = ref[j]; + results.push(Util.snakeCase(m)); + } + return results; + })()).concat(Configuration.CONFIG_PARAMS)); + + /** + * Generic HTML tag + * Depends on 'transformation', 'util' + */ + HtmlTag = (function() { + + /** + * Represents an HTML (DOM) tag + * @constructor HtmlTag + * @param {string} name - the name of the tag + * @param {string} [publicId] + * @param {Object} options + * @example tag = new HtmlTag( 'div', { 'width': 10}) + */ + var toAttribute; + + function HtmlTag(name, publicId, options) { + var transformation; + this.name = name; + this.publicId = publicId; + if (options == null) { + if (Util.isPlainObject(publicId)) { + options = publicId; + this.publicId = void 0; + } else { + options = {}; + } + } + transformation = new Transformation(options); + transformation.setParent(this); + this.transformation = function() { + return transformation; + }; + } + + + /** + * Convenience constructor + * Creates a new instance of an HTML (DOM) tag + * @function HtmlTag.new + * @param {string} name - the name of the tag + * @param {string} [publicId] + * @param {Object} options + * @return {HtmlTag} + * @example tag = HtmlTag.new( 'div', { 'width': 10}) + */ + + HtmlTag["new"] = function(name, publicId, options) { + return new this(name, publicId, options); + }; + + + /** + * Represent the given key and value as an HTML attribute. + * @function HtmlTag#toAttribute + * @protected + * @param {string} key - attribute name + * @param {*|boolean} value - the value of the attribute. If the value is boolean `true`, return the key only. + * @returns {string} the attribute + * + */ + + toAttribute = function(key, value) { + if (!value) { + return void 0; + } else if (value === true) { + return key; + } else { + return key + "=\"" + value + "\""; + } + }; + + + /** + * combine key and value from the `attr` to generate an HTML tag attributes string. + * `Transformation::toHtmlTagOptions` is used to filter out transformation and configuration keys. + * @protected + * @param {Object} attrs + * @return {string} the attributes in the format `'key1="value1" key2="value2"'` + * @ignore + */ + + HtmlTag.prototype.htmlAttrs = function(attrs) { + var key, pairs, value; + return pairs = ((function() { + var results; + results = []; + for (key in attrs) { + value = attrs[key]; + if (value) { + results.push(toAttribute(key, value)); + } + } + return results; + })()).sort().join(' '); + }; + + + /** + * Get all options related to this tag. + * @function HtmlTag#getOptions + * @returns {Object} the options + * + */ + + HtmlTag.prototype.getOptions = function() { + return this.transformation().toOptions(); + }; + + + /** + * Get the value of option `name` + * @function HtmlTag#getOption + * @param {string} name - the name of the option + * @returns {*} Returns the value of the option + * + */ + + HtmlTag.prototype.getOption = function(name) { + return this.transformation().getValue(name); + }; + + + /** + * Get the attributes of the tag. + * @function HtmlTag#attributes + * @returns {Object} attributes + */ + + HtmlTag.prototype.attributes = function() { + return this.transformation().toHtmlAttributes(); + }; + + + /** + * Set a tag attribute named `name` to `value` + * @function HtmlTag#setAttr + * @param {string} name - the name of the attribute + * @param {string} value - the value of the attribute + */ + + HtmlTag.prototype.setAttr = function(name, value) { + this.transformation().set("html_" + name, value); + return this; + }; + + + /** + * Get the value of the tag attribute `name` + * @function HtmlTag#getAttr + * @param {string} name - the name of the attribute + * @returns {*} + */ + + HtmlTag.prototype.getAttr = function(name) { + return this.attributes()["html_" + name] || this.attributes()[name]; + }; + + + /** + * Remove the tag attributed named `name` + * @function HtmlTag#removeAttr + * @param {string} name - the name of the attribute + * @returns {*} + */ + + HtmlTag.prototype.removeAttr = function(name) { + var ref; + return (ref = this.transformation().remove("html_" + name)) != null ? ref : this.transformation().remove(name); + }; + + + /** + * @function HtmlTag#content + * @protected + * @ignore + */ + + HtmlTag.prototype.content = function() { + return ""; + }; + + + /** + * @function HtmlTag#openTag + * @protected + * @ignore + */ + + HtmlTag.prototype.openTag = function() { + return "<" + this.name + " " + (this.htmlAttrs(this.attributes())) + ">"; + }; + + + /** + * @function HtmlTag#closeTag + * @protected + * @ignore + */ + + HtmlTag.prototype.closeTag = function() { + return ""; + }; + + + /** + * Generates an HTML representation of the tag. + * @function HtmlTag#toHtml + * @returns {string} Returns HTML in string format + */ + + HtmlTag.prototype.toHtml = function() { + return this.openTag() + this.content() + this.closeTag(); + }; + + + /** + * Creates a DOM object representing the tag. + * @function HtmlTag#toDOM + * @returns {Element} + */ + + HtmlTag.prototype.toDOM = function() { + var element, name, ref, value; + if (!Util.isFunction(typeof document !== "undefined" && document !== null ? document.createElement : void 0)) { + throw "Can't create DOM if document is not present!"; + } + element = document.createElement(this.name); + ref = this.attributes(); + for (name in ref) { + value = ref[name]; + element[name] = value; + } + return element; + }; + + HtmlTag.isResponsive = function(tag, responsiveClass) { + var dataSrc; + dataSrc = Util.getData(tag, 'src-cache') || Util.getData(tag, 'src'); + return Util.hasClass(tag, responsiveClass) && /\bw_auto\b/.exec(dataSrc); + }; + + return HtmlTag; + + })(); + + /** + * Image Tag + * Depends on 'tags/htmltag', 'cloudinary' + */ + ImageTag = (function(superClass) { + extend(ImageTag, superClass); + + + /** + * Creates an HTML (DOM) Image tag using Cloudinary as the source. + * @constructor ImageTag + * @extends HtmlTag + * @param {string} [publicId] + * @param {Object} [options] + */ + + function ImageTag(publicId, options) { + if (options == null) { + options = {}; + } + ImageTag.__super__.constructor.call(this, "img", publicId, options); + } + + + /** @override */ + + ImageTag.prototype.closeTag = function() { + return ""; + }; + + + /** @override */ + + ImageTag.prototype.attributes = function() { + var attr, options, srcAttribute; + attr = ImageTag.__super__.attributes.call(this) || []; + options = this.getOptions(); + srcAttribute = options.responsive && !options.client_hints ? 'data-src' : 'src'; + if (attr[srcAttribute] == null) { + attr[srcAttribute] = new Cloudinary(this.getOptions()).url(this.publicId); + } + return attr; + }; + + return ImageTag; + + })(HtmlTag); + + /** + * Video Tag + * Depends on 'tags/htmltag', 'util', 'cloudinary' + */ + VideoTag = (function(superClass) { + var DEFAULT_POSTER_OPTIONS, DEFAULT_VIDEO_SOURCE_TYPES, VIDEO_TAG_PARAMS; + + extend(VideoTag, superClass); + + VIDEO_TAG_PARAMS = ['source_types', 'source_transformation', 'fallback_content', 'poster']; + + DEFAULT_VIDEO_SOURCE_TYPES = ['webm', 'mp4', 'ogv']; + + DEFAULT_POSTER_OPTIONS = { + format: 'jpg', + resource_type: 'video' + }; + + + /** + * Creates an HTML (DOM) Video tag using Cloudinary as the source. + * @constructor VideoTag + * @extends HtmlTag + * @param {string} [publicId] + * @param {Object} [options] + */ + + function VideoTag(publicId, options) { + if (options == null) { + options = {}; + } + options = Util.defaults({}, options, Cloudinary.DEFAULT_VIDEO_PARAMS); + VideoTag.__super__.constructor.call(this, "video", publicId.replace(/\.(mp4|ogv|webm)$/, ''), options); + } + + + /** + * Set the transformation to apply on each source + * @function VideoTag#setSourceTransformation + * @param {Object} an object with pairs of source type and source transformation + * @returns {VideoTag} Returns this instance for chaining purposes. + */ + + VideoTag.prototype.setSourceTransformation = function(value) { + this.transformation().sourceTransformation(value); + return this; + }; + + + /** + * Set the source types to include in the video tag + * @function VideoTag#setSourceTypes + * @param {Array} an array of source types + * @returns {VideoTag} Returns this instance for chaining purposes. + */ + + VideoTag.prototype.setSourceTypes = function(value) { + this.transformation().sourceTypes(value); + return this; + }; + + + /** + * Set the poster to be used in the video tag + * @function VideoTag#setPoster + * @param {string|Object} value + * - string: a URL to use for the poster + * - Object: transformation parameters to apply to the poster. May optionally include a public_id to use instead of the video public_id. + * @returns {VideoTag} Returns this instance for chaining purposes. + */ + + VideoTag.prototype.setPoster = function(value) { + this.transformation().poster(value); + return this; + }; + + + /** + * Set the content to use as fallback in the video tag + * @function VideoTag#setFallbackContent + * @param {string} value - the content to use, in HTML format + * @returns {VideoTag} Returns this instance for chaining purposes. + */ + + VideoTag.prototype.setFallbackContent = function(value) { + this.transformation().fallbackContent(value); + return this; + }; + + VideoTag.prototype.content = function() { + var cld, fallback, innerTags, mimeType, sourceTransformation, sourceTypes, src, srcType, transformation, videoType; + sourceTypes = this.transformation().getValue('source_types'); + sourceTransformation = this.transformation().getValue('source_transformation'); + fallback = this.transformation().getValue('fallback_content'); + if (Util.isArray(sourceTypes)) { + cld = new Cloudinary(this.getOptions()); + innerTags = (function() { + var j, len, results; + results = []; + for (j = 0, len = sourceTypes.length; j < len; j++) { + srcType = sourceTypes[j]; + transformation = sourceTransformation[srcType] || {}; + src = cld.url("" + this.publicId, Util.defaults({}, transformation, { + resource_type: 'video', + format: srcType + })); + videoType = srcType === 'ogv' ? 'ogg' : srcType; + mimeType = 'video/' + videoType; + results.push(""); + } + return results; + }).call(this); + } else { + innerTags = []; + } + return innerTags.join('') + fallback; + }; + + VideoTag.prototype.attributes = function() { + var a, attr, j, len, poster, ref, ref1, sourceTypes; + sourceTypes = this.getOption('source_types'); + poster = (ref = this.getOption('poster')) != null ? ref : {}; + if (Util.isPlainObject(poster)) { + defaults = poster.public_id != null ? Cloudinary.DEFAULT_IMAGE_PARAMS : DEFAULT_POSTER_OPTIONS; + poster = new Cloudinary(this.getOptions()).url((ref1 = poster.public_id) != null ? ref1 : this.publicId, Util.defaults({}, poster, defaults)); + } + attr = VideoTag.__super__.attributes.call(this) || []; + for (j = 0, len = attr.length; j < len; j++) { + a = attr[j]; + if (!Util.contains(VIDEO_TAG_PARAMS)) { + attr = a; + } + } + if (!Util.isArray(sourceTypes)) { + attr["src"] = new Cloudinary(this.getOptions()).url(this.publicId, { + resource_type: 'video', + format: sourceTypes + }); + } + if (poster != null) { + attr["poster"] = poster; + } + return attr; + }; + + return VideoTag; + + })(HtmlTag); + + /** + * Image Tag + * Depends on 'tags/htmltag', 'cloudinary' + */ + ClientHintsMetaTag = (function(superClass) { + extend(ClientHintsMetaTag, superClass); + + + /** + * Creates an HTML (DOM) Meta tag that enables client-hints. + * @constructor ClientHintsMetaTag + * @extends HtmlTag + */ + + function ClientHintsMetaTag(options) { + ClientHintsMetaTag.__super__.constructor.call(this, 'meta', void 0, Util.assign({ + "http-equiv": "Accept-CH", + content: "DPR, Viewport-Width, Width" + }, options)); + } + + + /** @override */ + + ClientHintsMetaTag.prototype.closeTag = function() { + return ""; + }; + + return ClientHintsMetaTag; + + })(HtmlTag); + Cloudinary = (function() { + var AKAMAI_SHARED_CDN, CF_SHARED_CDN, DEFAULT_POSTER_OPTIONS, DEFAULT_VIDEO_SOURCE_TYPES, OLD_AKAMAI_SHARED_CDN, SEO_TYPES, SHARED_CDN, VERSION, absolutize, applyBreakpoints, cdnSubdomainNumber, closestAbove, cloudinaryUrlPrefix, defaultBreakpoints, finalizeResourceType, findContainerWidth, maxWidth, updateDpr; + + VERSION = "2.5.0"; + + CF_SHARED_CDN = "d3jpl91pxevbkh.cloudfront.net"; + + OLD_AKAMAI_SHARED_CDN = "cloudinary-a.akamaihd.net"; + + AKAMAI_SHARED_CDN = "res.cloudinary.com"; + + SHARED_CDN = AKAMAI_SHARED_CDN; + + DEFAULT_POSTER_OPTIONS = { + format: 'jpg', + resource_type: 'video' + }; + + DEFAULT_VIDEO_SOURCE_TYPES = ['webm', 'mp4', 'ogv']; + + SEO_TYPES = { + "image/upload": "images", + "image/private": "private_images", + "image/authenticated": "authenticated_images", + "raw/upload": "files", + "video/upload": "videos" + }; + + + /** + * @const {Object} Cloudinary.DEFAULT_IMAGE_PARAMS + * Defaults values for image parameters. + * + * (Previously defined using option_consume() ) + */ + + Cloudinary.DEFAULT_IMAGE_PARAMS = { + resource_type: "image", + transformation: [], + type: 'upload' + }; + + + /** + * Defaults values for video parameters. + * @const {Object} Cloudinary.DEFAULT_VIDEO_PARAMS + * (Previously defined using option_consume() ) + */ + + Cloudinary.DEFAULT_VIDEO_PARAMS = { + fallback_content: '', + resource_type: "video", + source_transformation: {}, + source_types: DEFAULT_VIDEO_SOURCE_TYPES, + transformation: [], + type: 'upload' + }; + + + /** + * Main Cloudinary class + * @class Cloudinary + * @param {Object} options - options to configure Cloudinary + * @see Configuration for more details + * @example + * var cl = new cloudinary.Cloudinary( { cloud_name: "mycloud"}); + * var imgTag = cl.image("myPicID"); + */ + + function Cloudinary(options) { + var configuration; + this.devicePixelRatioCache = {}; + this.responsiveConfig = {}; + this.responsiveResizeInitialized = false; + configuration = new Configuration(options); + this.config = function(newConfig, newValue) { + return configuration.config(newConfig, newValue); + }; + + /** + * Use \ tags in the document to configure this Cloudinary instance. + * @return {Cloudinary} this for chaining + */ + this.fromDocument = function() { + configuration.fromDocument(); + return this; + }; + + /** + * Use environment variables to configure this Cloudinary instance. + * @return {Cloudinary} this for chaining + */ + this.fromEnvironment = function() { + configuration.fromEnvironment(); + return this; + }; + + /** + * Initialize configuration. + * @function Cloudinary#init + * @see Configuration#init + * @return {Cloudinary} this for chaining + */ + this.init = function() { + configuration.init(); + return this; + }; + } + + + /** + * Convenience constructor + * @param {Object} options + * @return {Cloudinary} + * @example cl = cloudinary.Cloudinary.new( { cloud_name: "mycloud"}) + */ + + Cloudinary["new"] = function(options) { + return new this(options); + }; + + + /** + * Return the resource type and action type based on the given configuration + * @function Cloudinary#finalizeResourceType + * @param {Object|string} resourceType + * @param {string} [type='upload'] + * @param {string} [urlSuffix] + * @param {boolean} [useRootPath] + * @param {boolean} [shorten] + * @returns {string} resource_type/type + * @ignore + */ + + finalizeResourceType = function(resourceType, type, urlSuffix, useRootPath, shorten) { + var key, options; + if (resourceType == null) { + resourceType = "image"; + } + if (type == null) { + type = "upload"; + } + if (Util.isPlainObject(resourceType)) { + options = resourceType; + resourceType = options.resource_type; + type = options.type; + urlSuffix = options.url_suffix; + useRootPath = options.use_root_path; + shorten = options.shorten; + } + if (type == null) { + type = 'upload'; + } + if (urlSuffix != null) { + resourceType = SEO_TYPES[resourceType + "/" + type]; + type = null; + if (resourceType == null) { + throw new Error("URL Suffix only supported for " + (((function() { + var results; + results = []; + for (key in SEO_TYPES) { + results.push(key); + } + return results; + })()).join(', '))); + } + } + if (useRootPath) { + if (resourceType === 'image' && type === 'upload' || resourceType === "images") { + resourceType = null; + type = null; + } else { + throw new Error("Root path only supported for image/upload"); + } + } + if (shorten && resourceType === 'image' && type === 'upload') { + resourceType = 'iu'; + type = null; + } + return [resourceType, type].join("/"); + }; + + absolutize = function(url) { + var prefix; + if (!url.match(/^https?:\//)) { + prefix = document.location.protocol + '//' + document.location.host; + if (url[0] === '?') { + prefix += document.location.pathname; + } else if (url[0] !== '/') { + prefix += document.location.pathname.replace(/\/[^\/]*$/, '/'); + } + url = prefix + url; + } + return url; + }; + + + /** + * Generate an resource URL. + * @function Cloudinary#url + * @param {string} publicId - the public ID of the resource + * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters + * and {@link Configuration} parameters + * @param {string} [options.type='upload'] - the classification of the resource + * @param {Object} [options.resource_type='image'] - the type of the resource + * @return {string} The resource URL + */ + + Cloudinary.prototype.url = function(publicId, options) { + var error, error1, prefix, ref, resourceTypeAndType, transformation, transformationString, url, version; + if (options == null) { + options = {}; + } + if (!publicId) { + return publicId; + } + if (options instanceof Transformation) { + options = options.toOptions(); + } + options = Util.defaults({}, options, this.config(), Cloudinary.DEFAULT_IMAGE_PARAMS); + if (options.type === 'fetch') { + options.fetch_format = options.fetch_format || options.format; + publicId = absolutize(publicId); + } + transformation = new Transformation(options); + transformationString = transformation.serialize(); + if (!options.cloud_name) { + throw 'Unknown cloud_name'; + } + if (publicId.search('/') >= 0 && !publicId.match(/^v[0-9]+/) && !publicId.match(/^https?:\//) && !((ref = options.version) != null ? ref.toString() : void 0)) { + options.version = 1; + } + if (publicId.match(/^https?:/)) { + if (options.type === 'upload' || options.type === 'asset') { + url = publicId; + } else { + publicId = encodeURIComponent(publicId).replace(/%3A/g, ':').replace(/%2F/g, '/'); + } + } else { + try { + publicId = decodeURIComponent(publicId); + } catch (error1) { + error = error1; + } + publicId = encodeURIComponent(publicId).replace(/%3A/g, ':').replace(/%2F/g, '/'); + if (options.url_suffix) { + if (options.url_suffix.match(/[\.\/]/)) { + throw 'url_suffix should not include . or /'; + } + publicId = publicId + '/' + options.url_suffix; + } + if (options.format) { + if (!options.trust_public_id) { + publicId = publicId.replace(/\.(jpg|png|gif|webp)$/, ''); + } + publicId = publicId + '.' + options.format; + } + } + prefix = cloudinaryUrlPrefix(publicId, options); + resourceTypeAndType = finalizeResourceType(options.resource_type, options.type, options.url_suffix, options.use_root_path, options.shorten); + version = options.version ? 'v' + options.version : ''; + return url || Util.compact([prefix, resourceTypeAndType, transformationString, version, publicId]).join('/').replace(/([^:])\/+/g, '$1/'); + }; + + + /** + * Generate an video resource URL. + * @function Cloudinary#video_url + * @param {string} publicId - the public ID of the resource + * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters + * and {@link Configuration} parameters + * @param {string} [options.type='upload'] - the classification of the resource + * @return {string} The video URL + */ + + Cloudinary.prototype.video_url = function(publicId, options) { + options = Util.assign({ + resource_type: 'video' + }, options); + return this.url(publicId, options); + }; + + + /** + * Generate an video thumbnail URL. + * @function Cloudinary#video_thumbnail_url + * @param {string} publicId - the public ID of the resource + * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters + * and {@link Configuration} parameters + * @param {string} [options.type='upload'] - the classification of the resource + * @return {string} The video thumbnail URL + */ + + Cloudinary.prototype.video_thumbnail_url = function(publicId, options) { + options = Util.assign({}, DEFAULT_POSTER_OPTIONS, options); + return this.url(publicId, options); + }; + + + /** + * Generate a string representation of the provided transformation options. + * @function Cloudinary#transformation_string + * @param {Object} options - the transformation options + * @returns {string} The transformation string + */ + + Cloudinary.prototype.transformation_string = function(options) { + return new Transformation(options).serialize(); + }; + + + /** + * Generate an image tag. + * @function Cloudinary#image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.image = function(publicId, options) { + var client_hints, img, ref, ref1; + if (options == null) { + options = {}; + } + img = this.imageTag(publicId, options); + client_hints = (ref = (ref1 = options.client_hints) != null ? ref1 : this.config('client_hints')) != null ? ref : false; + if (!((options.src != null) || client_hints)) { + img.setAttr("src", ''); + } + img = img.toDOM(); + if (!client_hints) { + Util.setData(img, 'src-cache', this.url(publicId, options)); + this.cloudinary_update(img, options); + } + return img; + }; + + + /** + * Creates a new ImageTag instance, configured using this own's configuration. + * @function Cloudinary#imageTag + * @param {string} publicId - the public ID of the resource + * @param {Object} options - additional options to pass to the new ImageTag instance + * @return {ImageTag} An ImageTag that is attached (chained) to this Cloudinary instance + */ + + Cloudinary.prototype.imageTag = function(publicId, options) { + var tag; + tag = new ImageTag(publicId, this.config()); + tag.transformation().fromOptions(options); + return tag; + }; + + + /** + * Generate an image tag for the video thumbnail. + * @function Cloudinary#video_thumbnail + * @param {string} publicId - the public ID of the video + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} An image tag element + */ + + Cloudinary.prototype.video_thumbnail = function(publicId, options) { + return this.image(publicId, Util.merge({}, DEFAULT_POSTER_OPTIONS, options)); + }; + + + /** + * @function Cloudinary#facebook_profile_image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.facebook_profile_image = function(publicId, options) { + return this.image(publicId, Util.assign({ + type: 'facebook' + }, options)); + }; + + + /** + * @function Cloudinary#twitter_profile_image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.twitter_profile_image = function(publicId, options) { + return this.image(publicId, Util.assign({ + type: 'twitter' + }, options)); + }; + + + /** + * @function Cloudinary#twitter_name_profile_image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.twitter_name_profile_image = function(publicId, options) { + return this.image(publicId, Util.assign({ + type: 'twitter_name' + }, options)); + }; + + + /** + * @function Cloudinary#gravatar_image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.gravatar_image = function(publicId, options) { + return this.image(publicId, Util.assign({ + type: 'gravatar' + }, options)); + }; + + + /** + * @function Cloudinary#fetch_image + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.fetch_image = function(publicId, options) { + return this.image(publicId, Util.assign({ + type: 'fetch' + }, options)); + }; + + + /** + * @function Cloudinary#video + * @param {string} publicId - the public ID of the image + * @param {Object} [options] - options for the tag and transformations + * @return {HTMLImageElement} an image tag element + */ + + Cloudinary.prototype.video = function(publicId, options) { + if (options == null) { + options = {}; + } + return this.videoTag(publicId, options).toHtml(); + }; + + + /** + * Creates a new VideoTag instance, configured using this own's configuration. + * @function Cloudinary#videoTag + * @param {string} publicId - the public ID of the resource + * @param {Object} options - additional options to pass to the new VideoTag instance + * @return {VideoTag} A VideoTag that is attached (chained) to this Cloudinary instance + */ + + Cloudinary.prototype.videoTag = function(publicId, options) { + options = Util.defaults({}, options, this.config()); + return new VideoTag(publicId, options); + }; + + + /** + * Generate the URL of the sprite image + * @function Cloudinary#sprite_css + * @param {string} publicId - the public ID of the resource + * @param {Object} [options] - options for the tag and transformations + * @see {@link http://cloudinary.com/documentation/sprite_generation Sprite generation} + */ + + Cloudinary.prototype.sprite_css = function(publicId, options) { + options = Util.assign({ + type: 'sprite' + }, options); + if (!publicId.match(/.css$/)) { + options.format = 'css'; + } + return this.url(publicId, options); + }; + + + /** + * Initialize the responsive behaviour.
+ * Calls {@link Cloudinary#cloudinary_update} to modify image tags. + * @function Cloudinary#responsive + * @param {Object} options + * @param {String} [options.responsive_class='cld-responsive'] - provide an alternative class used to locate img tags + * @param {number} [options.responsive_debounce=100] - the debounce interval in milliseconds. + * @param {boolean} [bootstrap=true] if true processes the img tags by calling cloudinary_update. When false the tags will be processed only after a resize event. + * @see {@link Cloudinary#cloudinary_update} for additional configuration parameters + */ + + Cloudinary.prototype.responsive = function(options, bootstrap) { + var ref, ref1, ref2, responsiveClass, responsiveResize, timeout; + if (bootstrap == null) { + bootstrap = true; + } + this.responsiveConfig = Util.merge(this.responsiveConfig || {}, options); + responsiveClass = (ref = this.responsiveConfig['responsive_class']) != null ? ref : this.config('responsive_class'); + if (bootstrap) { + this.cloudinary_update("img." + responsiveClass + ", img.cld-hidpi", this.responsiveConfig); + } + responsiveResize = (ref1 = (ref2 = this.responsiveConfig['responsive_resize']) != null ? ref2 : this.config('responsive_resize')) != null ? ref1 : true; + if (responsiveResize && !this.responsiveResizeInitialized) { + this.responsiveConfig.resizing = this.responsiveResizeInitialized = true; + timeout = null; + return window.addEventListener('resize', (function(_this) { + return function() { + var debounce, ref3, ref4, reset, run, wait, waitFunc; + debounce = (ref3 = (ref4 = _this.responsiveConfig['responsive_debounce']) != null ? ref4 : _this.config('responsive_debounce')) != null ? ref3 : 100; + reset = function() { + if (timeout) { + clearTimeout(timeout); + return timeout = null; + } + }; + run = function() { + return _this.cloudinary_update("img." + responsiveClass, _this.responsiveConfig); + }; + waitFunc = function() { + reset(); + return run(); + }; + wait = function() { + reset(); + return timeout = setTimeout(waitFunc, debounce); + }; + if (debounce) { + return wait(); + } else { + return run(); + } + }; + })(this)); + } + }; + + + /** + * @function Cloudinary#calc_breakpoint + * @private + * @ignore + */ + + Cloudinary.prototype.calc_breakpoint = function(element, width, steps) { + var breakpoints, point; + breakpoints = Util.getData(element, 'breakpoints') || Util.getData(element, 'stoppoints') || this.config('breakpoints') || this.config('stoppoints') || defaultBreakpoints; + if (Util.isFunction(breakpoints)) { + return breakpoints(width, steps); + } else { + if (Util.isString(breakpoints)) { + breakpoints = ((function() { + var j, len, ref, results; + ref = breakpoints.split(','); + results = []; + for (j = 0, len = ref.length; j < len; j++) { + point = ref[j]; + results.push(parseInt(point)); + } + return results; + })()).sort(function(a, b) { + return a - b; + }); + } + return closestAbove(breakpoints, width); + } + }; + + + /** + * @function Cloudinary#calc_stoppoint + * @deprecated Use {@link calc_breakpoint} instead. + * @private + * @ignore + */ + + Cloudinary.prototype.calc_stoppoint = Cloudinary.prototype.calc_breakpoint; + + + /** + * @function Cloudinary#device_pixel_ratio + * @private + */ + + Cloudinary.prototype.device_pixel_ratio = function(roundDpr) { + var dpr, dprString; + if (roundDpr == null) { + roundDpr = true; + } + dpr = (typeof window !== "undefined" && window !== null ? window.devicePixelRatio : void 0) || 1; + if (roundDpr) { + dpr = Math.ceil(dpr); + } + if (dpr <= 0 || dpr === NaN) { + dpr = 1; + } + dprString = dpr.toString(); + if (dprString.match(/^\d+$/)) { + dprString += '.0'; + } + return dprString; + }; + + defaultBreakpoints = function(width, steps) { + if (steps == null) { + steps = 100; + } + return steps * Math.ceil(width / steps); + }; + + closestAbove = function(list, value) { + var i; + i = list.length - 2; + while (i >= 0 && list[i] >= value) { + i--; + } + return list[i + 1]; + }; + + cdnSubdomainNumber = function(publicId) { + return crc32(publicId) % 5 + 1; + }; + + cloudinaryUrlPrefix = function(publicId, options) { + var cdnPart, host, path, protocol, ref, subdomain; + if (((ref = options.cloud_name) != null ? ref.indexOf("/") : void 0) === 0) { + return '/res' + options.cloud_name; + } + protocol = "http://"; + cdnPart = ""; + subdomain = "res"; + host = ".cloudinary.com"; + path = "/" + options.cloud_name; + if (options.protocol) { + protocol = options.protocol + '//'; + } + if (options.private_cdn) { + cdnPart = options.cloud_name + "-"; + path = ""; + } + if (options.cdn_subdomain) { + subdomain = "res-" + cdnSubdomainNumber(publicId); + } + if (options.secure) { + protocol = "https://"; + if (options.secure_cdn_subdomain === false) { + subdomain = "res"; + } + if ((options.secure_distribution != null) && options.secure_distribution !== OLD_AKAMAI_SHARED_CDN && options.secure_distribution !== SHARED_CDN) { + cdnPart = ""; + subdomain = ""; + host = options.secure_distribution; + } + } else if (options.cname) { + protocol = "http://"; + cdnPart = ""; + subdomain = options.cdn_subdomain ? 'a' + ((crc32(publicId) % 5) + 1) + '.' : ''; + host = options.cname; + } + return [protocol, cdnPart, subdomain, host, path].join(""); + }; + + + /** + * Finds all `img` tags under each node and sets it up to provide the image through Cloudinary + * @param {Element[]} nodes the parent nodes to search for img under + * @param {Object} [options={}] options and transformations params + * @function Cloudinary#processImageTags + */ + + Cloudinary.prototype.processImageTags = function(nodes, options) { + var images, imgOptions, node, publicId, url; + if (options == null) { + options = {}; + } + if (Util.isEmpty(nodes)) { + return this; + } + options = Util.defaults({}, options, this.config()); + images = (function() { + var j, len, ref, results; + results = []; + for (j = 0, len = nodes.length; j < len; j++) { + node = nodes[j]; + if (!(((ref = node.tagName) != null ? ref.toUpperCase() : void 0) === 'IMG')) { + continue; + } + imgOptions = Util.assign({ + width: node.getAttribute('width'), + height: node.getAttribute('height'), + src: node.getAttribute('src') + }, options); + publicId = imgOptions['source'] || imgOptions['src']; + delete imgOptions['source']; + delete imgOptions['src']; + url = this.url(publicId, imgOptions); + imgOptions = new Transformation(imgOptions).toHtmlAttributes(); + Util.setData(node, 'src-cache', url); + node.setAttribute('width', imgOptions.width); + node.setAttribute('height', imgOptions.height); + results.push(node); + } + return results; + }).call(this); + this.cloudinary_update(images, options); + return this; + }; + + applyBreakpoints = function(tag, width, steps, options) { + var ref, ref1, ref2, responsive_use_breakpoints; + responsive_use_breakpoints = (ref = (ref1 = (ref2 = options['responsive_use_breakpoints']) != null ? ref2 : options['responsive_use_stoppoints']) != null ? ref1 : this.config('responsive_use_breakpoints')) != null ? ref : this.config('responsive_use_stoppoints'); + if ((!responsive_use_breakpoints) || (responsive_use_breakpoints === 'resize' && !options.resizing)) { + return width; + } else { + return this.calc_breakpoint(tag, width, steps); + } + }; + + findContainerWidth = function(element) { + var containerWidth, style; + containerWidth = 0; + while (((element = element != null ? element.parentNode : void 0) instanceof Element) && !containerWidth) { + style = window.getComputedStyle(element); + if (!/^inline/.test(style.display)) { + containerWidth = Util.width(element); + } + } + return containerWidth; + }; + + updateDpr = function(dataSrc, roundDpr) { + return dataSrc.replace(/\bdpr_(1\.0|auto)\b/g, 'dpr_' + this.device_pixel_ratio(roundDpr)); + }; + + maxWidth = function(requiredWidth, tag) { + var imageWidth; + imageWidth = Util.getData(tag, 'width') || 0; + if (requiredWidth > imageWidth) { + imageWidth = requiredWidth; + Util.setData(tag, 'width', requiredWidth); + } + return imageWidth; + }; + + + /** + * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio. + * Only images marked with the cld-responsive class have w_auto updated. + * @function Cloudinary#cloudinary_update + * @param {(Array|string|NodeList)} elements - the elements to modify + * @param {Object} options + * @param {boolean|string} [options.responsive_use_breakpoints=true] + * - when `true`, always use breakpoints for width + * - when `"resize"` use exact width on first render and breakpoints on resize + * - when `false` always use exact width + * @param {boolean} [options.responsive] - if `true`, enable responsive on this element. Can be done by adding cld-responsive. + * @param {boolean} [options.responsive_preserve_height] - if set to true, original css height is preserved. + * Should only be used if the transformation supports different aspect ratios. + */ + + Cloudinary.prototype.cloudinary_update = function(elements, options) { + var containerWidth, dataSrc, j, len, match, ref, ref1, ref2, ref3, ref4, ref5, requiredWidth, responsive, responsiveClass, roundDpr, setUrl, tag; + if (options == null) { + options = {}; + } + if (elements === null) { + return this; + } + responsive = (ref = (ref1 = options.responsive) != null ? ref1 : this.config('responsive')) != null ? ref : false; + elements = (function() { + switch (false) { + case !Util.isArray(elements): + return elements; + case elements.constructor.name !== "NodeList": + return elements; + case !Util.isString(elements): + return document.querySelectorAll(elements); + default: + return [elements]; + } + })(); + responsiveClass = (ref2 = (ref3 = this.responsiveConfig['responsive_class']) != null ? ref3 : options['responsive_class']) != null ? ref2 : this.config('responsive_class'); + roundDpr = (ref4 = options['round_dpr']) != null ? ref4 : this.config('round_dpr'); + for (j = 0, len = elements.length; j < len; j++) { + tag = elements[j]; + if (!((ref5 = tag.tagName) != null ? ref5.match(/img/i) : void 0)) { + continue; + } + setUrl = true; + if (responsive) { + Util.addClass(tag, responsiveClass); + } + dataSrc = Util.getData(tag, 'src-cache') || Util.getData(tag, 'src'); + if (!Util.isEmpty(dataSrc)) { + dataSrc = updateDpr.call(this, dataSrc, roundDpr); + if (HtmlTag.isResponsive(tag, responsiveClass)) { + containerWidth = findContainerWidth(tag); + if (containerWidth !== 0) { + switch (false) { + case !/w_auto:breakpoints/.test(dataSrc): + requiredWidth = maxWidth(containerWidth, tag); + dataSrc = dataSrc.replace(/w_auto:breakpoints([_0-9]*)(:[0-9]+)?/, "w_auto:breakpoints$1:" + requiredWidth); + break; + case !(match = /w_auto(:(\d+))?/.exec(dataSrc)): + requiredWidth = applyBreakpoints.call(this, tag, containerWidth, match[2], options); + requiredWidth = maxWidth(requiredWidth, tag); + dataSrc = dataSrc.replace(/w_auto[^,\/]*/g, "w_" + requiredWidth); + } + Util.removeAttribute(tag, 'width'); + if (!options.responsive_preserve_height) { + Util.removeAttribute(tag, 'height'); + } + } else { + setUrl = false; + } + } + if (setUrl) { + Util.setAttribute(tag, 'src', dataSrc); + } + } + } + return this; + }; + + + /** + * Provide a transformation object, initialized with own's options, for chaining purposes. + * @function Cloudinary#transformation + * @param {Object} options + * @return {Transformation} + */ + + Cloudinary.prototype.transformation = function(options) { + return Transformation["new"](this.config()).fromOptions(options).setParent(this); + }; + + return Cloudinary; + + })(); + + /** + * Cloudinary jQuery plugin + * Depends on 'jquery', 'util', 'transformation', 'cloudinary' + */ + CloudinaryJQuery = (function(superClass) { + extend(CloudinaryJQuery, superClass); + + + /** + * Cloudinary class with jQuery support + * @constructor CloudinaryJQuery + * @extends Cloudinary + */ + + function CloudinaryJQuery(options) { + CloudinaryJQuery.__super__.constructor.call(this, options); + } + + + /** + * @override + */ + + CloudinaryJQuery.prototype.image = function(publicId, options) { + var client_hints, img, ref, ref1; + if (options == null) { + options = {}; + } + img = this.imageTag(publicId, options); + client_hints = (ref = (ref1 = options.client_hints) != null ? ref1 : this.config('client_hints')) != null ? ref : false; + if (!((options.src != null) || client_hints)) { + img.setAttr("src", ''); + } + img = jQuery(img.toHtml()); + if (!client_hints) { + img.data('src-cache', this.url(publicId, options)).cloudinary_update(options); + } + return img; + }; + + + /** + * @override + */ + + CloudinaryJQuery.prototype.responsive = function(options) { + var ref, ref1, ref2, responsiveClass, responsiveConfig, responsiveResizeInitialized, responsive_resize, timeout; + responsiveConfig = jQuery.extend(responsiveConfig || {}, options); + responsiveClass = (ref = this.responsiveConfig['responsive_class']) != null ? ref : this.config('responsive_class'); + jQuery("img." + responsiveClass + ", img.cld-hidpi").cloudinary_update(responsiveConfig); + responsive_resize = (ref1 = (ref2 = responsiveConfig['responsive_resize']) != null ? ref2 : this.config('responsive_resize')) != null ? ref1 : true; + if (responsive_resize && !responsiveResizeInitialized) { + responsiveConfig.resizing = responsiveResizeInitialized = true; + timeout = null; + return jQuery(window).on('resize', (function(_this) { + return function() { + var debounce, ref3, ref4, reset, run, wait; + debounce = (ref3 = (ref4 = responsiveConfig['responsive_debounce']) != null ? ref4 : _this.config('responsive_debounce')) != null ? ref3 : 100; + reset = function() { + if (timeout) { + clearTimeout(timeout); + return timeout = null; + } + }; + run = function() { + return jQuery("img." + responsiveClass).cloudinary_update(responsiveConfig); + }; + wait = function() { + reset(); + return setTimeout((function() { + reset(); + return run(); + }), debounce); + }; + if (debounce) { + return wait(); + } else { + return run(); + } + }; + })(this)); + } + }; + + return CloudinaryJQuery; + + })(Cloudinary); + + /** + * The following methods are provided through the jQuery class + * @class jQuery + */ + + /** + * Convert all img tags in the collection to utilize Cloudinary. + * @function jQuery#cloudinary + * @param {Object} [options] - options for the tag and transformations + * @returns {jQuery} + */ + jQuery.fn.cloudinary = function(options) { + this.filter('img').each(function() { + var img_options, public_id, url; + img_options = jQuery.extend({ + width: jQuery(this).attr('width'), + height: jQuery(this).attr('height'), + src: jQuery(this).attr('src') + }, jQuery(this).data(), options); + public_id = img_options.source || img_options.src; + delete img_options.source; + delete img_options.src; + url = jQuery.cloudinary.url(public_id, img_options); + img_options = new Transformation(img_options).toHtmlAttributes(); + return jQuery(this).data('src-cache', url).attr({ + width: img_options.width, + height: img_options.height + }); + }).cloudinary_update(options); + return this; + }; + + /** + * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio. + * Only images marked with the cld-responsive class have w_auto updated. + * options: + * - responsive_use_stoppoints: + * - true - always use stoppoints for width + * - "resize" - use exact width on first render and stoppoints on resize (default) + * - false - always use exact width + * - responsive: + * - true - enable responsive on this element. Can be done by adding cld-responsive. + * Note that jQuery.cloudinary.responsive() should be called once on the page. + * - responsive_preserve_height: if set to true, original css height is perserved. Should only be used if the transformation supports different aspect ratios. + */ + jQuery.fn.cloudinary_update = function(options) { + if (options == null) { + options = {}; + } + jQuery.cloudinary.cloudinary_update(this.filter('img').toArray(), options); + return this; + }; + webp = null; + + /** + * @function jQuery#webpify + */ + jQuery.fn.webpify = function(options, webp_options) { + var that, webp_canary; + if (options == null) { + options = {}; + } + that = this; + webp_options = webp_options != null ? webp_options : options; + if (!webp) { + webp = jQuery.Deferred(); + webp_canary = new Image; + webp_canary.onerror = webp.reject; + webp_canary.onload = webp.resolve; + webp_canary.src = 'data:image/webp;base64,UklGRi4AAABXRUJQVlA4TCEAAAAvAUAAEB8wAiMwAgSSNtse/cXjxyCCmrYNWPwmHRH9jwMA'; + } + jQuery(function() { + return webp.done(function() { + return jQuery(that).cloudinary(jQuery.extend({}, webp_options, { + format: 'webp' + })); + }).fail(function() { + return jQuery(that).cloudinary(options); + }); + }); + return this; + }; + jQuery.fn.fetchify = function(options) { + return this.cloudinary(jQuery.extend(options, { + 'type': 'fetch' + })); + }; + jQuery.cloudinary = new CloudinaryJQuery(); + jQuery.cloudinary.fromDocument(); + + /** + * This module extends CloudinaryJquery to support jQuery File Upload + * Depends on 'jquery', 'util', 'cloudinaryjquery', 'jquery.ui.widget', 'jquery.iframe-transport','jquery.fileupload' + */ + + /** + * Delete a resource using the upload token + * @function CloudinaryJQuery#delete_by_token + * @param {string} delete_token - the delete token + * @param {Object} [options] + * @param {string} [options.url] - an alternative URL to use for the API + * @param {string} [options.cloud_name] - an alternative cloud_name to use. This parameter is ignored if `options.url` is provided. + */ + CloudinaryJQuery.prototype.delete_by_token = function(delete_token, options) { + var cloud_name, dataType, url; + options = options || {}; + url = options.url; + if (!url) { + cloud_name = options.cloud_name || jQuery.cloudinary.config().cloud_name; + url = 'https://api.cloudinary.com/v1_1/' + cloud_name + '/delete_by_token'; + } + dataType = jQuery.support.xhrFileUpload ? 'json' : 'iframe json'; + return jQuery.ajax({ + url: url, + method: 'POST', + data: { + token: delete_token + }, + headers: { + 'X-Requested-With': 'XMLHttpRequest' + }, + dataType: dataType + }); + }; + + /** + * Creates an `input` tag and sets it up to upload files to cloudinary + * @function CloudinaryJQuery#unsigned_upload_tag + * @param {string} + */ + CloudinaryJQuery.prototype.unsigned_upload_tag = function(upload_preset, upload_params, options) { + return jQuery('').attr({ + type: 'file', + name: 'file' + }).unsigned_cloudinary_upload(upload_preset, upload_params, options); + }; + + /** + * Initialize the jQuery File Upload plugin to upload to Cloudinary + * @function jQuery#cloudinary_fileupload + * @param {Object} options + * @returns {jQuery} + */ + jQuery.fn.cloudinary_fileupload = function(options) { + var cloud_name, initializing, resource_type, type, upload_url; + if (!Util.isFunction(jQuery.fn.fileupload)) { + return this; + } + initializing = !this.data('blueimpFileupload'); + if (initializing) { + options = jQuery.extend({ + maxFileSize: 20000000, + dataType: 'json', + headers: { + 'X-Requested-With': 'XMLHttpRequest' + } + }, options); + } + this.fileupload(options); + if (initializing) { + this.bind('fileuploaddone', function(e, data) { + var add_field, field, multiple, upload_info; + if (data.result.error) { + return; + } + data.result.path = ['v', data.result.version, '/', data.result.public_id, data.result.format ? '.' + data.result.format : ''].join(''); + if (data.cloudinaryField && data.form.length > 0) { + upload_info = [data.result.resource_type, data.result.type, data.result.path].join('/') + '#' + data.result.signature; + multiple = jQuery(e.target).prop('multiple'); + add_field = function() { + return jQuery('').attr({ + type: 'hidden', + name: data.cloudinaryField + }).val(upload_info).appendTo(data.form); + }; + if (multiple) { + add_field(); + } else { + field = jQuery(data.form).find('input[name="' + data.cloudinaryField + '"]'); + if (field.length > 0) { + field.val(upload_info); + } else { + add_field(); + } + } + } + return jQuery(e.target).trigger('cloudinarydone', data); + }); + this.bind('fileuploadsend', function(e, data) { + data.headers = jQuery.extend({}, data.headers, { + 'X-Unique-Upload-Id': (Math.random() * 10000000000).toString(16) + }); + return true; + }); + this.bind('fileuploadstart', function(e) { + return jQuery(e.target).trigger('cloudinarystart'); + }); + this.bind('fileuploadstop', function(e) { + return jQuery(e.target).trigger('cloudinarystop'); + }); + this.bind('fileuploadprogress', function(e, data) { + return jQuery(e.target).trigger('cloudinaryprogress', data); + }); + this.bind('fileuploadprogressall', function(e, data) { + return jQuery(e.target).trigger('cloudinaryprogressall', data); + }); + this.bind('fileuploadfail', function(e, data) { + return jQuery(e.target).trigger('cloudinaryfail', data); + }); + this.bind('fileuploadalways', function(e, data) { + return jQuery(e.target).trigger('cloudinaryalways', data); + }); + if (!this.fileupload('option').url) { + cloud_name = options.cloud_name || jQuery.cloudinary.config().cloud_name; + resource_type = options.resource_type || 'auto'; + type = options.type || 'upload'; + upload_url = 'https://api.cloudinary.com/v1_1/' + cloud_name + '/' + resource_type + '/' + type; + this.fileupload('option', 'url', upload_url); + } + } + return this; + }; + + /** + * Add a file to upload + * @function jQuery#cloudinary_upload_url + * @param {string} remote_url - the url to add + * @returns {jQuery} + */ + jQuery.fn.cloudinary_upload_url = function(remote_url) { + if (!Util.isFunction(jQuery.fn.fileupload)) { + return this; + } + this.fileupload('option', 'formData').file = remote_url; + this.fileupload('add', { + files: [remote_url] + }); + delete this.fileupload('option', 'formData').file; + return this; + }; + + /** + * Initialize the jQuery File Upload plugin to upload to Cloudinary using unsigned upload + * @function jQuery#unsigned_cloudinary_upload + * @param {string} upload_preset - the upload preset to use + * @param {Object} [upload_params] - parameters that should be past to the server + * @param {Object} [options] + * @returns {jQuery} + */ + jQuery.fn.unsigned_cloudinary_upload = function(upload_preset, upload_params, options) { + var attr, attrs_to_move, html_options, i, key, value; + if (upload_params == null) { + upload_params = {}; + } + if (options == null) { + options = {}; + } + upload_params = Util.cloneDeep(upload_params); + options = Util.cloneDeep(options); + attrs_to_move = ['cloud_name', 'resource_type', 'type']; + i = 0; + while (i < attrs_to_move.length) { + attr = attrs_to_move[i]; + if (upload_params[attr]) { + options[attr] = upload_params[attr]; + delete upload_params[attr]; + } + i++; + } + for (key in upload_params) { + value = upload_params[key]; + if (Util.isPlainObject(value)) { + upload_params[key] = jQuery.map(value, function(v, k) { + if (Util.isString(v)) { + v = v.replace(/[\|=]/g, "\\$&"); + } + return k + '=' + v; + }).join('|'); + } else if (Util.isArray(value)) { + if (value.length > 0 && jQuery.isArray(value[0])) { + upload_params[key] = jQuery.map(value, function(array_value) { + return array_value.join(','); + }).join('|'); + } else { + upload_params[key] = value.join(','); + } + } + } + if (!upload_params.callback) { + upload_params.callback = '/cloudinary_cors.html'; + } + upload_params.upload_preset = upload_preset; + options.formData = upload_params; + if (options.cloudinary_field) { + options.cloudinaryField = options.cloudinary_field; + delete options.cloudinary_field; + } + html_options = options.html || {}; + html_options["class"] = Util.trim("cloudinary_fileupload " + (html_options["class"] || '')); + if (options.multiple) { + html_options.multiple = true; + } + this.attr(html_options).cloudinary_fileupload(options); + return this; + }; + jQuery.cloudinary = new CloudinaryJQuery(); + cloudinary = { + utf8_encode: utf8_encode, + crc32: crc32, + Util: Util, + Condition: Condition, + Transformation: Transformation, + Configuration: Configuration, + HtmlTag: HtmlTag, + ImageTag: ImageTag, + VideoTag: VideoTag, + ClientHintsMetaTag: ClientHintsMetaTag, + Layer: Layer, + FetchLayer: FetchLayer, + TextLayer: TextLayer, + SubtitlesLayer: SubtitlesLayer, + Cloudinary: Cloudinary, + VERSION: "2.5.0", + CloudinaryJQuery: CloudinaryJQuery + }; + return cloudinary; +}); + + diff --git a/lib/cloudinary/static/js/jquery.fileupload-image.js b/lib/cloudinary/static/js/jquery.fileupload-image.js new file mode 100644 index 00000000..65fc6d7b --- /dev/null +++ b/lib/cloudinary/static/js/jquery.fileupload-image.js @@ -0,0 +1,326 @@ +/* + * jQuery File Upload Image Preview & Resize Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2013, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* jshint nomen:false */ +/* global define, require, window, Blob */ + +;(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + 'load-image', + 'load-image-meta', + 'load-image-scale', + 'load-image-exif', + 'canvas-to-blob', + './jquery.fileupload-process' + ], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory( + require('jquery'), + require('blueimp-load-image/js/load-image'), + require('blueimp-load-image/js/load-image-meta'), + require('blueimp-load-image/js/load-image-scale'), + require('blueimp-load-image/js/load-image-exif'), + require('blueimp-canvas-to-blob'), + require('./jquery.fileupload-process') + ); + } else { + // Browser globals: + factory( + window.jQuery, + window.loadImage + ); + } +}(function ($, loadImage) { + 'use strict'; + + // Prepend to the default processQueue: + $.blueimp.fileupload.prototype.options.processQueue.unshift( + { + action: 'loadImageMetaData', + disableImageHead: '@', + disableExif: '@', + disableExifThumbnail: '@', + disableExifSub: '@', + disableExifGps: '@', + disabled: '@disableImageMetaDataLoad' + }, + { + action: 'loadImage', + // Use the action as prefix for the "@" options: + prefix: true, + fileTypes: '@', + maxFileSize: '@', + noRevoke: '@', + disabled: '@disableImageLoad' + }, + { + action: 'resizeImage', + // Use "image" as prefix for the "@" options: + prefix: 'image', + maxWidth: '@', + maxHeight: '@', + minWidth: '@', + minHeight: '@', + crop: '@', + orientation: '@', + forceResize: '@', + disabled: '@disableImageResize' + }, + { + action: 'saveImage', + quality: '@imageQuality', + type: '@imageType', + disabled: '@disableImageResize' + }, + { + action: 'saveImageMetaData', + disabled: '@disableImageMetaDataSave' + }, + { + action: 'resizeImage', + // Use "preview" as prefix for the "@" options: + prefix: 'preview', + maxWidth: '@', + maxHeight: '@', + minWidth: '@', + minHeight: '@', + crop: '@', + orientation: '@', + thumbnail: '@', + canvas: '@', + disabled: '@disableImagePreview' + }, + { + action: 'setImage', + name: '@imagePreviewName', + disabled: '@disableImagePreview' + }, + { + action: 'deleteImageReferences', + disabled: '@disableImageReferencesDeletion' + } + ); + + // The File Upload Resize plugin extends the fileupload widget + // with image resize functionality: + $.widget('blueimp.fileupload', $.blueimp.fileupload, { + + options: { + // The regular expression for the types of images to load: + // matched against the file type: + loadImageFileTypes: /^image\/(gif|jpeg|png|svg\+xml)$/, + // The maximum file size of images to load: + loadImageMaxFileSize: 10000000, // 10MB + // The maximum width of resized images: + imageMaxWidth: 1920, + // The maximum height of resized images: + imageMaxHeight: 1080, + // Defines the image orientation (1-8) or takes the orientation + // value from Exif data if set to true: + imageOrientation: false, + // Define if resized images should be cropped or only scaled: + imageCrop: false, + // Disable the resize image functionality by default: + disableImageResize: true, + // The maximum width of the preview images: + previewMaxWidth: 80, + // The maximum height of the preview images: + previewMaxHeight: 80, + // Defines the preview orientation (1-8) or takes the orientation + // value from Exif data if set to true: + previewOrientation: true, + // Create the preview using the Exif data thumbnail: + previewThumbnail: true, + // Define if preview images should be cropped or only scaled: + previewCrop: false, + // Define if preview images should be resized as canvas elements: + previewCanvas: true + }, + + processActions: { + + // Loads the image given via data.files and data.index + // as img element, if the browser supports the File API. + // Accepts the options fileTypes (regular expression) + // and maxFileSize (integer) to limit the files to load: + loadImage: function (data, options) { + if (options.disabled) { + return data; + } + var that = this, + file = data.files[data.index], + dfd = $.Deferred(); + if (($.type(options.maxFileSize) === 'number' && + file.size > options.maxFileSize) || + (options.fileTypes && + !options.fileTypes.test(file.type)) || + !loadImage( + file, + function (img) { + if (img.src) { + data.img = img; + } + dfd.resolveWith(that, [data]); + }, + options + )) { + return data; + } + return dfd.promise(); + }, + + // Resizes the image given as data.canvas or data.img + // and updates data.canvas or data.img with the resized image. + // Also stores the resized image as preview property. + // Accepts the options maxWidth, maxHeight, minWidth, + // minHeight, canvas and crop: + resizeImage: function (data, options) { + if (options.disabled || !(data.canvas || data.img)) { + return data; + } + options = $.extend({canvas: true}, options); + var that = this, + dfd = $.Deferred(), + img = (options.canvas && data.canvas) || data.img, + resolve = function (newImg) { + if (newImg && (newImg.width !== img.width || + newImg.height !== img.height || + options.forceResize)) { + data[newImg.getContext ? 'canvas' : 'img'] = newImg; + } + data.preview = newImg; + dfd.resolveWith(that, [data]); + }, + thumbnail; + if (data.exif) { + if (options.orientation === true) { + options.orientation = data.exif.get('Orientation'); + } + if (options.thumbnail) { + thumbnail = data.exif.get('Thumbnail'); + if (thumbnail) { + loadImage(thumbnail, resolve, options); + return dfd.promise(); + } + } + // Prevent orienting the same image twice: + if (data.orientation) { + delete options.orientation; + } else { + data.orientation = options.orientation; + } + } + if (img) { + resolve(loadImage.scale(img, options)); + return dfd.promise(); + } + return data; + }, + + // Saves the processed image given as data.canvas + // inplace at data.index of data.files: + saveImage: function (data, options) { + if (!data.canvas || options.disabled) { + return data; + } + var that = this, + file = data.files[data.index], + dfd = $.Deferred(); + if (data.canvas.toBlob) { + data.canvas.toBlob( + function (blob) { + if (!blob.name) { + if (file.type === blob.type) { + blob.name = file.name; + } else if (file.name) { + blob.name = file.name.replace( + /\.\w+$/, + '.' + blob.type.substr(6) + ); + } + } + // Don't restore invalid meta data: + if (file.type !== blob.type) { + delete data.imageHead; + } + // Store the created blob at the position + // of the original file in the files list: + data.files[data.index] = blob; + dfd.resolveWith(that, [data]); + }, + options.type || file.type, + options.quality + ); + } else { + return data; + } + return dfd.promise(); + }, + + loadImageMetaData: function (data, options) { + if (options.disabled) { + return data; + } + var that = this, + dfd = $.Deferred(); + loadImage.parseMetaData(data.files[data.index], function (result) { + $.extend(data, result); + dfd.resolveWith(that, [data]); + }, options); + return dfd.promise(); + }, + + saveImageMetaData: function (data, options) { + if (!(data.imageHead && data.canvas && + data.canvas.toBlob && !options.disabled)) { + return data; + } + var file = data.files[data.index], + blob = new Blob([ + data.imageHead, + // Resized images always have a head size of 20 bytes, + // including the JPEG marker and a minimal JFIF header: + this._blobSlice.call(file, 20) + ], {type: file.type}); + blob.name = file.name; + data.files[data.index] = blob; + return data; + }, + + // Sets the resized version of the image as a property of the + // file object, must be called after "saveImage": + setImage: function (data, options) { + if (data.preview && !options.disabled) { + data.files[data.index][options.name || 'preview'] = data.preview; + } + return data; + }, + + deleteImageReferences: function (data, options) { + if (!options.disabled) { + delete data.img; + delete data.canvas; + delete data.preview; + delete data.imageHead; + } + return data; + } + + } + + }); + +})); diff --git a/lib/cloudinary/static/js/jquery.fileupload-process.js b/lib/cloudinary/static/js/jquery.fileupload-process.js new file mode 100644 index 00000000..638f0d26 --- /dev/null +++ b/lib/cloudinary/static/js/jquery.fileupload-process.js @@ -0,0 +1,178 @@ +/* + * jQuery File Upload Processing Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2012, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* jshint nomen:false */ +/* global define, require, window */ + +;(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + './jquery.fileupload' + ], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory( + require('jquery'), + require('./jquery.fileupload') + ); + } else { + // Browser globals: + factory( + window.jQuery + ); + } +}(function ($) { + 'use strict'; + + var originalAdd = $.blueimp.fileupload.prototype.options.add; + + // The File Upload Processing plugin extends the fileupload widget + // with file processing functionality: + $.widget('blueimp.fileupload', $.blueimp.fileupload, { + + options: { + // The list of processing actions: + processQueue: [ + /* + { + action: 'log', + type: 'debug' + } + */ + ], + add: function (e, data) { + var $this = $(this); + data.process(function () { + return $this.fileupload('process', data); + }); + originalAdd.call(this, e, data); + } + }, + + processActions: { + /* + log: function (data, options) { + console[options.type]( + 'Processing "' + data.files[data.index].name + '"' + ); + } + */ + }, + + _processFile: function (data, originalData) { + var that = this, + dfd = $.Deferred().resolveWith(that, [data]), + chain = dfd.promise(); + this._trigger('process', null, data); + $.each(data.processQueue, function (i, settings) { + var func = function (data) { + if (originalData.errorThrown) { + return $.Deferred() + .rejectWith(that, [originalData]).promise(); + } + return that.processActions[settings.action].call( + that, + data, + settings + ); + }; + chain = chain.then(func, settings.always && func); + }); + chain + .done(function () { + that._trigger('processdone', null, data); + that._trigger('processalways', null, data); + }) + .fail(function () { + that._trigger('processfail', null, data); + that._trigger('processalways', null, data); + }); + return chain; + }, + + // Replaces the settings of each processQueue item that + // are strings starting with an "@", using the remaining + // substring as key for the option map, + // e.g. "@autoUpload" is replaced with options.autoUpload: + _transformProcessQueue: function (options) { + var processQueue = []; + $.each(options.processQueue, function () { + var settings = {}, + action = this.action, + prefix = this.prefix === true ? action : this.prefix; + $.each(this, function (key, value) { + if ($.type(value) === 'string' && + value.charAt(0) === '@') { + settings[key] = options[ + value.slice(1) || (prefix ? prefix + + key.charAt(0).toUpperCase() + key.slice(1) : key) + ]; + } else { + settings[key] = value; + } + + }); + processQueue.push(settings); + }); + options.processQueue = processQueue; + }, + + // Returns the number of files currently in the processsing queue: + processing: function () { + return this._processing; + }, + + // Processes the files given as files property of the data parameter, + // returns a Promise object that allows to bind callbacks: + process: function (data) { + var that = this, + options = $.extend({}, this.options, data); + if (options.processQueue && options.processQueue.length) { + this._transformProcessQueue(options); + if (this._processing === 0) { + this._trigger('processstart'); + } + $.each(data.files, function (index) { + var opts = index ? $.extend({}, options) : options, + func = function () { + if (data.errorThrown) { + return $.Deferred() + .rejectWith(that, [data]).promise(); + } + return that._processFile(opts, data); + }; + opts.index = index; + that._processing += 1; + that._processingQueue = that._processingQueue.then(func, func) + .always(function () { + that._processing -= 1; + if (that._processing === 0) { + that._trigger('processstop'); + } + }); + }); + } + return this._processingQueue; + }, + + _create: function () { + this._super(); + this._processing = 0; + this._processingQueue = $.Deferred().resolveWith(this) + .promise(); + } + + }); + +})); diff --git a/lib/cloudinary/static/js/jquery.fileupload-validate.js b/lib/cloudinary/static/js/jquery.fileupload-validate.js new file mode 100644 index 00000000..eebeb373 --- /dev/null +++ b/lib/cloudinary/static/js/jquery.fileupload-validate.js @@ -0,0 +1,125 @@ +/* + * jQuery File Upload Validation Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2013, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* global define, require, window */ + +;(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + './jquery.fileupload-process' + ], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory( + require('jquery'), + require('./jquery.fileupload-process') + ); + } else { + // Browser globals: + factory( + window.jQuery + ); + } +}(function ($) { + 'use strict'; + + // Append to the default processQueue: + $.blueimp.fileupload.prototype.options.processQueue.push( + { + action: 'validate', + // Always trigger this action, + // even if the previous action was rejected: + always: true, + // Options taken from the global options map: + acceptFileTypes: '@', + maxFileSize: '@', + minFileSize: '@', + maxNumberOfFiles: '@', + disabled: '@disableValidation' + } + ); + + // The File Upload Validation plugin extends the fileupload widget + // with file validation functionality: + $.widget('blueimp.fileupload', $.blueimp.fileupload, { + + options: { + /* + // The regular expression for allowed file types, matches + // against either file type or file name: + acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, + // The maximum allowed file size in bytes: + maxFileSize: 10000000, // 10 MB + // The minimum allowed file size in bytes: + minFileSize: undefined, // No minimal file size + // The limit of files to be uploaded: + maxNumberOfFiles: 10, + */ + + // Function returning the current number of files, + // has to be overriden for maxNumberOfFiles validation: + getNumberOfFiles: $.noop, + + // Error and info messages: + messages: { + maxNumberOfFiles: 'Maximum number of files exceeded', + acceptFileTypes: 'File type not allowed', + maxFileSize: 'File is too large', + minFileSize: 'File is too small' + } + }, + + processActions: { + + validate: function (data, options) { + if (options.disabled) { + return data; + } + var dfd = $.Deferred(), + settings = this.options, + file = data.files[data.index], + fileSize; + if (options.minFileSize || options.maxFileSize) { + fileSize = file.size; + } + if ($.type(options.maxNumberOfFiles) === 'number' && + (settings.getNumberOfFiles() || 0) + data.files.length > + options.maxNumberOfFiles) { + file.error = settings.i18n('maxNumberOfFiles'); + } else if (options.acceptFileTypes && + !(options.acceptFileTypes.test(file.type) || + options.acceptFileTypes.test(file.name))) { + file.error = settings.i18n('acceptFileTypes'); + } else if (fileSize > options.maxFileSize) { + file.error = settings.i18n('maxFileSize'); + } else if ($.type(fileSize) === 'number' && + fileSize < options.minFileSize) { + file.error = settings.i18n('minFileSize'); + } else { + delete file.error; + } + if (file.error || data.files.error) { + data.files.error = true; + dfd.rejectWith(this, [data]); + } else { + dfd.resolveWith(this, [data]); + } + return dfd.promise(); + } + + } + + }); + +})); diff --git a/lib/cloudinary/static/js/jquery.fileupload.js b/lib/cloudinary/static/js/jquery.fileupload.js new file mode 100644 index 00000000..f20bc6d0 --- /dev/null +++ b/lib/cloudinary/static/js/jquery.fileupload.js @@ -0,0 +1,1482 @@ +/* + * jQuery File Upload Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* jshint nomen:false */ +/* global define, require, window, document, location, Blob, FormData */ + +;(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + 'jquery-ui/ui/widget' + ], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory( + require('jquery'), + require('./vendor/jquery.ui.widget') + ); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // Detect file input support, based on + // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ + $.support.fileInput = !(new RegExp( + // Handle devices which give false positives for the feature detection: + '(Android (1\\.[0156]|2\\.[01]))' + + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' + + '|(w(eb)?OSBrowser)|(webOS)' + + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' + ).test(window.navigator.userAgent) || + // Feature detection for all other devices: + $('').prop('disabled')); + + // The FileReader API is not actually used, but works as feature detection, + // as some Safari versions (5?) support XHR file uploads via the FormData API, + // but not non-multipart XHR file uploads. + // window.XMLHttpRequestUpload is not available on IE10, so we check for + // window.ProgressEvent instead to detect XHR2 file upload capability: + $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader); + $.support.xhrFormDataFileUpload = !!window.FormData; + + // Detect support for Blob slicing (required for chunked uploads): + $.support.blobSlice = window.Blob && (Blob.prototype.slice || + Blob.prototype.webkitSlice || Blob.prototype.mozSlice); + + // Helper function to create drag handlers for dragover/dragenter/dragleave: + function getDragHandler(type) { + var isDragOver = type === 'dragover'; + return function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var dataTransfer = e.dataTransfer; + if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 && + this._trigger( + type, + $.Event(type, {delegatedEvent: e}) + ) !== false) { + e.preventDefault(); + if (isDragOver) { + dataTransfer.dropEffect = 'copy'; + } + } + }; + } + + // The fileupload widget listens for change events on file input fields defined + // via fileInput setting and paste or drop events of the given dropZone. + // In addition to the default jQuery Widget methods, the fileupload widget + // exposes the "add" and "send" methods, to add or directly send files using + // the fileupload API. + // By default, files added via file input selection, paste, drag & drop or + // "add" method are uploaded immediately, but it is possible to override + // the "add" callback option to queue file uploads. + $.widget('blueimp.fileupload', { + + options: { + // The drop target element(s), by the default the complete document. + // Set to null to disable drag & drop support: + dropZone: $(document), + // The paste target element(s), by the default undefined. + // Set to a DOM node or jQuery object to enable file pasting: + pasteZone: undefined, + // The file input field(s), that are listened to for change events. + // If undefined, it is set to the file input fields inside + // of the widget element on plugin initialization. + // Set to null to disable the change listener. + fileInput: undefined, + // By default, the file input field is replaced with a clone after + // each input field change event. This is required for iframe transport + // queues and allows change events to be fired for the same file + // selection, but can be disabled by setting the following option to false: + replaceFileInput: true, + // The parameter name for the file form data (the request argument name). + // If undefined or empty, the name property of the file input field is + // used, or "files[]" if the file input name property is also empty, + // can be a string or an array of strings: + paramName: undefined, + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads: true, + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads: undefined, + // The following option limits the number of files uploaded with one + // XHR request to keep the request size under or equal to the defined + // limit in bytes: + limitMultiFileUploadSize: undefined, + // Multipart file uploads add a number of bytes to each uploaded file, + // therefore the following option adds an overhead for each file used + // in the limitMultiFileUploadSize configuration: + limitMultiFileUploadSizeOverhead: 512, + // Set the following option to true to issue all file upload requests + // in a sequential order: + sequentialUploads: false, + // To limit the number of concurrent uploads, + // set the following option to an integer greater than 0: + limitConcurrentUploads: undefined, + // Set the following option to true to force iframe transport uploads: + forceIframeTransport: false, + // Set the following option to the location of a redirect url on the + // origin server, for cross-domain iframe transport uploads: + redirect: undefined, + // The parameter name for the redirect url, sent as part of the form + // data and set to 'redirect' if this option is empty: + redirectParamName: undefined, + // Set the following option to the location of a postMessage window, + // to enable postMessage transport uploads: + postMessage: undefined, + // By default, XHR file uploads are sent as multipart/form-data. + // The iframe transport is always using multipart/form-data. + // Set to false to enable non-multipart XHR uploads: + multipart: true, + // To upload large files in smaller chunks, set the following option + // to a preferred maximum chunk size. If set to 0, null or undefined, + // or the browser does not support the required Blob API, files will + // be uploaded as a whole. + maxChunkSize: undefined, + // When a non-multipart upload or a chunked multipart upload has been + // aborted, this option can be used to resume the upload by setting + // it to the size of the already uploaded bytes. This option is most + // useful when modifying the options object inside of the "add" or + // "send" callbacks, as the options are cloned for each file upload. + uploadedBytes: undefined, + // By default, failed (abort or error) file uploads are removed from the + // global progress calculation. Set the following option to false to + // prevent recalculating the global progress data: + recalculateProgress: true, + // Interval in milliseconds to calculate and trigger progress events: + progressInterval: 100, + // Interval in milliseconds to calculate progress bitrate: + bitrateInterval: 500, + // By default, uploads are started automatically when adding files: + autoUpload: true, + + // Error and info messages: + messages: { + uploadedBytes: 'Uploaded bytes exceed file size' + }, + + // Translation function, gets the message key to be translated + // and an object with context specific data as arguments: + i18n: function (message, context) { + message = this.messages[message] || message.toString(); + if (context) { + $.each(context, function (key, value) { + message = message.replace('{' + key + '}', value); + }); + } + return message; + }, + + // Additional form data to be sent along with the file uploads can be set + // using this option, which accepts an array of objects with name and + // value properties, a function returning such an array, a FormData + // object (for XHR file uploads), or a simple object. + // The form of the first fileInput is given as parameter to the function: + formData: function (form) { + return form.serializeArray(); + }, + + // The add callback is invoked as soon as files are added to the fileupload + // widget (via file input selection, drag & drop, paste or add API call). + // If the singleFileUploads option is enabled, this callback will be + // called once for each file in the selection for XHR file uploads, else + // once for each file selection. + // + // The upload starts when the submit method is invoked on the data parameter. + // The data object contains a files property holding the added files + // and allows you to override plugin options as well as define ajax settings. + // + // Listeners for this callback can also be bound the following way: + // .bind('fileuploadadd', func); + // + // data.submit() returns a Promise object and allows to attach additional + // handlers using jQuery's Deferred callbacks: + // data.submit().done(func).fail(func).always(func); + add: function (e, data) { + if (e.isDefaultPrevented()) { + return false; + } + if (data.autoUpload || (data.autoUpload !== false && + $(this).fileupload('option', 'autoUpload'))) { + data.process().done(function () { + data.submit(); + }); + } + }, + + // Other callbacks: + + // Callback for the submit event of each file upload: + // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); + + // Callback for the start of each file upload request: + // send: function (e, data) {}, // .bind('fileuploadsend', func); + + // Callback for successful uploads: + // done: function (e, data) {}, // .bind('fileuploaddone', func); + + // Callback for failed (abort or error) uploads: + // fail: function (e, data) {}, // .bind('fileuploadfail', func); + + // Callback for completed (success, abort or error) requests: + // always: function (e, data) {}, // .bind('fileuploadalways', func); + + // Callback for upload progress events: + // progress: function (e, data) {}, // .bind('fileuploadprogress', func); + + // Callback for global upload progress events: + // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); + + // Callback for uploads start, equivalent to the global ajaxStart event: + // start: function (e) {}, // .bind('fileuploadstart', func); + + // Callback for uploads stop, equivalent to the global ajaxStop event: + // stop: function (e) {}, // .bind('fileuploadstop', func); + + // Callback for change events of the fileInput(s): + // change: function (e, data) {}, // .bind('fileuploadchange', func); + + // Callback for paste events to the pasteZone(s): + // paste: function (e, data) {}, // .bind('fileuploadpaste', func); + + // Callback for drop events of the dropZone(s): + // drop: function (e, data) {}, // .bind('fileuploaddrop', func); + + // Callback for dragover events of the dropZone(s): + // dragover: function (e) {}, // .bind('fileuploaddragover', func); + + // Callback for the start of each chunk upload request: + // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); + + // Callback for successful chunk uploads: + // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); + + // Callback for failed (abort or error) chunk uploads: + // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); + + // Callback for completed (success, abort or error) chunk upload requests: + // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); + + // The plugin options are used as settings object for the ajax calls. + // The following are jQuery ajax settings required for the file uploads: + processData: false, + contentType: false, + cache: false, + timeout: 0 + }, + + // A list of options that require reinitializing event listeners and/or + // special initialization code: + _specialOptions: [ + 'fileInput', + 'dropZone', + 'pasteZone', + 'multipart', + 'forceIframeTransport' + ], + + _blobSlice: $.support.blobSlice && function () { + var slice = this.slice || this.webkitSlice || this.mozSlice; + return slice.apply(this, arguments); + }, + + _BitrateTimer: function () { + this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); + this.loaded = 0; + this.bitrate = 0; + this.getBitrate = function (now, loaded, interval) { + var timeDiff = now - this.timestamp; + if (!this.bitrate || !interval || timeDiff > interval) { + this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; + this.loaded = loaded; + this.timestamp = now; + } + return this.bitrate; + }; + }, + + _isXHRUpload: function (options) { + return !options.forceIframeTransport && + ((!options.multipart && $.support.xhrFileUpload) || + $.support.xhrFormDataFileUpload); + }, + + _getFormData: function (options) { + var formData; + if ($.type(options.formData) === 'function') { + return options.formData(options.form); + } + if ($.isArray(options.formData)) { + return options.formData; + } + if ($.type(options.formData) === 'object') { + formData = []; + $.each(options.formData, function (name, value) { + formData.push({name: name, value: value}); + }); + return formData; + } + return []; + }, + + _getTotal: function (files) { + var total = 0; + $.each(files, function (index, file) { + total += file.size || 1; + }); + return total; + }, + + _initProgressObject: function (obj) { + var progress = { + loaded: 0, + total: 0, + bitrate: 0 + }; + if (obj._progress) { + $.extend(obj._progress, progress); + } else { + obj._progress = progress; + } + }, + + _initResponseObject: function (obj) { + var prop; + if (obj._response) { + for (prop in obj._response) { + if (obj._response.hasOwnProperty(prop)) { + delete obj._response[prop]; + } + } + } else { + obj._response = {}; + } + }, + + _onProgress: function (e, data) { + if (e.lengthComputable) { + var now = ((Date.now) ? Date.now() : (new Date()).getTime()), + loaded; + if (data._time && data.progressInterval && + (now - data._time < data.progressInterval) && + e.loaded !== e.total) { + return; + } + data._time = now; + loaded = Math.floor( + e.loaded / e.total * (data.chunkSize || data._progress.total) + ) + (data.uploadedBytes || 0); + // Add the difference from the previously loaded state + // to the global loaded counter: + this._progress.loaded += (loaded - data._progress.loaded); + this._progress.bitrate = this._bitrateTimer.getBitrate( + now, + this._progress.loaded, + data.bitrateInterval + ); + data._progress.loaded = data.loaded = loaded; + data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( + now, + loaded, + data.bitrateInterval + ); + // Trigger a custom progress event with a total data property set + // to the file size(s) of the current upload and a loaded data + // property calculated accordingly: + this._trigger( + 'progress', + $.Event('progress', {delegatedEvent: e}), + data + ); + // Trigger a global progress event for all current file uploads, + // including ajax calls queued for sequential file uploads: + this._trigger( + 'progressall', + $.Event('progressall', {delegatedEvent: e}), + this._progress + ); + } + }, + + _initProgressListener: function (options) { + var that = this, + xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); + // Accesss to the native XHR object is required to add event listeners + // for the upload progress event: + if (xhr.upload) { + $(xhr.upload).bind('progress', function (e) { + var oe = e.originalEvent; + // Make sure the progress event properties get copied over: + e.lengthComputable = oe.lengthComputable; + e.loaded = oe.loaded; + e.total = oe.total; + that._onProgress(e, options); + }); + options.xhr = function () { + return xhr; + }; + } + }, + + _isInstanceOf: function (type, obj) { + // Cross-frame instanceof check + return Object.prototype.toString.call(obj) === '[object ' + type + ']'; + }, + + _initXHRData: function (options) { + var that = this, + formData, + file = options.files[0], + // Ignore non-multipart setting if not supported: + multipart = options.multipart || !$.support.xhrFileUpload, + paramName = $.type(options.paramName) === 'array' ? + options.paramName[0] : options.paramName; + options.headers = $.extend({}, options.headers); + if (options.contentRange) { + options.headers['Content-Range'] = options.contentRange; + } + if (!multipart || options.blob || !this._isInstanceOf('File', file)) { + options.headers['Content-Disposition'] = 'attachment; filename="' + + encodeURI(file.name) + '"'; + } + if (!multipart) { + options.contentType = file.type || 'application/octet-stream'; + options.data = options.blob || file; + } else if ($.support.xhrFormDataFileUpload) { + if (options.postMessage) { + // window.postMessage does not allow sending FormData + // objects, so we just add the File/Blob objects to + // the formData array and let the postMessage window + // create the FormData object out of this array: + formData = this._getFormData(options); + if (options.blob) { + formData.push({ + name: paramName, + value: options.blob + }); + } else { + $.each(options.files, function (index, file) { + formData.push({ + name: ($.type(options.paramName) === 'array' && + options.paramName[index]) || paramName, + value: file + }); + }); + } + } else { + if (that._isInstanceOf('FormData', options.formData)) { + formData = options.formData; + } else { + formData = new FormData(); + $.each(this._getFormData(options), function (index, field) { + formData.append(field.name, field.value); + }); + } + if (options.blob) { + formData.append(paramName, options.blob, file.name); + } else { + $.each(options.files, function (index, file) { + // This check allows the tests to run with + // dummy objects: + if (that._isInstanceOf('File', file) || + that._isInstanceOf('Blob', file)) { + formData.append( + ($.type(options.paramName) === 'array' && + options.paramName[index]) || paramName, + file, + file.uploadName || file.name + ); + } + }); + } + } + options.data = formData; + } + // Blob reference is not needed anymore, free memory: + options.blob = null; + }, + + _initIframeSettings: function (options) { + var targetHost = $('').prop('href', options.url).prop('host'); + // Setting the dataType to iframe enables the iframe transport: + options.dataType = 'iframe ' + (options.dataType || ''); + // The iframe transport accepts a serialized array as form data: + options.formData = this._getFormData(options); + // Add redirect url to form data on cross-domain uploads: + if (options.redirect && targetHost && targetHost !== location.host) { + options.formData.push({ + name: options.redirectParamName || 'redirect', + value: options.redirect + }); + } + }, + + _initDataSettings: function (options) { + if (this._isXHRUpload(options)) { + if (!this._chunkedUpload(options, true)) { + if (!options.data) { + this._initXHRData(options); + } + this._initProgressListener(options); + } + if (options.postMessage) { + // Setting the dataType to postmessage enables the + // postMessage transport: + options.dataType = 'postmessage ' + (options.dataType || ''); + } + } else { + this._initIframeSettings(options); + } + }, + + _getParamName: function (options) { + var fileInput = $(options.fileInput), + paramName = options.paramName; + if (!paramName) { + paramName = []; + fileInput.each(function () { + var input = $(this), + name = input.prop('name') || 'files[]', + i = (input.prop('files') || [1]).length; + while (i) { + paramName.push(name); + i -= 1; + } + }); + if (!paramName.length) { + paramName = [fileInput.prop('name') || 'files[]']; + } + } else if (!$.isArray(paramName)) { + paramName = [paramName]; + } + return paramName; + }, + + _initFormSettings: function (options) { + // Retrieve missing options from the input field and the + // associated form, if available: + if (!options.form || !options.form.length) { + options.form = $(options.fileInput.prop('form')); + // If the given file input doesn't have an associated form, + // use the default widget file input's form: + if (!options.form.length) { + options.form = $(this.options.fileInput.prop('form')); + } + } + options.paramName = this._getParamName(options); + if (!options.url) { + options.url = options.form.prop('action') || location.href; + } + // The HTTP request method must be "POST" or "PUT": + options.type = (options.type || + ($.type(options.form.prop('method')) === 'string' && + options.form.prop('method')) || '' + ).toUpperCase(); + if (options.type !== 'POST' && options.type !== 'PUT' && + options.type !== 'PATCH') { + options.type = 'POST'; + } + if (!options.formAcceptCharset) { + options.formAcceptCharset = options.form.attr('accept-charset'); + } + }, + + _getAJAXSettings: function (data) { + var options = $.extend({}, this.options, data); + this._initFormSettings(options); + this._initDataSettings(options); + return options; + }, + + // jQuery 1.6 doesn't provide .state(), + // while jQuery 1.8+ removed .isRejected() and .isResolved(): + _getDeferredState: function (deferred) { + if (deferred.state) { + return deferred.state(); + } + if (deferred.isResolved()) { + return 'resolved'; + } + if (deferred.isRejected()) { + return 'rejected'; + } + return 'pending'; + }, + + // Maps jqXHR callbacks to the equivalent + // methods of the given Promise object: + _enhancePromise: function (promise) { + promise.success = promise.done; + promise.error = promise.fail; + promise.complete = promise.always; + return promise; + }, + + // Creates and returns a Promise object enhanced with + // the jqXHR methods abort, success, error and complete: + _getXHRPromise: function (resolveOrReject, context, args) { + var dfd = $.Deferred(), + promise = dfd.promise(); + context = context || this.options.context || promise; + if (resolveOrReject === true) { + dfd.resolveWith(context, args); + } else if (resolveOrReject === false) { + dfd.rejectWith(context, args); + } + promise.abort = dfd.promise; + return this._enhancePromise(promise); + }, + + // Adds convenience methods to the data callback argument: + _addConvenienceMethods: function (e, data) { + var that = this, + getPromise = function (args) { + return $.Deferred().resolveWith(that, args).promise(); + }; + data.process = function (resolveFunc, rejectFunc) { + if (resolveFunc || rejectFunc) { + data._processQueue = this._processQueue = + (this._processQueue || getPromise([this])).then( + function () { + if (data.errorThrown) { + return $.Deferred() + .rejectWith(that, [data]).promise(); + } + return getPromise(arguments); + } + ).then(resolveFunc, rejectFunc); + } + return this._processQueue || getPromise([this]); + }; + data.submit = function () { + if (this.state() !== 'pending') { + data.jqXHR = this.jqXHR = + (that._trigger( + 'submit', + $.Event('submit', {delegatedEvent: e}), + this + ) !== false) && that._onSend(e, this); + } + return this.jqXHR || that._getXHRPromise(); + }; + data.abort = function () { + if (this.jqXHR) { + return this.jqXHR.abort(); + } + this.errorThrown = 'abort'; + that._trigger('fail', null, this); + return that._getXHRPromise(false); + }; + data.state = function () { + if (this.jqXHR) { + return that._getDeferredState(this.jqXHR); + } + if (this._processQueue) { + return that._getDeferredState(this._processQueue); + } + }; + data.processing = function () { + return !this.jqXHR && this._processQueue && that + ._getDeferredState(this._processQueue) === 'pending'; + }; + data.progress = function () { + return this._progress; + }; + data.response = function () { + return this._response; + }; + }, + + // Parses the Range header from the server response + // and returns the uploaded bytes: + _getUploadedBytes: function (jqXHR) { + var range = jqXHR.getResponseHeader('Range'), + parts = range && range.split('-'), + upperBytesPos = parts && parts.length > 1 && + parseInt(parts[1], 10); + return upperBytesPos && upperBytesPos + 1; + }, + + // Uploads a file in multiple, sequential requests + // by splitting the file up in multiple blob chunks. + // If the second parameter is true, only tests if the file + // should be uploaded in chunks, but does not invoke any + // upload requests: + _chunkedUpload: function (options, testOnly) { + options.uploadedBytes = options.uploadedBytes || 0; + var that = this, + file = options.files[0], + fs = file.size, + ub = options.uploadedBytes, + mcs = options.maxChunkSize || fs, + slice = this._blobSlice, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + upload; + if (!(this._isXHRUpload(options) && slice && (ub || ($.type(mcs) === 'function' ? mcs(options) : mcs) < fs)) || + options.data) { + return false; + } + if (testOnly) { + return true; + } + if (ub >= fs) { + file.error = options.i18n('uploadedBytes'); + return this._getXHRPromise( + false, + options.context, + [null, 'error', file.error] + ); + } + // The chunk upload method: + upload = function () { + // Clone the options object for each chunk upload: + var o = $.extend({}, options), + currentLoaded = o._progress.loaded; + o.blob = slice.call( + file, + ub, + ub + ($.type(mcs) === 'function' ? mcs(o) : mcs), + file.type + ); + // Store the current chunk size, as the blob itself + // will be dereferenced after data processing: + o.chunkSize = o.blob.size; + // Expose the chunk bytes position range: + o.contentRange = 'bytes ' + ub + '-' + + (ub + o.chunkSize - 1) + '/' + fs; + // Process the upload data (the blob and potential form data): + that._initXHRData(o); + // Add progress listeners for this chunk upload: + that._initProgressListener(o); + jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || + that._getXHRPromise(false, o.context)) + .done(function (result, textStatus, jqXHR) { + ub = that._getUploadedBytes(jqXHR) || + (ub + o.chunkSize); + // Create a progress event if no final progress event + // with loaded equaling total has been triggered + // for this chunk: + if (currentLoaded + o.chunkSize - o._progress.loaded) { + that._onProgress($.Event('progress', { + lengthComputable: true, + loaded: ub - o.uploadedBytes, + total: ub - o.uploadedBytes + }), o); + } + options.uploadedBytes = o.uploadedBytes = ub; + o.result = result; + o.textStatus = textStatus; + o.jqXHR = jqXHR; + that._trigger('chunkdone', null, o); + that._trigger('chunkalways', null, o); + if (ub < fs) { + // File upload not yet complete, + // continue with the next chunk: + upload(); + } else { + dfd.resolveWith( + o.context, + [result, textStatus, jqXHR] + ); + } + }) + .fail(function (jqXHR, textStatus, errorThrown) { + o.jqXHR = jqXHR; + o.textStatus = textStatus; + o.errorThrown = errorThrown; + that._trigger('chunkfail', null, o); + that._trigger('chunkalways', null, o); + dfd.rejectWith( + o.context, + [jqXHR, textStatus, errorThrown] + ); + }); + }; + this._enhancePromise(promise); + promise.abort = function () { + return jqXHR.abort(); + }; + upload(); + return promise; + }, + + _beforeSend: function (e, data) { + if (this._active === 0) { + // the start callback is triggered when an upload starts + // and no other uploads are currently running, + // equivalent to the global ajaxStart event: + this._trigger('start'); + // Set timer for global bitrate progress calculation: + this._bitrateTimer = new this._BitrateTimer(); + // Reset the global progress values: + this._progress.loaded = this._progress.total = 0; + this._progress.bitrate = 0; + } + // Make sure the container objects for the .response() and + // .progress() methods on the data object are available + // and reset to their initial state: + this._initResponseObject(data); + this._initProgressObject(data); + data._progress.loaded = data.loaded = data.uploadedBytes || 0; + data._progress.total = data.total = this._getTotal(data.files) || 1; + data._progress.bitrate = data.bitrate = 0; + this._active += 1; + // Initialize the global progress values: + this._progress.loaded += data.loaded; + this._progress.total += data.total; + }, + + _onDone: function (result, textStatus, jqXHR, options) { + var total = options._progress.total, + response = options._response; + if (options._progress.loaded < total) { + // Create a progress event if no final progress event + // with loaded equaling total has been triggered: + this._onProgress($.Event('progress', { + lengthComputable: true, + loaded: total, + total: total + }), options); + } + response.result = options.result = result; + response.textStatus = options.textStatus = textStatus; + response.jqXHR = options.jqXHR = jqXHR; + this._trigger('done', null, options); + }, + + _onFail: function (jqXHR, textStatus, errorThrown, options) { + var response = options._response; + if (options.recalculateProgress) { + // Remove the failed (error or abort) file upload from + // the global progress calculation: + this._progress.loaded -= options._progress.loaded; + this._progress.total -= options._progress.total; + } + response.jqXHR = options.jqXHR = jqXHR; + response.textStatus = options.textStatus = textStatus; + response.errorThrown = options.errorThrown = errorThrown; + this._trigger('fail', null, options); + }, + + _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { + // jqXHRorResult, textStatus and jqXHRorError are added to the + // options object via done and fail callbacks + this._trigger('always', null, options); + }, + + _onSend: function (e, data) { + if (!data.submit) { + this._addConvenienceMethods(e, data); + } + var that = this, + jqXHR, + aborted, + slot, + pipe, + options = that._getAJAXSettings(data), + send = function () { + that._sending += 1; + // Set timer for bitrate progress calculation: + options._bitrateTimer = new that._BitrateTimer(); + jqXHR = jqXHR || ( + ((aborted || that._trigger( + 'send', + $.Event('send', {delegatedEvent: e}), + options + ) === false) && + that._getXHRPromise(false, options.context, aborted)) || + that._chunkedUpload(options) || $.ajax(options) + ).done(function (result, textStatus, jqXHR) { + that._onDone(result, textStatus, jqXHR, options); + }).fail(function (jqXHR, textStatus, errorThrown) { + that._onFail(jqXHR, textStatus, errorThrown, options); + }).always(function (jqXHRorResult, textStatus, jqXHRorError) { + that._onAlways( + jqXHRorResult, + textStatus, + jqXHRorError, + options + ); + that._sending -= 1; + that._active -= 1; + if (options.limitConcurrentUploads && + options.limitConcurrentUploads > that._sending) { + // Start the next queued upload, + // that has not been aborted: + var nextSlot = that._slots.shift(); + while (nextSlot) { + if (that._getDeferredState(nextSlot) === 'pending') { + nextSlot.resolve(); + break; + } + nextSlot = that._slots.shift(); + } + } + if (that._active === 0) { + // The stop callback is triggered when all uploads have + // been completed, equivalent to the global ajaxStop event: + that._trigger('stop'); + } + }); + return jqXHR; + }; + this._beforeSend(e, options); + if (this.options.sequentialUploads || + (this.options.limitConcurrentUploads && + this.options.limitConcurrentUploads <= this._sending)) { + if (this.options.limitConcurrentUploads > 1) { + slot = $.Deferred(); + this._slots.push(slot); + pipe = slot.then(send); + } else { + this._sequence = this._sequence.then(send, send); + pipe = this._sequence; + } + // Return the piped Promise object, enhanced with an abort method, + // which is delegated to the jqXHR object of the current upload, + // and jqXHR callbacks mapped to the equivalent Promise methods: + pipe.abort = function () { + aborted = [undefined, 'abort', 'abort']; + if (!jqXHR) { + if (slot) { + slot.rejectWith(options.context, aborted); + } + return send(); + } + return jqXHR.abort(); + }; + return this._enhancePromise(pipe); + } + return send(); + }, + + _onAdd: function (e, data) { + var that = this, + result = true, + options = $.extend({}, this.options, data), + files = data.files, + filesLength = files.length, + limit = options.limitMultiFileUploads, + limitSize = options.limitMultiFileUploadSize, + overhead = options.limitMultiFileUploadSizeOverhead, + batchSize = 0, + paramName = this._getParamName(options), + paramNameSet, + paramNameSlice, + fileSet, + i, + j = 0; + if (!filesLength) { + return false; + } + if (limitSize && files[0].size === undefined) { + limitSize = undefined; + } + if (!(options.singleFileUploads || limit || limitSize) || + !this._isXHRUpload(options)) { + fileSet = [files]; + paramNameSet = [paramName]; + } else if (!(options.singleFileUploads || limitSize) && limit) { + fileSet = []; + paramNameSet = []; + for (i = 0; i < filesLength; i += limit) { + fileSet.push(files.slice(i, i + limit)); + paramNameSlice = paramName.slice(i, i + limit); + if (!paramNameSlice.length) { + paramNameSlice = paramName; + } + paramNameSet.push(paramNameSlice); + } + } else if (!options.singleFileUploads && limitSize) { + fileSet = []; + paramNameSet = []; + for (i = 0; i < filesLength; i = i + 1) { + batchSize += files[i].size + overhead; + if (i + 1 === filesLength || + ((batchSize + files[i + 1].size + overhead) > limitSize) || + (limit && i + 1 - j >= limit)) { + fileSet.push(files.slice(j, i + 1)); + paramNameSlice = paramName.slice(j, i + 1); + if (!paramNameSlice.length) { + paramNameSlice = paramName; + } + paramNameSet.push(paramNameSlice); + j = i + 1; + batchSize = 0; + } + } + } else { + paramNameSet = paramName; + } + data.originalFiles = files; + $.each(fileSet || files, function (index, element) { + var newData = $.extend({}, data); + newData.files = fileSet ? element : [element]; + newData.paramName = paramNameSet[index]; + that._initResponseObject(newData); + that._initProgressObject(newData); + that._addConvenienceMethods(e, newData); + result = that._trigger( + 'add', + $.Event('add', {delegatedEvent: e}), + newData + ); + return result; + }); + return result; + }, + + _replaceFileInput: function (data) { + var input = data.fileInput, + inputClone = input.clone(true), + restoreFocus = input.is(document.activeElement); + // Add a reference for the new cloned file input to the data argument: + data.fileInputClone = inputClone; + $('
').append(inputClone)[0].reset(); + // Detaching allows to insert the fileInput on another form + // without loosing the file input value: + input.after(inputClone).detach(); + // If the fileInput had focus before it was detached, + // restore focus to the inputClone. + if (restoreFocus) { + inputClone.focus(); + } + // Avoid memory leaks with the detached file input: + $.cleanData(input.unbind('remove')); + // Replace the original file input element in the fileInput + // elements set with the clone, which has been copied including + // event handlers: + this.options.fileInput = this.options.fileInput.map(function (i, el) { + if (el === input[0]) { + return inputClone[0]; + } + return el; + }); + // If the widget has been initialized on the file input itself, + // override this.element with the file input clone: + if (input[0] === this.element[0]) { + this.element = inputClone; + } + }, + + _handleFileTreeEntry: function (entry, path) { + var that = this, + dfd = $.Deferred(), + entries = [], + dirReader, + errorHandler = function (e) { + if (e && !e.entry) { + e.entry = entry; + } + // Since $.when returns immediately if one + // Deferred is rejected, we use resolve instead. + // This allows valid files and invalid items + // to be returned together in one set: + dfd.resolve([e]); + }, + successHandler = function (entries) { + that._handleFileTreeEntries( + entries, + path + entry.name + '/' + ).done(function (files) { + dfd.resolve(files); + }).fail(errorHandler); + }, + readEntries = function () { + dirReader.readEntries(function (results) { + if (!results.length) { + successHandler(entries); + } else { + entries = entries.concat(results); + readEntries(); + } + }, errorHandler); + }; + path = path || ''; + if (entry.isFile) { + if (entry._file) { + // Workaround for Chrome bug #149735 + entry._file.relativePath = path; + dfd.resolve(entry._file); + } else { + entry.file(function (file) { + file.relativePath = path; + dfd.resolve(file); + }, errorHandler); + } + } else if (entry.isDirectory) { + dirReader = entry.createReader(); + readEntries(); + } else { + // Return an empy list for file system items + // other than files or directories: + dfd.resolve([]); + } + return dfd.promise(); + }, + + _handleFileTreeEntries: function (entries, path) { + var that = this; + return $.when.apply( + $, + $.map(entries, function (entry) { + return that._handleFileTreeEntry(entry, path); + }) + ).then(function () { + return Array.prototype.concat.apply( + [], + arguments + ); + }); + }, + + _getDroppedFiles: function (dataTransfer) { + dataTransfer = dataTransfer || {}; + var items = dataTransfer.items; + if (items && items.length && (items[0].webkitGetAsEntry || + items[0].getAsEntry)) { + return this._handleFileTreeEntries( + $.map(items, function (item) { + var entry; + if (item.webkitGetAsEntry) { + entry = item.webkitGetAsEntry(); + if (entry) { + // Workaround for Chrome bug #149735: + entry._file = item.getAsFile(); + } + return entry; + } + return item.getAsEntry(); + }) + ); + } + return $.Deferred().resolve( + $.makeArray(dataTransfer.files) + ).promise(); + }, + + _getSingleFileInputFiles: function (fileInput) { + fileInput = $(fileInput); + var entries = fileInput.prop('webkitEntries') || + fileInput.prop('entries'), + files, + value; + if (entries && entries.length) { + return this._handleFileTreeEntries(entries); + } + files = $.makeArray(fileInput.prop('files')); + if (!files.length) { + value = fileInput.prop('value'); + if (!value) { + return $.Deferred().resolve([]).promise(); + } + // If the files property is not available, the browser does not + // support the File API and we add a pseudo File object with + // the input value as name with path information removed: + files = [{name: value.replace(/^.*\\/, '')}]; + } else if (files[0].name === undefined && files[0].fileName) { + // File normalization for Safari 4 and Firefox 3: + $.each(files, function (index, file) { + file.name = file.fileName; + file.size = file.fileSize; + }); + } + return $.Deferred().resolve(files).promise(); + }, + + _getFileInputFiles: function (fileInput) { + if (!(fileInput instanceof $) || fileInput.length === 1) { + return this._getSingleFileInputFiles(fileInput); + } + return $.when.apply( + $, + $.map(fileInput, this._getSingleFileInputFiles) + ).then(function () { + return Array.prototype.concat.apply( + [], + arguments + ); + }); + }, + + _onChange: function (e) { + var that = this, + data = { + fileInput: $(e.target), + form: $(e.target.form) + }; + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + if (that.options.replaceFileInput) { + that._replaceFileInput(data); + } + if (that._trigger( + 'change', + $.Event('change', {delegatedEvent: e}), + data + ) !== false) { + that._onAdd(e, data); + } + }); + }, + + _onPaste: function (e) { + var items = e.originalEvent && e.originalEvent.clipboardData && + e.originalEvent.clipboardData.items, + data = {files: []}; + if (items && items.length) { + $.each(items, function (index, item) { + var file = item.getAsFile && item.getAsFile(); + if (file) { + data.files.push(file); + } + }); + if (this._trigger( + 'paste', + $.Event('paste', {delegatedEvent: e}), + data + ) !== false) { + this._onAdd(e, data); + } + } + }, + + _onDrop: function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var that = this, + dataTransfer = e.dataTransfer, + data = {}; + if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { + e.preventDefault(); + this._getDroppedFiles(dataTransfer).always(function (files) { + data.files = files; + if (that._trigger( + 'drop', + $.Event('drop', {delegatedEvent: e}), + data + ) !== false) { + that._onAdd(e, data); + } + }); + } + }, + + _onDragOver: getDragHandler('dragover'), + + _onDragEnter: getDragHandler('dragenter'), + + _onDragLeave: getDragHandler('dragleave'), + + _initEventHandlers: function () { + if (this._isXHRUpload(this.options)) { + this._on(this.options.dropZone, { + dragover: this._onDragOver, + drop: this._onDrop, + // event.preventDefault() on dragenter is required for IE10+: + dragenter: this._onDragEnter, + // dragleave is not required, but added for completeness: + dragleave: this._onDragLeave + }); + this._on(this.options.pasteZone, { + paste: this._onPaste + }); + } + if ($.support.fileInput) { + this._on(this.options.fileInput, { + change: this._onChange + }); + } + }, + + _destroyEventHandlers: function () { + this._off(this.options.dropZone, 'dragenter dragleave dragover drop'); + this._off(this.options.pasteZone, 'paste'); + this._off(this.options.fileInput, 'change'); + }, + + _destroy: function () { + this._destroyEventHandlers(); + }, + + _setOption: function (key, value) { + var reinit = $.inArray(key, this._specialOptions) !== -1; + if (reinit) { + this._destroyEventHandlers(); + } + this._super(key, value); + if (reinit) { + this._initSpecialOptions(); + this._initEventHandlers(); + } + }, + + _initSpecialOptions: function () { + var options = this.options; + if (options.fileInput === undefined) { + options.fileInput = this.element.is('input[type="file"]') ? + this.element : this.element.find('input[type="file"]'); + } else if (!(options.fileInput instanceof $)) { + options.fileInput = $(options.fileInput); + } + if (!(options.dropZone instanceof $)) { + options.dropZone = $(options.dropZone); + } + if (!(options.pasteZone instanceof $)) { + options.pasteZone = $(options.pasteZone); + } + }, + + _getRegExp: function (str) { + var parts = str.split('/'), + modifiers = parts.pop(); + parts.shift(); + return new RegExp(parts.join('/'), modifiers); + }, + + _isRegExpOption: function (key, value) { + return key !== 'url' && $.type(value) === 'string' && + /^\/.*\/[igm]{0,3}$/.test(value); + }, + + _initDataAttributes: function () { + var that = this, + options = this.options, + data = this.element.data(); + // Initialize options set via HTML5 data-attributes: + $.each( + this.element[0].attributes, + function (index, attr) { + var key = attr.name.toLowerCase(), + value; + if (/^data-/.test(key)) { + // Convert hyphen-ated key to camelCase: + key = key.slice(5).replace(/-[a-z]/g, function (str) { + return str.charAt(1).toUpperCase(); + }); + value = data[key]; + if (that._isRegExpOption(key, value)) { + value = that._getRegExp(value); + } + options[key] = value; + } + } + ); + }, + + _create: function () { + this._initDataAttributes(); + this._initSpecialOptions(); + this._slots = []; + this._sequence = this._getXHRPromise(true); + this._sending = this._active = 0; + this._initProgressObject(this); + this._initEventHandlers(); + }, + + // This method is exposed to the widget API and allows to query + // the number of active uploads: + active: function () { + return this._active; + }, + + // This method is exposed to the widget API and allows to query + // the widget upload progress. + // It returns an object with loaded, total and bitrate properties + // for the running uploads: + progress: function () { + return this._progress; + }, + + // This method is exposed to the widget API and allows adding files + // using the fileupload API. The data parameter accepts an object which + // must have a files property and can contain additional options: + // .fileupload('add', {files: filesList}); + add: function (data) { + var that = this; + if (!data || this.options.disabled) { + return; + } + if (data.fileInput && !data.files) { + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + that._onAdd(null, data); + }); + } else { + data.files = $.makeArray(data.files); + this._onAdd(null, data); + } + }, + + // This method is exposed to the widget API and allows sending files + // using the fileupload API. The data parameter accepts an object which + // must have a files or fileInput property and can contain additional options: + // .fileupload('send', {files: filesList}); + // The method returns a Promise object for the file upload call. + send: function (data) { + if (data && !this.options.disabled) { + if (data.fileInput && !data.files) { + var that = this, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + aborted; + promise.abort = function () { + aborted = true; + if (jqXHR) { + return jqXHR.abort(); + } + dfd.reject(null, 'abort', 'abort'); + return promise; + }; + this._getFileInputFiles(data.fileInput).always( + function (files) { + if (aborted) { + return; + } + if (!files.length) { + dfd.reject(); + return; + } + data.files = files; + jqXHR = that._onSend(null, data); + jqXHR.then( + function (result, textStatus, jqXHR) { + dfd.resolve(result, textStatus, jqXHR); + }, + function (jqXHR, textStatus, errorThrown) { + dfd.reject(jqXHR, textStatus, errorThrown); + } + ); + } + ); + return this._enhancePromise(promise); + } + data.files = $.makeArray(data.files); + if (data.files.length) { + return this._onSend(null, data); + } + } + return this._getXHRPromise(false, data && data.context); + } + + }); + +})); diff --git a/lib/cloudinary/static/js/jquery.iframe-transport.js b/lib/cloudinary/static/js/jquery.iframe-transport.js new file mode 100644 index 00000000..8d25c464 --- /dev/null +++ b/lib/cloudinary/static/js/jquery.iframe-transport.js @@ -0,0 +1,224 @@ +/* + * jQuery Iframe Transport Plugin + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + */ + +/* global define, require, window, document, JSON */ + +;(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define(['jquery'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS: + factory(require('jquery')); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // Helper variable to create unique names for the transport iframes: + var counter = 0, + jsonAPI = $, + jsonParse = 'parseJSON'; + + if ('JSON' in window && 'parse' in JSON) { + jsonAPI = JSON; + jsonParse = 'parse'; + } + + // The iframe transport accepts four additional options: + // options.fileInput: a jQuery collection of file input fields + // options.paramName: the parameter name for the file form data, + // overrides the name property of the file input field(s), + // can be a string or an array of strings. + // options.formData: an array of objects with name and value properties, + // equivalent to the return data of .serializeArray(), e.g.: + // [{name: 'a', value: 1}, {name: 'b', value: 2}] + // options.initialIframeSrc: the URL of the initial iframe src, + // by default set to "javascript:false;" + $.ajaxTransport('iframe', function (options) { + if (options.async) { + // javascript:false as initial iframe src + // prevents warning popups on HTTPS in IE6: + /*jshint scripturl: true */ + var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', + /*jshint scripturl: false */ + form, + iframe, + addParamChar; + return { + send: function (_, completeCallback) { + form = $('
'); + form.attr('accept-charset', options.formAcceptCharset); + addParamChar = /\?/.test(options.url) ? '&' : '?'; + // XDomainRequest only supports GET and POST: + if (options.type === 'DELETE') { + options.url = options.url + addParamChar + '_method=DELETE'; + options.type = 'POST'; + } else if (options.type === 'PUT') { + options.url = options.url + addParamChar + '_method=PUT'; + options.type = 'POST'; + } else if (options.type === 'PATCH') { + options.url = options.url + addParamChar + '_method=PATCH'; + options.type = 'POST'; + } + // IE versions below IE8 cannot set the name property of + // elements that have already been added to the DOM, + // so we set the name along with the iframe HTML markup: + counter += 1; + iframe = $( + '' + ).bind('load', function () { + var fileInputClones, + paramNames = $.isArray(options.paramName) ? + options.paramName : [options.paramName]; + iframe + .unbind('load') + .bind('load', function () { + var response; + // Wrap in a try/catch block to catch exceptions thrown + // when trying to access cross-domain iframe contents: + try { + response = iframe.contents(); + // Google Chrome and Firefox do not throw an + // exception when calling iframe.contents() on + // cross-domain requests, so we unify the response: + if (!response.length || !response[0].firstChild) { + throw new Error(); + } + } catch (e) { + response = undefined; + } + // The complete callback returns the + // iframe content document as response object: + completeCallback( + 200, + 'success', + {'iframe': response} + ); + // Fix for IE endless progress bar activity bug + // (happens on form submits to iframe targets): + $('') + .appendTo(form); + window.setTimeout(function () { + // Removing the form in a setTimeout call + // allows Chrome's developer tools to display + // the response result + form.remove(); + }, 0); + }); + form + .prop('target', iframe.prop('name')) + .prop('action', options.url) + .prop('method', options.type); + if (options.formData) { + $.each(options.formData, function (index, field) { + $('') + .prop('name', field.name) + .val(field.value) + .appendTo(form); + }); + } + if (options.fileInput && options.fileInput.length && + options.type === 'POST') { + fileInputClones = options.fileInput.clone(); + // Insert a clone for each file input field: + options.fileInput.after(function (index) { + return fileInputClones[index]; + }); + if (options.paramName) { + options.fileInput.each(function (index) { + $(this).prop( + 'name', + paramNames[index] || options.paramName + ); + }); + } + // Appending the file input fields to the hidden form + // removes them from their original location: + form + .append(options.fileInput) + .prop('enctype', 'multipart/form-data') + // enctype must be set as encoding for IE: + .prop('encoding', 'multipart/form-data'); + // Remove the HTML5 form attribute from the input(s): + options.fileInput.removeAttr('form'); + } + form.submit(); + // Insert the file input fields at their original location + // by replacing the clones with the originals: + if (fileInputClones && fileInputClones.length) { + options.fileInput.each(function (index, input) { + var clone = $(fileInputClones[index]); + // Restore the original name and form properties: + $(input) + .prop('name', clone.prop('name')) + .attr('form', clone.attr('form')); + clone.replaceWith(input); + }); + } + }); + form.append(iframe).appendTo(document.body); + }, + abort: function () { + if (iframe) { + // javascript:false as iframe src aborts the request + // and prevents warning popups on HTTPS in IE6. + // concat is used to avoid the "Script URL" JSLint error: + iframe + .unbind('load') + .prop('src', initialIframeSrc); + } + if (form) { + form.remove(); + } + } + }; + } + }); + + // The iframe transport returns the iframe content document as response. + // The following adds converters from iframe to text, json, html, xml + // and script. + // Please note that the Content-Type for JSON responses has to be text/plain + // or text/html, if the browser doesn't include application/json in the + // Accept header, else IE will show a download dialog. + // The Content-Type for XML responses on the other hand has to be always + // application/xml or text/xml, so IE properly parses the XML response. + // See also + // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation + $.ajaxSetup({ + converters: { + 'iframe text': function (iframe) { + return iframe && $(iframe[0].body).text(); + }, + 'iframe json': function (iframe) { + return iframe && jsonAPI[jsonParse]($(iframe[0].body).text()); + }, + 'iframe html': function (iframe) { + return iframe && $(iframe[0].body).html(); + }, + 'iframe xml': function (iframe) { + var xmlDoc = iframe && iframe[0]; + return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : + $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || + $(xmlDoc.body).html()); + }, + 'iframe script': function (iframe) { + return iframe && $.globalEval($(iframe[0].body).text()); + } + } + }); + +})); diff --git a/lib/cloudinary/static/js/jquery.ui.widget.js b/lib/cloudinary/static/js/jquery.ui.widget.js new file mode 100644 index 00000000..e08df3fd --- /dev/null +++ b/lib/cloudinary/static/js/jquery.ui.widget.js @@ -0,0 +1,572 @@ +/*! jQuery UI - v1.11.4+CommonJS - 2015-08-28 +* http://jqueryui.com +* Includes: widget.js +* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ + +(function( factory ) { + if ( typeof define === "function" && define.amd ) { + + // AMD. Register as an anonymous module. + define([ "jquery" ], factory ); + + } else if ( typeof exports === "object" ) { + + // Node/CommonJS + factory( require( "jquery" ) ); + + } else { + + // Browser globals + factory( jQuery ); + } +}(function( $ ) { +/*! + * jQuery UI Widget 1.11.4 + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + * + * http://api.jqueryui.com/jQuery.widget/ + */ + + +var widget_uuid = 0, + widget_slice = Array.prototype.slice; + +$.cleanData = (function( orig ) { + return function( elems ) { + var events, elem, i; + for ( i = 0; (elem = elems[i]) != null; i++ ) { + try { + + // Only trigger remove when necessary to save time + events = $._data( elem, "events" ); + if ( events && events.remove ) { + $( elem ).triggerHandler( "remove" ); + } + + // http://bugs.jquery.com/ticket/8235 + } catch ( e ) {} + } + orig( elems ); + }; +})( $.cleanData ); + +$.widget = function( name, base, prototype ) { + var fullName, existingConstructor, constructor, basePrototype, + // proxiedPrototype allows the provided prototype to remain unmodified + // so that it can be used as a mixin for multiple widgets (#8876) + proxiedPrototype = {}, + namespace = name.split( "." )[ 0 ]; + + name = name.split( "." )[ 1 ]; + fullName = namespace + "-" + name; + + if ( !prototype ) { + prototype = base; + base = $.Widget; + } + + // create selector for plugin + $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { + return !!$.data( elem, fullName ); + }; + + $[ namespace ] = $[ namespace ] || {}; + existingConstructor = $[ namespace ][ name ]; + constructor = $[ namespace ][ name ] = function( options, element ) { + // allow instantiation without "new" keyword + if ( !this._createWidget ) { + return new constructor( options, element ); + } + + // allow instantiation without initializing for simple inheritance + // must use "new" keyword (the code above always passes args) + if ( arguments.length ) { + this._createWidget( options, element ); + } + }; + // extend with the existing constructor to carry over any static properties + $.extend( constructor, existingConstructor, { + version: prototype.version, + // copy the object used to create the prototype in case we need to + // redefine the widget later + _proto: $.extend( {}, prototype ), + // track widgets that inherit from this widget in case this widget is + // redefined after a widget inherits from it + _childConstructors: [] + }); + + basePrototype = new base(); + // we need to make the options hash a property directly on the new instance + // otherwise we'll modify the options hash on the prototype that we're + // inheriting from + basePrototype.options = $.widget.extend( {}, basePrototype.options ); + $.each( prototype, function( prop, value ) { + if ( !$.isFunction( value ) ) { + proxiedPrototype[ prop ] = value; + return; + } + proxiedPrototype[ prop ] = (function() { + var _super = function() { + return base.prototype[ prop ].apply( this, arguments ); + }, + _superApply = function( args ) { + return base.prototype[ prop ].apply( this, args ); + }; + return function() { + var __super = this._super, + __superApply = this._superApply, + returnValue; + + this._super = _super; + this._superApply = _superApply; + + returnValue = value.apply( this, arguments ); + + this._super = __super; + this._superApply = __superApply; + + return returnValue; + }; + })(); + }); + constructor.prototype = $.widget.extend( basePrototype, { + // TODO: remove support for widgetEventPrefix + // always use the name + a colon as the prefix, e.g., draggable:start + // don't prefix for widgets that aren't DOM-based + widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name + }, proxiedPrototype, { + constructor: constructor, + namespace: namespace, + widgetName: name, + widgetFullName: fullName + }); + + // If this widget is being redefined then we need to find all widgets that + // are inheriting from it and redefine all of them so that they inherit from + // the new version of this widget. We're essentially trying to replace one + // level in the prototype chain. + if ( existingConstructor ) { + $.each( existingConstructor._childConstructors, function( i, child ) { + var childPrototype = child.prototype; + + // redefine the child widget using the same prototype that was + // originally used, but inherit from the new version of the base + $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); + }); + // remove the list of existing child constructors from the old constructor + // so the old child constructors can be garbage collected + delete existingConstructor._childConstructors; + } else { + base._childConstructors.push( constructor ); + } + + $.widget.bridge( name, constructor ); + + return constructor; +}; + +$.widget.extend = function( target ) { + var input = widget_slice.call( arguments, 1 ), + inputIndex = 0, + inputLength = input.length, + key, + value; + for ( ; inputIndex < inputLength; inputIndex++ ) { + for ( key in input[ inputIndex ] ) { + value = input[ inputIndex ][ key ]; + if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { + // Clone objects + if ( $.isPlainObject( value ) ) { + target[ key ] = $.isPlainObject( target[ key ] ) ? + $.widget.extend( {}, target[ key ], value ) : + // Don't extend strings, arrays, etc. with objects + $.widget.extend( {}, value ); + // Copy everything else by reference + } else { + target[ key ] = value; + } + } + } + } + return target; +}; + +$.widget.bridge = function( name, object ) { + var fullName = object.prototype.widgetFullName || name; + $.fn[ name ] = function( options ) { + var isMethodCall = typeof options === "string", + args = widget_slice.call( arguments, 1 ), + returnValue = this; + + if ( isMethodCall ) { + this.each(function() { + var methodValue, + instance = $.data( this, fullName ); + if ( options === "instance" ) { + returnValue = instance; + return false; + } + if ( !instance ) { + return $.error( "cannot call methods on " + name + " prior to initialization; " + + "attempted to call method '" + options + "'" ); + } + if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { + return $.error( "no such method '" + options + "' for " + name + " widget instance" ); + } + methodValue = instance[ options ].apply( instance, args ); + if ( methodValue !== instance && methodValue !== undefined ) { + returnValue = methodValue && methodValue.jquery ? + returnValue.pushStack( methodValue.get() ) : + methodValue; + return false; + } + }); + } else { + + // Allow multiple hashes to be passed on init + if ( args.length ) { + options = $.widget.extend.apply( null, [ options ].concat(args) ); + } + + this.each(function() { + var instance = $.data( this, fullName ); + if ( instance ) { + instance.option( options || {} ); + if ( instance._init ) { + instance._init(); + } + } else { + $.data( this, fullName, new object( options, this ) ); + } + }); + } + + return returnValue; + }; +}; + +$.Widget = function( /* options, element */ ) {}; +$.Widget._childConstructors = []; + +$.Widget.prototype = { + widgetName: "widget", + widgetEventPrefix: "", + defaultElement: "
", + options: { + disabled: false, + + // callbacks + create: null + }, + _createWidget: function( options, element ) { + element = $( element || this.defaultElement || this )[ 0 ]; + this.element = $( element ); + this.uuid = widget_uuid++; + this.eventNamespace = "." + this.widgetName + this.uuid; + + this.bindings = $(); + this.hoverable = $(); + this.focusable = $(); + + if ( element !== this ) { + $.data( element, this.widgetFullName, this ); + this._on( true, this.element, { + remove: function( event ) { + if ( event.target === element ) { + this.destroy(); + } + } + }); + this.document = $( element.style ? + // element within the document + element.ownerDocument : + // element is window or document + element.document || element ); + this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); + } + + this.options = $.widget.extend( {}, + this.options, + this._getCreateOptions(), + options ); + + this._create(); + this._trigger( "create", null, this._getCreateEventData() ); + this._init(); + }, + _getCreateOptions: $.noop, + _getCreateEventData: $.noop, + _create: $.noop, + _init: $.noop, + + destroy: function() { + this._destroy(); + // we can probably remove the unbind calls in 2.0 + // all event bindings should go through this._on() + this.element + .unbind( this.eventNamespace ) + .removeData( this.widgetFullName ) + // support: jquery <1.6.3 + // http://bugs.jquery.com/ticket/9413 + .removeData( $.camelCase( this.widgetFullName ) ); + this.widget() + .unbind( this.eventNamespace ) + .removeAttr( "aria-disabled" ) + .removeClass( + this.widgetFullName + "-disabled " + + "ui-state-disabled" ); + + // clean up events and states + this.bindings.unbind( this.eventNamespace ); + this.hoverable.removeClass( "ui-state-hover" ); + this.focusable.removeClass( "ui-state-focus" ); + }, + _destroy: $.noop, + + widget: function() { + return this.element; + }, + + option: function( key, value ) { + var options = key, + parts, + curOption, + i; + + if ( arguments.length === 0 ) { + // don't return a reference to the internal hash + return $.widget.extend( {}, this.options ); + } + + if ( typeof key === "string" ) { + // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } + options = {}; + parts = key.split( "." ); + key = parts.shift(); + if ( parts.length ) { + curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); + for ( i = 0; i < parts.length - 1; i++ ) { + curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; + curOption = curOption[ parts[ i ] ]; + } + key = parts.pop(); + if ( arguments.length === 1 ) { + return curOption[ key ] === undefined ? null : curOption[ key ]; + } + curOption[ key ] = value; + } else { + if ( arguments.length === 1 ) { + return this.options[ key ] === undefined ? null : this.options[ key ]; + } + options[ key ] = value; + } + } + + this._setOptions( options ); + + return this; + }, + _setOptions: function( options ) { + var key; + + for ( key in options ) { + this._setOption( key, options[ key ] ); + } + + return this; + }, + _setOption: function( key, value ) { + this.options[ key ] = value; + + if ( key === "disabled" ) { + this.widget() + .toggleClass( this.widgetFullName + "-disabled", !!value ); + + // If the widget is becoming disabled, then nothing is interactive + if ( value ) { + this.hoverable.removeClass( "ui-state-hover" ); + this.focusable.removeClass( "ui-state-focus" ); + } + } + + return this; + }, + + enable: function() { + return this._setOptions({ disabled: false }); + }, + disable: function() { + return this._setOptions({ disabled: true }); + }, + + _on: function( suppressDisabledCheck, element, handlers ) { + var delegateElement, + instance = this; + + // no suppressDisabledCheck flag, shuffle arguments + if ( typeof suppressDisabledCheck !== "boolean" ) { + handlers = element; + element = suppressDisabledCheck; + suppressDisabledCheck = false; + } + + // no element argument, shuffle and use this.element + if ( !handlers ) { + handlers = element; + element = this.element; + delegateElement = this.widget(); + } else { + element = delegateElement = $( element ); + this.bindings = this.bindings.add( element ); + } + + $.each( handlers, function( event, handler ) { + function handlerProxy() { + // allow widgets to customize the disabled handling + // - disabled as an array instead of boolean + // - disabled class as method for disabling individual parts + if ( !suppressDisabledCheck && + ( instance.options.disabled === true || + $( this ).hasClass( "ui-state-disabled" ) ) ) { + return; + } + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + + // copy the guid so direct unbinding works + if ( typeof handler !== "string" ) { + handlerProxy.guid = handler.guid = + handler.guid || handlerProxy.guid || $.guid++; + } + + var match = event.match( /^([\w:-]*)\s*(.*)$/ ), + eventName = match[1] + instance.eventNamespace, + selector = match[2]; + if ( selector ) { + delegateElement.delegate( selector, eventName, handlerProxy ); + } else { + element.bind( eventName, handlerProxy ); + } + }); + }, + + _off: function( element, eventName ) { + eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + + this.eventNamespace; + element.unbind( eventName ).undelegate( eventName ); + + // Clear the stack to avoid memory leaks (#10056) + this.bindings = $( this.bindings.not( element ).get() ); + this.focusable = $( this.focusable.not( element ).get() ); + this.hoverable = $( this.hoverable.not( element ).get() ); + }, + + _delay: function( handler, delay ) { + function handlerProxy() { + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + var instance = this; + return setTimeout( handlerProxy, delay || 0 ); + }, + + _hoverable: function( element ) { + this.hoverable = this.hoverable.add( element ); + this._on( element, { + mouseenter: function( event ) { + $( event.currentTarget ).addClass( "ui-state-hover" ); + }, + mouseleave: function( event ) { + $( event.currentTarget ).removeClass( "ui-state-hover" ); + } + }); + }, + + _focusable: function( element ) { + this.focusable = this.focusable.add( element ); + this._on( element, { + focusin: function( event ) { + $( event.currentTarget ).addClass( "ui-state-focus" ); + }, + focusout: function( event ) { + $( event.currentTarget ).removeClass( "ui-state-focus" ); + } + }); + }, + + _trigger: function( type, event, data ) { + var prop, orig, + callback = this.options[ type ]; + + data = data || {}; + event = $.Event( event ); + event.type = ( type === this.widgetEventPrefix ? + type : + this.widgetEventPrefix + type ).toLowerCase(); + // the original event may come from any element + // so we need to reset the target on the new event + event.target = this.element[ 0 ]; + + // copy original event properties over to the new event + orig = event.originalEvent; + if ( orig ) { + for ( prop in orig ) { + if ( !( prop in event ) ) { + event[ prop ] = orig[ prop ]; + } + } + } + + this.element.trigger( event, data ); + return !( $.isFunction( callback ) && + callback.apply( this.element[0], [ event ].concat( data ) ) === false || + event.isDefaultPrevented() ); + } +}; + +$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { + $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { + if ( typeof options === "string" ) { + options = { effect: options }; + } + var hasOptions, + effectName = !options ? + method : + options === true || typeof options === "number" ? + defaultEffect : + options.effect || defaultEffect; + options = options || {}; + if ( typeof options === "number" ) { + options = { duration: options }; + } + hasOptions = !$.isEmptyObject( options ); + options.complete = callback; + if ( options.delay ) { + element.delay( options.delay ); + } + if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { + element[ method ]( options ); + } else if ( effectName !== method && element[ effectName ] ) { + element[ effectName ]( options.duration, options.easing, callback ); + } else { + element.queue(function( next ) { + $( this )[ method ](); + if ( callback ) { + callback.call( element[ 0 ] ); + } + next(); + }); + } + }; +}); + +var widget = $.widget; + + + +})); diff --git a/lib/cloudinary/static/js/load-image.all.min.js b/lib/cloudinary/static/js/load-image.all.min.js new file mode 100644 index 00000000..acd7113e --- /dev/null +++ b/lib/cloudinary/static/js/load-image.all.min.js @@ -0,0 +1,2 @@ +!function(e){"use strict";function t(e,i,a){var o,n=document.createElement("img");return n.onerror=function(o){return t.onerror(n,o,e,i,a)},n.onload=function(o){return t.onload(n,o,e,i,a)},"string"==typeof e?(t.fetchBlob(e,function(i){i?(e=i,o=t.createObjectURL(e)):(o=e,a&&a.crossOrigin&&(n.crossOrigin=a.crossOrigin)),n.src=o},a),n):t.isInstanceOf("Blob",e)||t.isInstanceOf("File",e)?(o=n._objectURL=t.createObjectURL(e))?(n.src=o,n):t.readFile(e,function(e){var t=e.target;t&&t.result?n.src=t.result:i&&i(e)}):void 0}function i(e,i){!e._objectURL||i&&i.noRevoke||(t.revokeObjectURL(e._objectURL),delete e._objectURL)}var a=e.createObjectURL&&e||e.URL&&URL.revokeObjectURL&&URL||e.webkitURL&&webkitURL;t.fetchBlob=function(e,t,i){t()},t.isInstanceOf=function(e,t){return Object.prototype.toString.call(t)==="[object "+e+"]"},t.transform=function(e,t,i,a,o){i(e,o)},t.onerror=function(e,t,a,o,n){i(e,n),o&&o.call(e,t)},t.onload=function(e,a,o,n,r){i(e,r),n&&t.transform(e,r,n,o,{})},t.createObjectURL=function(e){return!!a&&a.createObjectURL(e)},t.revokeObjectURL=function(e){return!!a&&a.revokeObjectURL(e)},t.readFile=function(t,i,a){if(e.FileReader){var o=new FileReader;if(o.onload=o.onerror=i,a=a||"readAsDataURL",o[a])return o[a](t),o}return!1},"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:e.loadImage=t}("undefined"!=typeof window&&window||this),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image"],e):e("object"==typeof module&&module.exports?require("./load-image"):window.loadImage)}(function(e){"use strict";var t=e.transform;e.transform=function(i,a,o,n,r){t.call(e,e.scale(i,a,r),a,o,n,r)},e.transformCoordinates=function(){},e.getTransformedOptions=function(e,t){var i,a,o,n,r=t.aspectRatio;if(!r)return t;i={};for(a in t)t.hasOwnProperty(a)&&(i[a]=t[a]);return i.crop=!0,o=e.naturalWidth||e.width,n=e.naturalHeight||e.height,o/n>r?(i.maxWidth=n*r,i.maxHeight=n):(i.maxWidth=o,i.maxHeight=o/r),i},e.renderImageToCanvas=function(e,t,i,a,o,n,r,s,l,d){return e.getContext("2d").drawImage(t,i,a,o,n,r,s,l,d),e},e.hasCanvasOption=function(e){return e.canvas||e.crop||!!e.aspectRatio},e.scale=function(t,i,a){function o(){var e=Math.max((l||v)/v,(d||P)/P);e>1&&(v*=e,P*=e)}function n(){var e=Math.min((r||v)/v,(s||P)/P);e<1&&(v*=e,P*=e)}i=i||{};var r,s,l,d,c,u,f,g,h,m,p,S=document.createElement("canvas"),b=t.getContext||e.hasCanvasOption(i)&&S.getContext,y=t.naturalWidth||t.width,x=t.naturalHeight||t.height,v=y,P=x;if(b&&(f=(i=e.getTransformedOptions(t,i,a)).left||0,g=i.top||0,i.sourceWidth?(c=i.sourceWidth,void 0!==i.right&&void 0===i.left&&(f=y-c-i.right)):c=y-f-(i.right||0),i.sourceHeight?(u=i.sourceHeight,void 0!==i.bottom&&void 0===i.top&&(g=x-u-i.bottom)):u=x-g-(i.bottom||0),v=c,P=u),r=i.maxWidth,s=i.maxHeight,l=i.minWidth,d=i.minHeight,b&&r&&s&&i.crop?(v=r,P=s,(p=c/u-r/s)<0?(u=s*c/r,void 0===i.top&&void 0===i.bottom&&(g=(x-u)/2)):p>0&&(c=r*u/s,void 0===i.left&&void 0===i.right&&(f=(y-c)/2))):((i.contain||i.cover)&&(l=r=r||l,d=s=s||d),i.cover?(n(),o()):(o(),n())),b){if((h=i.pixelRatio)>1&&(S.style.width=v+"px",S.style.height=P+"px",v*=h,P*=h,S.getContext("2d").scale(h,h)),(m=i.downsamplingRatio)>0&&m<1&&vv;)S.width=c*m,S.height=u*m,e.renderImageToCanvas(S,t,f,g,c,u,0,0,S.width,S.height),f=0,g=0,c=S.width,u=S.height,(t=document.createElement("canvas")).width=c,t.height=u,e.renderImageToCanvas(t,S,0,0,c,u,0,0,c,u);return S.width=v,S.height=P,e.transformCoordinates(S,i),e.renderImageToCanvas(S,t,f,g,c,u,0,0,v,P)}return t.width=v,t.height=P,t}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image"],e):e("object"==typeof module&&module.exports?require("./load-image"):window.loadImage)}(function(e){"use strict";var t="undefined"!=typeof Blob&&(Blob.prototype.slice||Blob.prototype.webkitSlice||Blob.prototype.mozSlice);e.blobSlice=t&&function(){return(this.slice||this.webkitSlice||this.mozSlice).apply(this,arguments)},e.metaDataParsers={jpeg:{65505:[]}},e.parseMetaData=function(t,i,a,o){a=a||{},o=o||{};var n=this,r=a.maxMetaDataSize||262144;!!("undefined"!=typeof DataView&&t&&t.size>=12&&"image/jpeg"===t.type&&e.blobSlice)&&e.readFile(e.blobSlice.call(t,0,r),function(t){if(t.target.error)return console.log(t.target.error),void i(o);var r,s,l,d,c=t.target.result,u=new DataView(c),f=2,g=u.byteLength-4,h=f;if(65496===u.getUint16(0)){for(;f=65504&&r<=65519||65534===r);){if(s=u.getUint16(f+2)+2,f+s>u.byteLength){console.log("Invalid meta data: Invalid segment size.");break}if(l=e.metaDataParsers.jpeg[r])for(d=0;d6&&(c.slice?o.imageHead=c.slice(0,h):o.imageHead=new Uint8Array(c).subarray(0,h))}else console.log("Invalid JPEG file: Missing JPEG marker.");i(o)},"readAsArrayBuffer")||i(o)},e.hasMetaOption=function(e){return e&&e.meta};var i=e.transform;e.transform=function(t,a,o,n,r){e.hasMetaOption(a)?e.parseMetaData(n,function(r){i.call(e,t,a,o,n,r)},a,r):i.apply(e,arguments)}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-meta")):e(window.loadImage)}(function(e){"use strict";"undefined"!=typeof fetch&&"undefined"!=typeof Request&&(e.fetchBlob=function(t,i,a){if(e.hasMetaOption(a))return fetch(new Request(t,a)).then(function(e){return e.blob()}).then(i).catch(function(e){console.log(e),i()});i()})}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-meta")):e(window.loadImage)}(function(e){"use strict";e.ExifMap=function(){return this},e.ExifMap.prototype.map={Orientation:274},e.ExifMap.prototype.get=function(e){return this[e]||this[this.map[e]]},e.getExifThumbnail=function(e,t,i){var a,o,n;{if(i&&!(t+i>e.byteLength)){for(a=[],o=0;o4?i+t.getUint32(a+8,r):a+8)+s>t.byteLength)){if(1===n)return g.getValue(t,l,r);for(d=[],c=0;ce.byteLength)console.log("Invalid Exif data: Invalid directory offset.");else{if(n=e.getUint16(i,a),!((r=i+2+12*n)+4>e.byteLength)){for(s=0;st.byteLength)console.log("Invalid Exif data: Invalid segment size.");else if(0===t.getUint16(i+8)){switch(t.getUint16(d)){case 18761:r=!0;break;case 19789:r=!1;break;default:return void console.log("Invalid Exif data: Invalid byte alignment marker.")}42===t.getUint16(d+2,r)?(s=t.getUint32(d+4,r),o.exif=new e.ExifMap,(s=e.parseExifTags(t,d,d+s,r,o))&&!n.disableExifThumbnail&&(l={exif:{}},s=e.parseExifTags(t,d,d+s,r,l),l.exif[513]&&(o.exif.Thumbnail=e.getExifThumbnail(t,d+l.exif[513],l.exif[514]))),o.exif[34665]&&!n.disableExifSub&&e.parseExifTags(t,d,d+o.exif[34665],r,o),o.exif[34853]&&!n.disableExifGps&&e.parseExifTags(t,d,d+o.exif[34853],r,o)):console.log("Invalid Exif data: Missing TIFF marker.")}else console.log("Invalid Exif data: Missing byte alignment offset.")}},e.metaDataParsers.jpeg[65505].push(e.parseExifData)}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-exif"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-exif")):e(window.loadImage)}(function(e){"use strict";e.ExifMap.prototype.tags={256:"ImageWidth",257:"ImageHeight",34665:"ExifIFDPointer",34853:"GPSInfoIFDPointer",40965:"InteroperabilityIFDPointer",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",274:"Orientation",277:"SamplesPerPixel",284:"PlanarConfiguration",530:"YCbCrSubSampling",531:"YCbCrPositioning",282:"XResolution",283:"YResolution",296:"ResolutionUnit",273:"StripOffsets",278:"RowsPerStrip",279:"StripByteCounts",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",301:"TransferFunction",318:"WhitePoint",319:"PrimaryChromaticities",529:"YCbCrCoefficients",532:"ReferenceBlackWhite",306:"DateTime",270:"ImageDescription",271:"Make",272:"Model",305:"Software",315:"Artist",33432:"Copyright",36864:"ExifVersion",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",42240:"Gamma",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37500:"MakerNote",37510:"UserComment",40964:"RelatedSoundFile",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37520:"SubSecTime",37521:"SubSecTimeOriginal",37522:"SubSecTimeDigitized",33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"PhotographicSensitivity",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBias",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37396:"SubjectArea",37386:"FocalLength",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},e.ExifMap.prototype.stringValues={ExposureProgram:{0:"Undefined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"},MeteringMode:{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"},LightSource:{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"},Flash:{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"},SensingMethod:{1:"Undefined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"},SceneCaptureType:{0:"Standard",1:"Landscape",2:"Portrait",3:"Night scene"},SceneType:{1:"Directly photographed"},CustomRendered:{0:"Normal process",1:"Custom process"},WhiteBalance:{0:"Auto white balance",1:"Manual white balance"},GainControl:{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"},Contrast:{0:"Normal",1:"Soft",2:"Hard"},Saturation:{0:"Normal",1:"Low saturation",2:"High saturation"},Sharpness:{0:"Normal",1:"Soft",2:"Hard"},SubjectDistanceRange:{0:"Unknown",1:"Macro",2:"Close view",3:"Distant view"},FileSource:{3:"DSC"},ComponentsConfiguration:{0:"",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"},Orientation:{1:"top-left",2:"top-right",3:"bottom-right",4:"bottom-left",5:"left-top",6:"right-top",7:"right-bottom",8:"left-bottom"}},e.ExifMap.prototype.getText=function(e){var t=this.get(e);switch(e){case"LightSource":case"Flash":case"MeteringMode":case"ExposureProgram":case"SensingMethod":case"SceneCaptureType":case"SceneType":case"CustomRendered":case"WhiteBalance":case"GainControl":case"Contrast":case"Saturation":case"Sharpness":case"SubjectDistanceRange":case"FileSource":case"Orientation":return this.stringValues[e][t];case"ExifVersion":case"FlashpixVersion":if(!t)return;return String.fromCharCode(t[0],t[1],t[2],t[3]);case"ComponentsConfiguration":if(!t)return;return this.stringValues[e][t[0]]+this.stringValues[e][t[1]]+this.stringValues[e][t[2]]+this.stringValues[e][t[3]];case"GPSVersionID":if(!t)return;return t[0]+"."+t[1]+"."+t[2]+"."+t[3]}return String(t)},function(e){var t,i=e.tags,a=e.map;for(t in i)i.hasOwnProperty(t)&&(a[i[t]]=t)}(e.ExifMap.prototype),e.ExifMap.prototype.getAll=function(){var e,t,i={};for(e in this)this.hasOwnProperty(e)&&(t=this.tags[e])&&(i[t]=this.getText(t));return i}}),function(e){"use strict";"function"==typeof define&&define.amd?define(["./load-image","./load-image-scale","./load-image-meta"],e):"object"==typeof module&&module.exports?e(require("./load-image"),require("./load-image-scale"),require("./load-image-meta")):e(window.loadImage)}(function(e){"use strict";var t=e.hasCanvasOption,i=e.hasMetaOption,a=e.transformCoordinates,o=e.getTransformedOptions;e.hasCanvasOption=function(i){return!!i.orientation||t.call(e,i)},e.hasMetaOption=function(t){return t&&!0===t.orientation||i.call(e,t)},e.transformCoordinates=function(t,i){a.call(e,t,i);var o=t.getContext("2d"),n=t.width,r=t.height,s=t.style.width,l=t.style.height,d=i.orientation;if(d&&!(d>8))switch(d>4&&(t.width=r,t.height=n,t.style.width=l,t.style.height=s),d){case 2:o.translate(n,0),o.scale(-1,1);break;case 3:o.translate(n,r),o.rotate(Math.PI);break;case 4:o.translate(0,r),o.scale(1,-1);break;case 5:o.rotate(.5*Math.PI),o.scale(1,-1);break;case 6:o.rotate(.5*Math.PI),o.translate(0,-r);break;case 7:o.rotate(.5*Math.PI),o.translate(n,-r),o.scale(-1,1);break;case 8:o.rotate(-.5*Math.PI),o.translate(-n,0)}},e.getTransformedOptions=function(t,i,a){var n,r,s=o.call(e,t,i),l=s.orientation;if(!0===l&&a&&a.exif&&(l=a.exif.get("Orientation")),!l||l>8||1===l)return s;n={};for(r in s)s.hasOwnProperty(r)&&(n[r]=s[r]);switch(n.orientation=l,l){case 2:n.left=s.right,n.right=s.left;break;case 3:n.left=s.right,n.top=s.bottom,n.right=s.left,n.bottom=s.top;break;case 4:n.top=s.bottom,n.bottom=s.top;break;case 5:n.left=s.top,n.top=s.left,n.right=s.bottom,n.bottom=s.right;break;case 6:n.left=s.top,n.top=s.right,n.right=s.bottom,n.bottom=s.left;break;case 7:n.left=s.bottom,n.top=s.right,n.right=s.top,n.bottom=s.left;break;case 8:n.left=s.bottom,n.top=s.left,n.right=s.top,n.bottom=s.right}return n.orientation>4&&(n.maxWidth=s.maxHeight,n.maxHeight=s.maxWidth,n.minWidth=s.minHeight,n.minHeight=s.minWidth,n.sourceWidth=s.sourceHeight,n.sourceHeight=s.sourceWidth),n}}); +//# sourceMappingURL=load-image.all.min.js.map \ No newline at end of file diff --git a/lib/cloudinary/templates/cloudinary_direct_upload.html b/lib/cloudinary/templates/cloudinary_direct_upload.html new file mode 100644 index 00000000..2bf710c4 --- /dev/null +++ b/lib/cloudinary/templates/cloudinary_direct_upload.html @@ -0,0 +1,12 @@ +
+ {% for name, value in params.items %} + + {% endfor %} + {% block extra %} {% endblock %} + {% block file %} + + {% endblock %} + {% block submit %} + + {% endblock %} +
diff --git a/lib/cloudinary/templates/cloudinary_includes.html b/lib/cloudinary/templates/cloudinary_includes.html new file mode 100644 index 00000000..6300c037 --- /dev/null +++ b/lib/cloudinary/templates/cloudinary_includes.html @@ -0,0 +1,14 @@ +{% load staticfiles %} + + + + + + +{% if processing %} + + + + + +{% endif %} diff --git a/lib/cloudinary/templates/cloudinary_js_config.html b/lib/cloudinary/templates/cloudinary_js_config.html new file mode 100644 index 00000000..dc7f4890 --- /dev/null +++ b/lib/cloudinary/templates/cloudinary_js_config.html @@ -0,0 +1,3 @@ + diff --git a/lib/cloudinary/templatetags/__init__.py b/lib/cloudinary/templatetags/__init__.py new file mode 100644 index 00000000..792d6005 --- /dev/null +++ b/lib/cloudinary/templatetags/__init__.py @@ -0,0 +1 @@ +# diff --git a/lib/cloudinary/templatetags/cloudinary.py b/lib/cloudinary/templatetags/cloudinary.py new file mode 100644 index 00000000..febe1e2f --- /dev/null +++ b/lib/cloudinary/templatetags/cloudinary.py @@ -0,0 +1,85 @@ +from __future__ import absolute_import + +import json + +from django import template +from django.forms import Form +from django.utils.safestring import mark_safe + +import cloudinary +from cloudinary import CloudinaryResource, utils, uploader +from cloudinary.forms import CloudinaryJsFileField, cl_init_js_callbacks +from cloudinary.compat import PY3 + +register = template.Library() + + +@register.simple_tag(takes_context=True) +def cloudinary_url(context, source, options_dict=None, **options): + if options_dict is None: + options = dict(**options) + else: + options = dict(options_dict, **options) + try: + if context['request'].is_secure() and 'secure' not in options: + options['secure'] = True + except KeyError: + pass + if not isinstance(source, CloudinaryResource): + source = CloudinaryResource(source) + return source.build_url(**options) + + +@register.simple_tag(name='cloudinary', takes_context=True) +def cloudinary_tag(context, image, options_dict=None, **options): + if options_dict is None: + options = dict(**options) + else: + options = dict(options_dict, **options) + try: + if context['request'].is_secure() and 'secure' not in options: + options['secure'] = True + except KeyError: + pass + if not isinstance(image, CloudinaryResource): + image = CloudinaryResource(image) + return mark_safe(image.image(**options)) + + +@register.simple_tag +def cloudinary_direct_upload_field(field_name="image", request=None): + form = type("OnTheFlyForm", (Form,), {field_name: CloudinaryJsFileField()})() + if request: + cl_init_js_callbacks(form, request) + value = form[field_name] + if not PY3: + value = unicode(value) + return value + + +"""Deprecated - please use cloudinary_direct_upload_field, or a proper form""" +@register.inclusion_tag('cloudinary_direct_upload.html') +def cloudinary_direct_upload(callback_url, **options): + params = utils.build_upload_params(callback=callback_url, **options) + params = utils.sign_request(params, options) + + api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), + upload_prefix=options.get("upload_prefix")) + + return {"params": params, "url": api_url} + + +@register.inclusion_tag('cloudinary_includes.html') +def cloudinary_includes(processing=False): + return {"processing": processing} + + +CLOUDINARY_JS_CONFIG_PARAMS = ("api_key", "cloud_name", "private_cdn", "secure_distribution", "cdn_subdomain") +@register.inclusion_tag('cloudinary_js_config.html') +def cloudinary_js_config(): + config = cloudinary.config() + return dict( + params=json.dumps(dict( + (param, getattr(config, param)) for param in CLOUDINARY_JS_CONFIG_PARAMS if getattr(config, param, None) + )) + ) diff --git a/lib/cloudinary/uploader.py b/lib/cloudinary/uploader.py new file mode 100644 index 00000000..4230f393 --- /dev/null +++ b/lib/cloudinary/uploader.py @@ -0,0 +1,325 @@ +# Copyright Cloudinary +import json +import re +import socket +from os.path import getsize + +import cloudinary +import urllib3 +import certifi +from cloudinary import utils +from cloudinary.api import Error +from cloudinary.compat import string_types +from urllib3.exceptions import HTTPError +from urllib3 import PoolManager + +try: + from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox +except Exception: + def is_appengine_sandbox(): + return False + +try: # Python 2.7+ + from collections import OrderedDict +except ImportError: + from urllib3.packages.ordered_dict import OrderedDict + +if is_appengine_sandbox(): + # AppEngineManager uses AppEngine's URLFetch API behind the scenes + _http = AppEngineManager() +else: + # PoolManager uses a socket-level API behind the scenes + _http = PoolManager( + cert_reqs='CERT_REQUIRED', + ca_certs=certifi.where() + ) + + +def upload(file, **options): + params = utils.build_upload_params(**options) + return call_api("upload", params, file=file, **options) + + +def unsigned_upload(file, upload_preset, **options): + return upload(file, upload_preset=upload_preset, unsigned=True, **options) + + +def upload_image(file, **options): + result = upload(file, **options) + return cloudinary.CloudinaryImage( + result["public_id"], version=str(result["version"]), + format=result.get("format"), metadata=result) + + +def upload_resource(file, **options): + result = upload(file, **options) + return cloudinary.CloudinaryResource( + result["public_id"], version=str(result["version"]), + format=result.get("format"), type=result["type"], resource_type=result["resource_type"], metadata=result) + + +def upload_large(file, **options): + """ Upload large files. """ + upload_id = utils.random_public_id() + with open(file, 'rb') as file_io: + results = None + current_loc = 0 + chunk_size = options.get("chunk_size", 20000000) + file_size = getsize(file) + chunk = file_io.read(chunk_size) + while chunk: + range = "bytes {0}-{1}/{2}".format(current_loc, current_loc + len(chunk) - 1, file_size) + current_loc += len(chunk) + + results = upload_large_part((file, chunk), + http_headers={"Content-Range": range, "X-Unique-Upload-Id": upload_id}, + **options) + options["public_id"] = results.get("public_id") + chunk = file_io.read(chunk_size) + return results + + +def upload_large_part(file, **options): + """ Upload large files. """ + params = utils.build_upload_params(**options) + if 'resource_type' not in options: options['resource_type'] = "raw" + return call_api("upload", params, file=file, **options) + + +def destroy(public_id, **options): + params = { + "timestamp": utils.now(), + "type": options.get("type"), + "invalidate": options.get("invalidate"), + "public_id": public_id + } + return call_api("destroy", params, **options) + + +def rename(from_public_id, to_public_id, **options): + params = { + "timestamp": utils.now(), + "type": options.get("type"), + "overwrite": options.get("overwrite"), + "invalidate": options.get("invalidate"), + "from_public_id": from_public_id, + "to_public_id": to_public_id + } + return call_api("rename", params, **options) + + +def explicit(public_id, **options): + params = utils.build_upload_params(**options) + params["public_id"] = public_id + return call_api("explicit", params, **options) + + +def create_archive(**options): + params = utils.archive_params(**options) + if options.get("target_format") is not None: + params["target_format"] = options.get("target_format") + return call_api("generate_archive", params, **options) + + +def create_zip(**options): + return create_archive(target_format="zip", **options) + + +def generate_sprite(tag, **options): + params = { + "timestamp": utils.now(), + "tag": tag, + "async": options.get("async"), + "notification_url": options.get("notification_url"), + "transformation": utils.generate_transformation_string(fetch_format=options.get("format"), **options)[0] + } + return call_api("sprite", params, **options) + + +def multi(tag, **options): + params = { + "timestamp": utils.now(), + "tag": tag, + "format": options.get("format"), + "async": options.get("async"), + "notification_url": options.get("notification_url"), + "transformation": utils.generate_transformation_string(**options)[0] + } + return call_api("multi", params, **options) + + +def explode(public_id, **options): + params = { + "timestamp": utils.now(), + "public_id": public_id, + "format": options.get("format"), + "notification_url": options.get("notification_url"), + "transformation": utils.generate_transformation_string(**options)[0] + } + return call_api("explode", params, **options) + + +# options may include 'exclusive' (boolean) which causes clearing this tag from all other resources +def add_tag(tag, public_ids=None, **options): + exclusive = options.pop("exclusive", None) + command = "set_exclusive" if exclusive else "add" + return call_tags_api(tag, command, public_ids, **options) + + +def remove_tag(tag, public_ids=None, **options): + return call_tags_api(tag, "remove", public_ids, **options) + + +def replace_tag(tag, public_ids=None, **options): + return call_tags_api(tag, "replace", public_ids, **options) + + +def remove_all_tags(public_ids, **options): + """ + Remove all tags from the specified public IDs. + :param public_ids: the public IDs of the resources to update + :param options: additional options passed to the request + :return: dictionary with a list of public IDs that were updated + """ + return call_tags_api(None, "remove_all", public_ids, **options) + + +def add_context(context, public_ids, **options): + """ + Add a context keys and values. If a particular key already exists, the value associated with the key is updated. + :param context: dictionary of context + :param public_ids: the public IDs of the resources to update + :param options: additional options passed to the request + :return: dictionary with a list of public IDs that were updated + """ + return call_context_api(context, "add", public_ids, **options) + + +def remove_all_context(public_ids, **options): + """ + Remove all custom context from the specified public IDs. + :param public_ids: the public IDs of the resources to update + :param options: additional options passed to the request + :return: dictionary with a list of public IDs that were updated + """ + return call_context_api(None, "remove_all", public_ids, **options) + + +def call_tags_api(tag, command, public_ids=None, **options): + params = { + "timestamp": utils.now(), + "tag": tag, + "public_ids": utils.build_array(public_ids), + "command": command, + "type": options.get("type") + } + return call_api("tags", params, **options) + + +def call_context_api(context, command, public_ids=None, **options): + params = { + "timestamp": utils.now(), + "context": utils.encode_context(context), + "public_ids": utils.build_array(public_ids), + "command": command, + "type": options.get("type") + } + return call_api("context", params, **options) + + +TEXT_PARAMS = ["public_id", + "font_family", + "font_size", + "font_color", + "text_align", + "font_weight", + "font_style", + "background", + "opacity", + "text_decoration" + ] + + +def text(text, **options): + params = {"timestamp": utils.now(), "text": text} + for key in TEXT_PARAMS: + params[key] = options.get(key) + return call_api("text", params, **options) + + +def call_api(action, params, http_headers=None, return_error=False, unsigned=False, file=None, timeout=None, **options): + if http_headers is None: + http_headers = {} + file_io = None + try: + if unsigned: + params = utils.cleanup_params(params) + else: + params = utils.sign_request(params, options) + + param_list = OrderedDict() + for k, v in params.items(): + if isinstance(v, list): + for i in range(len(v)): + param_list["{0}[{1}]".format(k, i)] = v[i] + elif v: + param_list[k] = v + + api_url = utils.cloudinary_api_url(action, **options) + if file: + if isinstance(file, string_types): + if re.match(r'ftp:|https?:|s3:|data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$', file): + # URL + name = None + data = file + else: + # file path + name = file + with open(file, "rb") as opened: + data = opened.read() + elif hasattr(file, 'read') and callable(file.read): + # stream + data = file.read() + name = file.name if hasattr(file, 'name') and isinstance(file.name, str) else "stream" + elif isinstance(file, tuple): + name = None + data = file + else: + # Not a string, not a stream + name = "file" + data = file + + param_list["file"] = (name, data) if name else data + + headers = {"User-Agent": cloudinary.get_user_agent()} + headers.update(http_headers) + + kw = {} + if timeout is not None: + kw['timeout'] = timeout + + code = 200 + try: + response = _http.request("POST", api_url, param_list, headers, **kw) + except HTTPError as e: + raise Error("Unexpected error - {0!r}".format(e)) + except socket.error as e: + raise Error("Socket error: {0!r}".format(e)) + + try: + result = json.loads(response.data.decode('utf-8')) + except Exception as e: + # Error is parsing json + raise Error("Error parsing server response (%d) - %s. Got - %s", response.status, response, e) + + if "error" in result: + if response.status not in [200, 400, 401, 403, 404, 500]: + code = response.status + if return_error: + result["error"]["http_code"] = code + else: + raise Error(result["error"]["message"]) + + return result + finally: + if file_io: file_io.close() diff --git a/lib/cloudinary/utils.py b/lib/cloudinary/utils.py new file mode 100644 index 00000000..507bdad4 --- /dev/null +++ b/lib/cloudinary/utils.py @@ -0,0 +1,912 @@ +# Copyright Cloudinary +import base64 +import copy +import hashlib +import json +import random +import re +import string +import struct +import time +import zlib +from collections import OrderedDict +from datetime import datetime, date +from fractions import Fraction + +import six.moves.urllib.parse +from six import iteritems + +import cloudinary +from cloudinary import auth_token +from cloudinary.compat import PY3, to_bytes, to_bytearray, to_string, string_types, urlparse + +VAR_NAME_RE = r'(\$\([a-zA-Z]\w+\))' + +urlencode = six.moves.urllib.parse.urlencode +unquote = six.moves.urllib.parse.unquote + +""" @deprecated: use cloudinary.SHARED_CDN """ +SHARED_CDN = "res.cloudinary.com" + +DEFAULT_RESPONSIVE_WIDTH_TRANSFORMATION = {"width": "auto", "crop": "limit"} + +RANGE_VALUE_RE = r'^(?P(\d+\.)?\d+)(?P[%pP])?$' +RANGE_RE = r'^(\d+\.)?\d+[%pP]?\.\.(\d+\.)?\d+[%pP]?$' +FLOAT_RE = r'^(\d+)\.(\d+)?$' +__LAYER_KEYWORD_PARAMS = [("font_weight", "normal"), + ("font_style", "normal"), + ("text_decoration", "none"), + ("text_align", None), + ("stroke", "none")] + + +def build_array(arg): + if isinstance(arg, list): + return arg + elif arg is None: + return [] + else: + return [arg] + + +def build_list_of_dicts(val): + """ + Converts a value that can be presented as a list of dict. + + In case top level item is not a list, it is wrapped with a list + + Valid values examples: + - Valid dict: {"k": "v", "k2","v2"} + - List of dict: [{"k": "v"}, {"k2","v2"}] + - JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]' + - List of JSON decodable strings: ['{"k": "v"}', '{"k2","v2"}'] + + Invalid values examples: + - ["not", "a", "dict"] + - [123, None], + - [["another", "list"]] + + :param val: Input value + :type val: Union[list, dict, str] + + :return: Converted(or original) list of dict + :raises: ValueError in case value cannot be converted to a list of dict + """ + if val is None: + return [] + + if isinstance(val, str): + # use OrderedDict to preserve order + val = json.loads(val, object_pairs_hook=OrderedDict) + + if isinstance(val, dict): + val = [val] + + for index, item in enumerate(val): + if isinstance(item, str): + # use OrderedDict to preserve order + val[index] = json.loads(item, object_pairs_hook=OrderedDict) + if not isinstance(val[index], dict): + raise ValueError("Expected a list of dicts") + return val + + +def encode_double_array(array): + array = build_array(array) + if len(array) > 0 and isinstance(array[0], list): + return "|".join([",".join([str(i) for i in build_array(inner)]) for inner in array]) + else: + return ",".join([str(i) for i in array]) + + +def encode_dict(arg): + if isinstance(arg, dict): + if PY3: + items = arg.items() + else: + items = arg.iteritems() + return "|".join((k + "=" + v) for k, v in items) + else: + return arg + + +def encode_context(context): + """ + :param context: dict of context to be encoded + :return: a joined string of all keys and values properly escaped and separated by a pipe character + """ + + if not isinstance(context, dict): + return context + + return "|".join(("{}={}".format(k, v.replace("=", "\\=").replace("|", "\\|"))) for k, v in iteritems(context)) + + +def json_encode(value): + """ + Converts value to a json encoded string + + :param value: value to be encoded + + :return: JSON encoded string + """ + return json.dumps(value, default=__json_serializer, separators=(',', ':')) + + +def generate_transformation_string(**options): + responsive_width = options.pop("responsive_width", cloudinary.config().responsive_width) + size = options.pop("size", None) + if size: + options["width"], options["height"] = size.split("x") + width = options.get("width") + height = options.get("height") + has_layer = ("underlay" in options) or ("overlay" in options) + + crop = options.pop("crop", None) + angle = ".".join([str(value) for value in build_array(options.pop("angle", None))]) + no_html_sizes = has_layer or angle or crop == "fit" or crop == "limit" or responsive_width + + if width and (str(width).startswith("auto") or str(width) == "ow" or is_fraction(width) or no_html_sizes): + del options["width"] + if height and (str(height) == "oh" or is_fraction(height) or no_html_sizes): + del options["height"] + + background = options.pop("background", None) + if background: + background = background.replace("#", "rgb:") + color = options.pop("color", None) + if color: + color = color.replace("#", "rgb:") + + base_transformations = build_array(options.pop("transformation", None)) + if any(isinstance(bs, dict) for bs in base_transformations): + def recurse(bs): + if isinstance(bs, dict): + return generate_transformation_string(**bs)[0] + else: + return generate_transformation_string(transformation=bs)[0] + base_transformations = list(map(recurse, base_transformations)) + named_transformation = None + else: + named_transformation = ".".join(base_transformations) + base_transformations = [] + + effect = options.pop("effect", None) + if isinstance(effect, list): + effect = ":".join([str(x) for x in effect]) + elif isinstance(effect, dict): + effect = ":".join([str(x) for x in list(effect.items())[0]]) + + border = options.pop("border", None) + if isinstance(border, dict): + border_color = border.get("color", "black").replace("#", "rgb:") + border = "%(width)spx_solid_%(color)s" % {"color": border_color, + "width": str(border.get("width", 2))} + + flags = ".".join(build_array(options.pop("flags", None))) + dpr = options.pop("dpr", cloudinary.config().dpr) + duration = norm_range_value(options.pop("duration", None)) + start_offset = norm_range_value(options.pop("start_offset", None)) + end_offset = norm_range_value(options.pop("end_offset", None)) + offset = split_range(options.pop("offset", None)) + if offset: + start_offset = norm_range_value(offset[0]) + end_offset = norm_range_value(offset[1]) + + video_codec = process_video_codec_param(options.pop("video_codec", None)) + + aspect_ratio = options.pop("aspect_ratio", None) + if isinstance(aspect_ratio, Fraction): + aspect_ratio = str(aspect_ratio.numerator) + ":" + str(aspect_ratio.denominator) + + overlay = process_layer(options.pop("overlay", None), "overlay") + underlay = process_layer(options.pop("underlay", None), "underlay") + if_value = process_conditional(options.pop("if", None)) + + params = { + "a": normalize_expression(angle), + "ar": normalize_expression(aspect_ratio), + "b": background, + "bo": border, + "c": crop, + "co": color, + "dpr": normalize_expression(dpr), + "du": normalize_expression(duration), + "e": normalize_expression(effect), + "eo": normalize_expression(end_offset), + "fl": flags, + "h": normalize_expression(height), + "l": overlay, + "o": normalize_expression(options.pop('opacity',None)), + "q": normalize_expression(options.pop('quality',None)), + "r": normalize_expression(options.pop('radius',None)), + "so": normalize_expression(start_offset), + "t": named_transformation, + "u": underlay, + "w": normalize_expression(width), + "x": normalize_expression(options.pop('x',None)), + "y": normalize_expression(options.pop('y',None)), + "vc": video_codec, + "z": normalize_expression(options.pop('zoom',None)) + } + simple_params = { + "ac": "audio_codec", + "af": "audio_frequency", + "br": "bit_rate", + "cs": "color_space", + "d": "default_image", + "dl": "delay", + "dn": "density", + "f": "fetch_format", + "g": "gravity", + "ki": "keyframe_interval", + "p": "prefix", + "pg": "page", + "sp": "streaming_profile", + "vs": "video_sampling", + } + + for param, option in simple_params.items(): + params[param] = options.pop(option, None) + + variables = options.pop('variables',{}) + var_params = [] + for key,value in options.items(): + if re.match(r'^\$', key): + var_params.append(u"{0}_{1}".format(key, normalize_expression(str(value)))) + + var_params.sort() + + if variables: + for var in variables: + var_params.append(u"{0}_{1}".format(var[0], normalize_expression(str(var[1])))) + + + variables = ','.join(var_params) + + sorted_params = sorted([param + "_" + str(value) for param, value in params.items() if (value or value == 0)]) + if variables: + sorted_params.insert(0, str(variables)) + + if if_value is not None: + sorted_params.insert(0, "if_" + str(if_value)) + transformation = ",".join(sorted_params) + if "raw_transformation" in options: + transformation = transformation + "," + options.pop("raw_transformation") + transformations = base_transformations + [transformation] + if responsive_width: + responsive_width_transformation = cloudinary.config().responsive_width_transformation \ + or DEFAULT_RESPONSIVE_WIDTH_TRANSFORMATION + transformations += [generate_transformation_string(**responsive_width_transformation)[0]] + url = "/".join([trans for trans in transformations if trans]) + + if str(width).startswith("auto") or responsive_width: + options["responsive"] = True + if dpr == "auto": + options["hidpi"] = True + return url, options + + +def is_fraction(width): + width = str(width) + return re.match(FLOAT_RE, width) and float(width) < 1 + + +def split_range(range): + if (isinstance(range, list) or isinstance(range, tuple)) and len(range) >= 2: + return [range[0], range[-1]] + elif isinstance(range, string_types) and re.match(RANGE_RE, range): + return range.split("..", 1) + else: + return None + + +def norm_range_value(value): + if value is None: return None + + match = re.match(RANGE_VALUE_RE, str(value)) + + if match is None: return None + + modifier = '' + if match.group('modifier') is not None: + modifier = 'p' + return match.group('value') + modifier + + +def process_video_codec_param(param): + out_param = param + if isinstance(out_param, dict): + out_param = param['codec'] + if 'profile' in param: + out_param = out_param + ':' + param['profile'] + if 'level' in param: + out_param = out_param + ':' + param['level'] + return out_param + + +def cleanup_params(params): + return dict([(k, __safe_value(v)) for (k, v) in params.items() if v is not None and not v == ""]) + + +def sign_request(params, options): + api_key = options.get("api_key", cloudinary.config().api_key) + if not api_key: raise ValueError("Must supply api_key") + api_secret = options.get("api_secret", cloudinary.config().api_secret) + if not api_secret: raise ValueError("Must supply api_secret") + + params = cleanup_params(params) + params["signature"] = api_sign_request(params, api_secret) + params["api_key"] = api_key + + return params + + +def api_sign_request(params_to_sign, api_secret): + params = [(k + "=" + (",".join(v) if isinstance(v, list) else str(v))) for k, v in params_to_sign.items() if v] + to_sign = "&".join(sorted(params)) + return hashlib.sha1(to_bytes(to_sign + api_secret)).hexdigest() + + +def breakpoint_settings_mapper(breakpoint_settings): + breakpoint_settings = copy.deepcopy(breakpoint_settings) + transformation = breakpoint_settings.get("transformation") + if transformation is not None: + breakpoint_settings["transformation"], _ = generate_transformation_string(**transformation) + return breakpoint_settings + + +def generate_responsive_breakpoints_string(breakpoints): + if breakpoints is None: + return None + breakpoints = build_array(breakpoints) + return json.dumps(list(map(breakpoint_settings_mapper, breakpoints))) + + +def finalize_source(source, format, url_suffix): + source = re.sub(r'([^:])/+', r'\1/', source) + if re.match(r'^https?:/', source): + source = smart_escape(source) + source_to_sign = source + else: + source = unquote(source) + if not PY3: source = source.encode('utf8') + source = smart_escape(source) + source_to_sign = source + if url_suffix is not None: + if re.search(r'[\./]', url_suffix): raise ValueError("url_suffix should not include . or /") + source = source + "/" + url_suffix + if format is not None: + source = source + "." + format + source_to_sign = source_to_sign + "." + format + + return source, source_to_sign + + +def finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten): + upload_type = type or "upload" + if url_suffix is not None: + if resource_type == "image" and upload_type == "upload": + resource_type = "images" + upload_type = None + elif resource_type == "raw" and upload_type == "upload": + resource_type = "files" + upload_type = None + else: + raise ValueError("URL Suffix only supported for image/upload and raw/upload") + + if use_root_path: + if (resource_type == "image" and upload_type == "upload") or (resource_type == "images" and upload_type is None): + resource_type = None + upload_type = None + else: + raise ValueError("Root path only supported for image/upload") + + if shorten and resource_type == "image" and upload_type == "upload": + resource_type = "iu" + upload_type = None + + return resource_type, upload_type + + +def unsigned_download_url_prefix(source, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, secure, + secure_distribution): + """cdn_subdomain and secure_cdn_subdomain + 1) Customers in shared distribution (e.g. res.cloudinary.com) + if cdn_domain is true uses res-[1-5].cloudinary.com for both http and https. Setting secure_cdn_subdomain to false disables this for https. + 2) Customers with private cdn + if cdn_domain is true uses cloudname-res-[1-5].cloudinary.com for http + if secure_cdn_domain is true uses cloudname-res-[1-5].cloudinary.com for https (please contact support if you require this) + 3) Customers with cname + if cdn_domain is true uses a[1-5].cname for http. For https, uses the same naming scheme as 1 for shared distribution and as 2 for private distribution.""" + shared_domain = not private_cdn + shard = __crc(source) + if secure: + if secure_distribution is None or secure_distribution == cloudinary.OLD_AKAMAI_SHARED_CDN: + secure_distribution = cloud_name + "-res.cloudinary.com" if private_cdn else cloudinary.SHARED_CDN + + shared_domain = shared_domain or secure_distribution == cloudinary.SHARED_CDN + if secure_cdn_subdomain is None and shared_domain: + secure_cdn_subdomain = cdn_subdomain + + if secure_cdn_subdomain: + secure_distribution = re.sub('res.cloudinary.com', "res-" + shard + ".cloudinary.com", secure_distribution) + + prefix = "https://" + secure_distribution + elif cname: + subdomain = "a" + shard + "." if cdn_subdomain else "" + prefix = "http://" + subdomain + cname + else: + subdomain = cloud_name + "-res" if private_cdn else "res" + if cdn_subdomain: subdomain = subdomain + "-" + shard + prefix = "http://" + subdomain + ".cloudinary.com" + + if shared_domain: prefix += "/" + cloud_name + + return prefix + + +def merge(*dict_args): + result = None + for dictionary in dict_args: + if dictionary is not None: + if result is None: + result = dictionary.copy() + else: + result.update(dictionary) + return result + + +def cloudinary_url(source, **options): + original_source = source + + type = options.pop("type", "upload") + if type == 'fetch': + options["fetch_format"] = options.get("fetch_format", options.pop("format", None)) + transformation, options = generate_transformation_string(**options) + + resource_type = options.pop("resource_type", "image") + version = options.pop("version", None) + format = options.pop("format", None) + cdn_subdomain = options.pop("cdn_subdomain", cloudinary.config().cdn_subdomain) + secure_cdn_subdomain = options.pop("secure_cdn_subdomain", cloudinary.config().secure_cdn_subdomain) + cname = options.pop("cname", cloudinary.config().cname) + shorten = options.pop("shorten", cloudinary.config().shorten) + + cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name or None) + if cloud_name is None: + raise ValueError("Must supply cloud_name in tag or in configuration") + secure = options.pop("secure", cloudinary.config().secure) + private_cdn = options.pop("private_cdn", cloudinary.config().private_cdn) + secure_distribution = options.pop("secure_distribution", cloudinary.config().secure_distribution) + sign_url = options.pop("sign_url", cloudinary.config().sign_url) + api_secret = options.pop("api_secret", cloudinary.config().api_secret) + url_suffix = options.pop("url_suffix", None) + use_root_path = options.pop("use_root_path", cloudinary.config().use_root_path) + auth_token = options.pop("auth_token", None) + if auth_token is not False: + auth_token = merge(cloudinary.config().auth_token, auth_token) + + if (not source) or type == "upload" and re.match(r'^https?:', source): + return original_source, options + + resource_type, type = finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten) + source, source_to_sign = finalize_source(source, format, url_suffix) + + if source_to_sign.find("/") >= 0 \ + and not re.match(r'^https?:/', source_to_sign) \ + and not re.match(r'^v[0-9]+', source_to_sign) \ + and not version: + version = "1" + if version: version = "v" + str(version) + + transformation = re.sub(r'([^:])/+', r'\1/', transformation) + + signature = None + if sign_url and not auth_token: + to_sign = "/".join(__compact([transformation, source_to_sign])) + signature = "s--" + to_string( + base64.urlsafe_b64encode(hashlib.sha1(to_bytes(to_sign + api_secret)).digest())[0:8]) + "--" + + prefix = unsigned_download_url_prefix(source, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, + secure, secure_distribution) + source = "/".join(__compact([prefix, resource_type, type, signature, transformation, version, source])) + if sign_url and auth_token: + path = urlparse(source).path + token = cloudinary.auth_token.generate( **merge(auth_token, {"url": path})) + source = "%s?%s" % (source, token) + return source, options + + +def cloudinary_api_url(action='upload', **options): + cloudinary_prefix = options.get("upload_prefix", cloudinary.config().upload_prefix) or "https://api.cloudinary.com" + cloud_name = options.get("cloud_name", cloudinary.config().cloud_name) + if not cloud_name: raise ValueError("Must supply cloud_name") + resource_type = options.get("resource_type", "image") + return "/".join([cloudinary_prefix, "v1_1", cloud_name, resource_type, action]) + + +# Based on ruby's CGI::unescape. In addition does not escape / : +def smart_escape(source,unsafe = r"([^a-zA-Z0-9_.\-\/:]+)"): + def pack(m): + return to_bytes('%' + "%".join(["%02X" % x for x in struct.unpack('B' * len(m.group(1)), m.group(1))]).upper()) + return to_string(re.sub(to_bytes(unsafe), pack, to_bytes(source))) + + +def random_public_id(): + return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(16)) + + +def signed_preloaded_image(result): + filename = ".".join([x for x in [result["public_id"], result["format"]] if x]) + path = "/".join([result["resource_type"], "upload", "v" + str(result["version"]), filename]) + return path + "#" + result["signature"] + + +def now(): + return str(int(time.time())) + + +def private_download_url(public_id, format, **options): + cloudinary_params = sign_request({ + "timestamp": now(), + "public_id": public_id, + "format": format, + "type": options.get("type"), + "attachment": options.get("attachment"), + "expires_at": options.get("expires_at") + }, options) + + return cloudinary_api_url("download", **options) + "?" + urlencode(cloudinary_params) + + +def zip_download_url(tag, **options): + cloudinary_params = sign_request({ + "timestamp": now(), + "tag": tag, + "transformation": generate_transformation_string(**options)[0] + }, options) + + return cloudinary_api_url("download_tag.zip", **options) + "?" + urlencode(cloudinary_params) + + +def bracketize_seq(params): + url_params = dict() + for param_name in params: + param_value = params[param_name] + if isinstance(param_value, list): + param_name += "[]" + url_params[param_name] = param_value + return url_params + + +def download_archive_url(**options): + params = options.copy() + params.update(mode="download") + cloudinary_params = sign_request(archive_params(**params), options) + return cloudinary_api_url("generate_archive", **options) + "?" + urlencode(bracketize_seq(cloudinary_params), True) + + +def download_zip_url(**options): + new_options = options.copy() + new_options.update(target_format="zip") + return download_archive_url(**new_options) + +def generate_auth_token(**options): + token_options = merge(cloudinary.config().auth_token, options) + return auth_token.generate(**token_options) + +def archive_params(**options): + if options.get("timestamp") is None: + timestamp = now() + else: + timestamp = options.get("timestamp") + params = { + "allow_missing": options.get("allow_missing"), + "async": options.get("async"), + "expires_at": options.get("expires_at"), + "flatten_folders": options.get("flatten_folders"), + "flatten_transformations": options.get("flatten_transformations"), + "keep_derived": options.get("keep_derived"), + "mode": options.get("mode"), + "notification_url": options.get("notification_url"), + "phash": options.get("phash"), + "prefixes": options.get("prefixes") and build_array(options.get("prefixes")), + "public_ids": options.get("public_ids") and build_array(options.get("public_ids")), + "skip_transformation_name": options.get("skip_transformation_name"), + "tags": options.get("tags") and build_array(options.get("tags")), + "target_format": options.get("target_format"), + "target_public_id": options.get("target_public_id"), + "target_tags": options.get("target_tags") and build_array(options.get("target_tags")), + "timestamp": timestamp, + "transformations": build_eager(options.get("transformations")), + "type": options.get("type"), + "use_original_filename": options.get("use_original_filename"), + } + return params + + +def build_eager(transformations): + if transformations is None: + return None + eager = [] + for tr in build_array(transformations): + if isinstance(tr, string_types): + single_eager = tr + else: + ext = tr.get("format") + single_eager = "/".join([x for x in [generate_transformation_string(**tr)[0], ext] if x]) + eager.append(single_eager) + return "|".join(eager) + + +def build_custom_headers(headers): + if headers is None: + return None + elif isinstance(headers, list): + pass + elif isinstance(headers, dict): + headers = [k + ": " + v for k, v in headers.items()] + else: + return headers + return "\n".join(headers) + + +def build_upload_params(**options): + params = {"timestamp": now(), + "transformation": generate_transformation_string(**options)[0], + "public_id": options.get("public_id"), + "callback": options.get("callback"), + "format": options.get("format"), + "type": options.get("type"), + "backup": options.get("backup"), + "faces": options.get("faces"), + "image_metadata": options.get("image_metadata"), + "exif": options.get("exif"), + "colors": options.get("colors"), + "headers": build_custom_headers(options.get("headers")), + "eager": build_eager(options.get("eager")), + "use_filename": options.get("use_filename"), + "unique_filename": options.get("unique_filename"), + "discard_original_filename": options.get("discard_original_filename"), + "invalidate": options.get("invalidate"), + "notification_url": options.get("notification_url"), + "eager_notification_url": options.get("eager_notification_url"), + "eager_async": options.get("eager_async"), + "proxy": options.get("proxy"), + "folder": options.get("folder"), + "overwrite": options.get("overwrite"), + "tags": options.get("tags") and ",".join(build_array(options["tags"])), + "allowed_formats": options.get("allowed_formats") and ",".join(build_array(options["allowed_formats"])), + "face_coordinates": encode_double_array(options.get("face_coordinates")), + "custom_coordinates": encode_double_array(options.get("custom_coordinates")), + "context": encode_context(options.get("context")), + "moderation": options.get("moderation"), + "raw_convert": options.get("raw_convert"), + "quality_override": options.get("quality_override"), + "ocr": options.get("ocr"), + "categorization": options.get("categorization"), + "detection": options.get("detection"), + "similarity_search": options.get("similarity_search"), + "background_removal": options.get("background_removal"), + "upload_preset": options.get("upload_preset"), + "phash": options.get("phash"), + "return_delete_token": options.get("return_delete_token"), + "auto_tagging": options.get("auto_tagging") and str(options.get("auto_tagging")), + "responsive_breakpoints": generate_responsive_breakpoints_string(options.get("responsive_breakpoints")), + "async": options.get("async"), + "access_control": options.get("access_control") and json_encode(build_list_of_dicts(options.get("access_control")))} + return params + + +def __process_text_options(layer, layer_parameter): + font_family = layer.get("font_family") + font_size = layer.get("font_size") + keywords = [] + for attr, default_value in __LAYER_KEYWORD_PARAMS: + attr_value = layer.get(attr) + if attr_value != default_value and attr_value is not None: + keywords.append(attr_value) + + letter_spacing = layer.get("letter_spacing") + if letter_spacing is not None: + keywords.append("letter_spacing_" + str(letter_spacing)) + + line_spacing = layer.get("line_spacing") + if line_spacing is not None: + keywords.append("line_spacing_" + str(line_spacing)) + + if font_size is None and font_family is None and len(keywords) == 0: + return None + + if font_family is None: + raise ValueError("Must supply font_family for text in " + layer_parameter) + + if font_size is None: + raise ValueError("Must supply font_size for text in " + layer_parameter) + + keywords.insert(0, font_size) + keywords.insert(0, font_family) + + return '_'.join([str(k) for k in keywords]) + + +def process_layer(layer, layer_parameter): + if isinstance(layer, string_types) and layer.startswith("fetch:"): + layer = {"url": layer[len('fetch:'):]} + if not isinstance(layer, dict): + return layer + + resource_type = layer.get("resource_type") + text = layer.get("text") + type = layer.get("type") + public_id = layer.get("public_id") + format = layer.get("format") + fetch = layer.get("url") + components = list() + + if text is not None and resource_type is None: + resource_type = "text" + + if fetch and resource_type is None: + resource_type = "fetch" + + if public_id is not None and format is not None: + public_id = public_id + "." + format + + if public_id is None and resource_type != "text" and resource_type != "fetch": + raise ValueError("Must supply public_id for for non-text " + layer_parameter) + + if resource_type is not None and resource_type != "image": + components.append(resource_type) + + if type is not None and type != "upload": + components.append(type) + + if resource_type == "text" or resource_type == "subtitles": + if public_id is None and text is None: + raise ValueError("Must supply either text or public_id in " + layer_parameter) + + text_options = __process_text_options(layer, layer_parameter) + + if text_options is not None: + components.append(text_options) + + if public_id is not None: + public_id = public_id.replace("/", ':') + components.append(public_id) + + if text is not None: + var_pattern = VAR_NAME_RE + match = re.findall(var_pattern,text) + + parts= filter(lambda p: p is not None, re.split(var_pattern,text)) + encoded_text = [] + for part in parts: + if re.match(var_pattern,part): + encoded_text.append(part) + else: + encoded_text.append(smart_escape(smart_escape(part, r"([,/])"))) + + text = ''.join(encoded_text) + # text = text.replace("%2C", "%252C") + # text = text.replace("/", "%252F") + components.append(text) + elif resource_type == "fetch": + b64 = base64_encode_url(fetch) + components.append(b64) + else: + public_id = public_id.replace("/", ':') + components.append(public_id) + + return ':'.join(components) + +IF_OPERATORS = { + "=": 'eq', + "!=": 'ne', + "<": 'lt', + ">": 'gt', + "<=": 'lte', + ">=": 'gte', + "&&": 'and', + "||": 'or', + "*": 'mul', + "/": 'div', + "+": 'add', + "-": 'sub' +} + +PREDEFINED_VARS = { + "aspect_ratio": "ar", + "current_page": "cp", + "face_count": "fc", + "height": "h", + "initial_aspect_ratio": "iar", + "initial_height": "ih", + "initial_width": "iw", + "page_count": "pc", + "page_x": "px", + "page_y": "py", + "tags": "tags", + "width": "w" +} + +replaceRE = "((\\|\\||>=|<=|&&|!=|>|=|<|/|-|\\+|\\*)(?=[ _])|" + '|'.join(PREDEFINED_VARS.keys())+ ")" + + +def translate_if(match): + name = match.group(0) + return IF_OPERATORS.get(name, + PREDEFINED_VARS.get(name, + name)) + +def process_conditional(conditional): + if conditional is None: + return conditional + result = normalize_expression(conditional) + return result + +def normalize_expression(expression): + if re.match(r'^!.+!$',str(expression)): # quoted string + return expression + elif expression: + result = str(expression) + result = re.sub(replaceRE, translate_if, result) + result = re.sub('[ _]+', '_', result) + return result + else: + return expression + +def __join_pair(key, value): + if value is None or value == "": + return None + elif value is True: + return key + else: + return u"{0}=\"{1}\"".format(key, value) + + +def html_attrs(attrs, only=None): + return ' '.join(sorted([__join_pair(key, value) for key, value in attrs.items() if only is None or key in only])) + + +def __safe_value(v): + if isinstance(v, bool): + return "1" if v else "0" + else: + return v + + +def __crc(source): + return str((zlib.crc32(to_bytearray(source)) & 0xffffffff) % 5 + 1) + + +def __compact(array): + return filter(lambda x: x, array) + + +def base64_encode_url(url): + """ + Returns the Base64-decoded version of url. + The method tries to unquote the url because quoting it + + :param str url: + the url to encode. the value is URIdecoded and then + re-encoded before converting to base64 representation + + """ + + try: + url = unquote(url) + except: + pass + url = smart_escape(url) + b64 = base64.b64encode(url.encode('utf-8')) + return b64.decode('ascii') + + +def __json_serializer(obj): + """JSON serializer for objects not serializable by default json code""" + if isinstance(obj, (datetime, date)): + return obj.isoformat() + raise TypeError("Object of type %s is not JSON serializable" % type(obj))