UNPKG

xmp-js

Version:

Read and parse XMP from JPEG

2 lines (1 loc) 2.33 kB
"use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _createClass(e,r,t){return r&&_defineProperties(e.prototype,r),t&&_defineProperties(e,t),e}var XMP=function(){function e(r){_classCallCheck(this,e),this.buffer=null,r instanceof ArrayBuffer?this.buffer=r:r instanceof Uint8Array?this.buffer=r.buffer:("string"==typeof r||r instanceof String)&&this.fromDataUri(r)}return _createClass(e,[{key:"fromDataUri",value:function(r){this.buffer=e.dataUriToBuffer(r)}},{key:"find",value:function(){return e.find(this.buffer)}},{key:"parse",value:function(){var r=this.find();return e.parse(r)}}],[{key:"dataUriToBuffer",value:function(e){for(var r=atob(e.split(",")[1]),t=r.length,n=new ArrayBuffer(t),f=new Uint8Array(n),a=0;a<t;a++)f[a]=r.charCodeAt(a);return n}},{key:"find",value:function(r){var t;r instanceof ArrayBuffer?t=r:r instanceof Uint8Array?this.buffer=r.buffer:("string"==typeof r||r instanceof String)&&(t=e.dataUriToBuffer(r));var n=new DataView(t);if(65496!==n.getUint16(0,!1))return console.warn("not valid JPEG"),null;for(var f="<x:xmpmeta"[0],a="<x:xmpmeta".length,i=t.byteLength-a,o="x:xmpmeta>"[0],u="x:xmpmeta>".length,s=t.byteLength-u,c=2,l=c+a,g=!1;c<i;){if(String.fromCharCode(n.getUint8(c))===f&&"<x:xmpmeta"==e.stringFromBuffer(n,c,a)){g=!0;break}c++}if(!g)return console.warn("XMP not found"),null;for(;l<s&&(String.fromCharCode(n.getUint8(l))!==o||"x:xmpmeta>"!=e.stringFromBuffer(n,l,u));)l++;return l+=u,e.stringFromBuffer(n,c,l-c)}},{key:"stringFromBuffer",value:function(e,r,t){for(var n="",f=r;f<r+t;f++)n+=String.fromCharCode(e.getUint8(f));return n}},{key:"parse",value:function(e){if(!e)return null;var r={};return["title","description","rights","creator","subject"].forEach((function(t){var n=new RegExp("<dc:".concat(t,">([\\s\\S]*?)</dc:").concat(t,">"),"gim").exec(e);if(n&&0!==n.length){var f=n[1].trim();if(0===f.toLowerCase().indexOf("<rdf:bag>")){for(var a=new RegExp("<rdf:li>([\\s\\S]*?)</rdf:li>","gim"),i=a.exec(f),o=[];i;)o.push(i[1]),i=a.exec(f);r[t]=o}else r[t]=f.replace(/<[^>]*>?/gm,"").trim()}})),r}}]),e}();module.exports=XMP;