promethee 1.3.26 → 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,6 @@
1
+ /*! 12.2.13 */
2
+ /*! FileAPI 2.0.7 - BSD | git://github.com/mailru/FileAPI.git
3
+ * FileAPI — a set of javascript tools for working with files. Multiupload, drag'n'drop and chunked file upload. Images: crop, resize and auto orientation by EXIF.
4
+ */
5
+ !function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.Blob&&function(){try{return Boolean(new Blob)}catch(a){return!1}}(),d=c&&a.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(a){return!1}}(),e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,f=(c||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,f,g,h,i,j;for(b=a.split(",")[0].indexOf("base64")>=0?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]),f=new ArrayBuffer(b.length),g=new Uint8Array(f),h=0;h<b.length;h+=1)g[h]=b.charCodeAt(h);return i=a.split(",")[0].split(":")[1].split(";")[0],c?new Blob([d?g:f],{type:i}):(j=new e,j.append(f),j.getBlob(i))};a.HTMLCanvasElement&&!b.toBlob&&(b.mozGetAsFile?b.toBlob=function(a,c,d){a(d&&b.toDataURL&&f?f(this.toDataURL(c,d)):this.mozGetAsFile("blob",c))}:b.toDataURL&&f&&(b.toBlob=function(a,b,c){a(f(this.toDataURL(b,c)))})),a.dataURLtoBlob=f}(window),function(a,b){"use strict";function c(a,b,c,d,e){var f={type:c.type||c,target:a,result:d};S(f,e),b(f)}function d(a){return u&&!!u.prototype["readAs"+a]}function e(a,e,f,g){if(Y.isBlob(a)&&d(f)){var h=new u;T(h,M,function j(b){var d=b.type;"progress"==d?c(a,e,b,b.target.result,{loaded:b.loaded,total:b.total}):"loadend"==d?(U(h,M,j),h=null):c(a,e,b,b.target.result)});try{g?h["readAs"+f](a,g):h["readAs"+f](a)}catch(i){c(a,e,"error",b,{error:i.toString()})}}else c(a,e,"error",b,{error:"FileReader_not_support_"+f})}function f(a,b){if(!a.type&&a.size%4096===0&&a.size<=102400)if(u)try{var c=new u;V(c,M,function(a){var d="error"!=a.type;b(d),d&&c.abort()}),c.readAsDataURL(a)}catch(d){b(!1)}else b(null);else b(!0)}function g(a){var b;return a.getAsEntry?b=a.getAsEntry():a.webkitGetAsEntry&&(b=a.webkitGetAsEntry()),b}function h(a,b){if(a)if(a.isFile)a.file(function(c){c.fullPath=a.fullPath,b(!1,[c])},function(a){b("FileError.code: "+a.code)});else if(a.isDirectory){var c=a.createReader(),d=[];c.readEntries(function(a){Y.afor(a,function(a,c){h(c,function(c,e){c?Y.log(c):d=d.concat(e),a?a():b(!1,d)})})},function(a){b("directory_reader: "+a)})}else h(g(a),b);else b("invalid entry")}function i(a){var b={};return R(a,function(a,c){a&&"object"==typeof a&&void 0===a.nodeType&&(a=S({},a)),b[c]=a}),b}function j(a){return F.test(a&&a.tagName)}function k(a){return(a.originalEvent||a||"").dataTransfer||{}}function l(a){var b;for(b in a)if(a.hasOwnProperty(b)&&!(a[b]instanceof Object||"overlay"===b||"filter"===b))return!0;return!1}var m=1,n=function(){},o=a.document,p=o.doctype||{},q=a.navigator.userAgent,r=a.createObjectURL&&a||a.URL&&URL.revokeObjectURL&&URL||a.webkitURL&&webkitURL,s=a.Blob,t=a.File,u=a.FileReader,v=a.FormData,w=a.XMLHttpRequest,x=a.jQuery,y=!(!(t&&u&&(a.Uint8Array||v||w.prototype.sendAsBinary))||/safari\//i.test(q)&&!/chrome\//i.test(q)&&/windows/i.test(q)),z=y&&"withCredentials"in new w,A=y&&!!s&&!!(s.prototype.webkitSlice||s.prototype.mozSlice||s.prototype.slice),B=a.dataURLtoBlob,C=/img/i,D=/canvas/i,E=/img|canvas/i,F=/input/i,G=/^data:[^,]+,/,H={}.toString,I=a.Math,J=function(b){return b=new a.Number(I.pow(1024,b)),b.from=function(a){return I.round(a*this)},b},K={},L=[],M="abort progress error load loadend",N="status statusText readyState response responseXML responseText responseBody".split(" "),O="currentTarget",P="preventDefault",Q=function(a){return a&&"length"in a},R=function(a,b,c){if(a)if(Q(a))for(var d=0,e=a.length;e>d;d++)d in a&&b.call(c,a[d],d,a);else for(var f in a)a.hasOwnProperty(f)&&b.call(c,a[f],f,a)},S=function(a){for(var b=arguments,c=1,d=function(b,c){a[c]=b};c<b.length;c++)R(b[c],d);return a},T=function(a,b,c){if(a){var d=Y.uid(a);K[d]||(K[d]={});var e=u&&a&&a instanceof u;R(b.split(/\s+/),function(b){x&&!e?x.event.add(a,b,c):(K[d][b]||(K[d][b]=[]),K[d][b].push(c),a.addEventListener?a.addEventListener(b,c,!1):a.attachEvent?a.attachEvent("on"+b,c):a["on"+b]=c)})}},U=function(a,b,c){if(a){var d=Y.uid(a),e=K[d]||{},f=u&&a&&a instanceof u;R(b.split(/\s+/),function(b){if(x&&!f)x.event.remove(a,b,c);else{for(var d=e[b]||[],g=d.length;g--;)if(d[g]===c){d.splice(g,1);break}a.addEventListener?a.removeEventListener(b,c,!1):a.detachEvent?a.detachEvent("on"+b,c):a["on"+b]=null}})}},V=function(a,b,c){T(a,b,function d(e){U(a,b,d),c(e)})},W=function(b){return b.target||(b.target=a.event&&a.event.srcElement||o),3===b.target.nodeType&&(b.target=b.target.parentNode),b},X=function(a){var b=o.createElement("input");return b.setAttribute("type","file"),a in b},Y={version:"2.0.7",cors:!1,html5:!0,media:!1,formData:!0,multiPassResize:!0,debug:!1,pingUrl:!1,multiFlash:!1,flashAbortTimeout:0,withCredentials:!0,staticPath:"./dist/",flashUrl:0,flashImageUrl:0,postNameConcat:function(a,b){return a+(null!=b?"["+b+"]":"")},ext2mime:{jpg:"image/jpeg",tif:"image/tiff",txt:"text/plain"},accept:{"image/*":"art bm bmp dwg dxf cbr cbz fif fpx gif ico iefs jfif jpe jpeg jpg jps jut mcf nap nif pbm pcx pgm pict pm png pnm qif qtif ras rast rf rp svf tga tif tiff xbm xbm xpm xwd","audio/*":"m4a flac aac rm mpa wav wma ogg mp3 mp2 m3u mod amf dmf dsm far gdm imf it m15 med okt s3m stm sfx ult uni xm sid ac3 dts cue aif aiff wpl ape mac mpc mpp shn wv nsf spc gym adplug adx dsp adp ymf ast afc hps xs","video/*":"m4v 3gp nsv ts ty strm rm rmvb m3u ifo mov qt divx xvid bivx vob nrg img iso pva wmv asf asx ogm m2v avi bin dat dvr-ms mpg mpeg mp4 mkv avc vp3 svq3 nuv viv dv fli flv wpl"},uploadRetry:0,networkDownRetryTimeout:5e3,chunkSize:0,chunkUploadRetry:0,chunkNetworkDownRetryTimeout:2e3,KB:J(1),MB:J(2),GB:J(3),TB:J(4),EMPTY_PNG:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=",expando:"fileapi"+(new Date).getTime(),uid:function(a){return a?a[Y.expando]=a[Y.expando]||Y.uid():(++m,Y.expando+m)},log:function(){Y.debug&&Y._supportConsoleLog&&(Y._supportConsoleLogApply?console.log.apply(console,arguments):console.log([].join.call(arguments," ")))},newImage:function(a,b){var c=o.createElement("img");return b&&Y.event.one(c,"error load",function(a){b("error"==a.type,c),c=null}),c.src=a,c},getXHR:function(){var b;if(w)b=new w;else if(a.ActiveXObject)try{b=new ActiveXObject("MSXML2.XMLHttp.3.0")}catch(c){b=new ActiveXObject("Microsoft.XMLHTTP")}return b},isArray:Q,support:{dnd:z&&"ondrop"in o.createElement("div"),cors:z,html5:y,chunked:A,dataURI:!0,accept:X("accept"),multiple:X("multiple")},event:{on:T,off:U,one:V,fix:W},throttle:function(b,c){var d,e;return function(){e=arguments,d||(b.apply(a,e),d=setTimeout(function(){d=0,b.apply(a,e)},c))}},F:function(){},parseJSON:function(b){var c;return c=a.JSON&&JSON.parse?JSON.parse(b):new Function("return ("+b.replace(/([\r\n])/g,"\\$1")+");")()},trim:function(a){return a=String(a),a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")},defer:function(){var a,c,d=[],e={resolve:function(b,f){for(e.resolve=n,c=b||!1,a=f;f=d.shift();)f(c,a)},then:function(e){c!==b?e(c,a):d.push(e)}};return e},queue:function(a){var b=0,c=0,d=!1,e=!1,f={inc:function(){c++},next:function(){b++,setTimeout(f.check,0)},check:function(){b>=c&&!d&&f.end()},isFail:function(){return d},fail:function(){!d&&a(d=!0)},end:function(){e||(e=!0,a())}};return f},each:R,afor:function(a,b){var c=0,d=a.length;Q(a)&&d--?!function e(){b(d!=c&&e,a[c],c++)}():b(!1)},extend:S,isFile:function(a){return"[object File]"===H.call(a)},isBlob:function(a){return this.isFile(a)||"[object Blob]"===H.call(a)},isCanvas:function(a){return a&&D.test(a.nodeName)},getFilesFilter:function(a){return a="string"==typeof a?a:a.getAttribute&&a.getAttribute("accept")||"",a?new RegExp("("+a.replace(/\./g,"\\.").replace(/,/g,"|")+")$","i"):/./},readAsDataURL:function(a,b){Y.isCanvas(a)?c(a,b,"load",Y.toDataURL(a)):e(a,b,"DataURL")},readAsBinaryString:function(a,b){d("BinaryString")?e(a,b,"BinaryString"):e(a,function(a){if("load"==a.type)try{a.result=Y.toBinaryString(a.result)}catch(c){a.type="error",a.message=c.toString()}b(a)},"DataURL")},readAsArrayBuffer:function(a,b){e(a,b,"ArrayBuffer")},readAsText:function(a,b,c){c||(c=b,b="utf-8"),e(a,c,"Text",b)},toDataURL:function(a,b){return"string"==typeof a?a:a.toDataURL?a.toDataURL(b||"image/png"):void 0},toBinaryString:function(b){return a.atob(Y.toDataURL(b).replace(G,""))},readAsImage:function(a,d,e){if(Y.isFile(a))if(r){var f=r.createObjectURL(a);f===b?c(a,d,"error"):Y.readAsImage(f,d,e)}else Y.readAsDataURL(a,function(b){"load"==b.type?Y.readAsImage(b.result,d,e):(e||"error"==b.type)&&c(a,d,b,null,{loaded:b.loaded,total:b.total})});else if(Y.isCanvas(a))c(a,d,"load",a);else if(C.test(a.nodeName))if(a.complete)c(a,d,"load",a);else{var g="error abort load";V(a,g,function i(b){"load"==b.type&&r&&r.revokeObjectURL(a.src),U(a,g,i),c(a,d,b,a)})}else if(a.iframe)c(a,d,{type:"error"});else{var h=Y.newImage(a.dataURL||a);Y.readAsImage(h,d,e)}},checkFileObj:function(a){var b={},c=Y.accept;return"object"==typeof a?b=a:b.name=(a+"").split(/\\|\//g).pop(),null==b.type&&(b.type=b.name.split(".").pop()),R(c,function(a,c){a=new RegExp(a.replace(/\s/g,"|"),"i"),(a.test(b.type)||Y.ext2mime[b.type])&&(b.type=Y.ext2mime[b.type]||c.split("/")[0]+"/"+b.type)}),b},getDropFiles:function(a,b){var c=[],d=k(a),e=Q(d.items)&&d.items[0]&&g(d.items[0]),i=Y.queue(function(){b(c)});R((e?d.items:d.files)||[],function(a){i.inc();try{e?h(a,function(a,b){a?Y.log("[err] getDropFiles:",a):c.push.apply(c,b),i.next()}):f(a,function(b){b&&c.push(a),i.next()})}catch(b){i.next(),Y.log("[err] getDropFiles: ",b)}}),i.check()},getFiles:function(a,b,c){var d=[];return c?(Y.filterFiles(Y.getFiles(a),b,c),null):(a.jquery&&(a.each(function(){d=d.concat(Y.getFiles(this))}),a=d,d=[]),"string"==typeof b&&(b=Y.getFilesFilter(b)),a.originalEvent?a=W(a.originalEvent):a.srcElement&&(a=W(a)),a.dataTransfer?a=a.dataTransfer:a.target&&(a=a.target),a.files?(d=a.files,y||(d[0].blob=a,d[0].iframe=!0)):!y&&j(a)?Y.trim(a.value)&&(d=[Y.checkFileObj(a.value)],d[0].blob=a,d[0].iframe=!0):Q(a)&&(d=a),Y.filter(d,function(a){return!b||b.test(a.name)}))},getTotalSize:function(a){for(var b=0,c=a&&a.length;c--;)b+=a[c].size;return b},getInfo:function(a,b){var c={},d=L.concat();Y.isFile(a)?!function e(){var f=d.shift();f?f.test(a.type)?f(a,function(a,d){a?b(a):(S(c,d),e())}):e():b(!1,c)}():b("not_support_info",c)},addInfoReader:function(a,b){b.test=function(b){return a.test(b)},L.push(b)},filter:function(a,b){for(var c,d=[],e=0,f=a.length;f>e;e++)e in a&&(c=a[e],b.call(c,c,e,a)&&d.push(c));return d},filterFiles:function(a,b,c){if(a.length){var d,e=a.concat(),f=[],g=[];!function h(){e.length?(d=e.shift(),Y.getInfo(d,function(a,c){(b(d,a?!1:c)?f:g).push(d),h()})):c(f,g)}()}else c([],a)},upload:function(a){a=S({jsonp:"callback",prepare:Y.F,beforeupload:Y.F,upload:Y.F,fileupload:Y.F,fileprogress:Y.F,filecomplete:Y.F,progress:Y.F,complete:Y.F,pause:Y.F,imageOriginal:!0,chunkSize:Y.chunkSize,chunkUploadRetry:Y.chunkUploadRetry,uploadRetry:Y.uploadRetry},a),a.imageAutoOrientation&&!a.imageTransform&&(a.imageTransform={rotate:"auto"});var b,c=new Y.XHR(a),d=this._getFilesDataArray(a.files),e=this,f=0,g=0,h=!1;return R(d,function(a){f+=a.size}),c.files=[],R(d,function(a){c.files.push(a.file)}),c.total=f,c.loaded=0,c.filesLeft=d.length,a.beforeupload(c,a),b=function(){var j=d.shift(),k=j&&j.file,l=!1,m=i(a);if(c.filesLeft=d.length,k&&k.name===Y.expando&&(k=null,Y.log("[warn] FileAPI.upload() — called without files")),("abort"!=c.statusText||c.current)&&j){if(h=!1,c.currentFile=k,k&&a.prepare(k,m)===!1)return void b.call(e);m.file=k,e._getFormData(m,j,function(h){g||a.upload(c,a);var i=new Y.XHR(S({},m,{upload:k?function(){a.fileupload(k,i,m)}:n,progress:k?function(b){l||(l=b.loaded===b.total,a.fileprogress({type:"progress",total:j.total=b.total,loaded:j.loaded=b.loaded},k,i,m),a.progress({type:"progress",total:f,loaded:c.loaded=g+j.size*(b.loaded/b.total)|0},k,i,m))}:n,complete:function(d){R(N,function(a){c[a]=i[a]}),k&&(j.total=j.total||j.size,j.loaded=j.total,d||(this.progress(j),l=!0,g+=j.size,c.loaded=g),a.filecomplete(d,i,k,m)),setTimeout(function(){b.call(e)},0)}}));c.abort=function(a){a||(d.length=0),this.current=a,i.abort()},i.send(h)})}else{var o=200==c.status||201==c.status||204==c.status;a.complete(o?!1:c.statusText||"error",c,a),h=!0}},setTimeout(b,0),c.append=function(a,g){a=Y._getFilesDataArray([].concat(a)),R(a,function(a){f+=a.size,c.files.push(a.file),g?d.unshift(a):d.push(a)}),c.statusText="",h&&b.call(e)},c.remove=function(a){for(var b,c=d.length;c--;)d[c].file==a&&(b=d.splice(c,1),f-=b.size);return b},c},_getFilesDataArray:function(a){var b=[],c={};if(j(a)){var d=Y.getFiles(a);c[a.name||"file"]=null!==a.getAttribute("multiple")?d:d[0]}else Q(a)&&j(a[0])?R(a,function(a){c[a.name||"file"]=Y.getFiles(a)}):c=a;return R(c,function e(a,c){Q(a)?R(a,function(a){e(a,c)}):a&&(a.name||a.image)&&b.push({name:c,file:a,size:a.size,total:a.size,loaded:0})}),b.length||b.push({file:{name:Y.expando}}),b},_getFormData:function(a,b,c){var d=b.file,e=b.name,f=d.name,g=d.type,h=Y.support.transform&&a.imageTransform,i=new Y.Form,j=Y.queue(function(){c(i)}),k=h&&l(h),m=Y.postNameConcat;R(a.data,function n(a,b){"object"==typeof a?R(a,function(a,c){n(a,m(b,c))}):i.append(b,a)}),function o(b){b.image?(j.inc(),b.toData(function(a,b){f=f||(new Date).getTime()+".png",o(b),j.next()})):Y.Image&&h&&(/^image/.test(b.type)||E.test(b.nodeName))?(j.inc(),k&&(h=[h]),Y.Image.transform(b,h,a.imageAutoOrientation,function(c,d){if(k&&!c)B||Y.flashEngine||(i.multipart=!0),i.append(e,d[0],f,h[0].type||g);else{var l=0;c||R(d,function(a,b){B||Y.flashEngine||(i.multipart=!0),h[b].postName||(l=1),i.append(h[b].postName||m(e,b),a,f,h[b].type||g)}),(c||a.imageOriginal)&&i.append(m(e,l?"original":null),b,f,g)}j.next()})):f!==Y.expando&&i.append(e,b,f)}(d),j.check()},reset:function(a,b){var c,d;return x?(d=x(a).clone(!0).insertBefore(a).val("")[0],b||x(a).remove()):(c=a.parentNode,d=c.insertBefore(a.cloneNode(!0),a),d.value="",b||c.removeChild(a),R(K[Y.uid(a)],function(b,c){R(b,function(b){U(a,c,b),T(d,c,b)})})),d},load:function(a,b){var c=Y.getXHR();return c?(c.open("GET",a,!0),c.overrideMimeType&&c.overrideMimeType("text/plain; charset=x-user-defined"),T(c,"progress",function(a){a.lengthComputable&&b({type:a.type,loaded:a.loaded,total:a.total},c)}),c.onreadystatechange=function(){if(4==c.readyState)if(c.onreadystatechange=null,200==c.status){a=a.split("/");var d={name:a[a.length-1],size:c.getResponseHeader("Content-Length"),type:c.getResponseHeader("Content-Type")};d.dataURL="data:"+d.type+";base64,"+Y.encode64(c.responseBody||c.responseText),b({type:"load",result:d},c)}else b({type:"error"},c)},c.send(null)):b({type:"error"}),c},encode64:function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",d=0;for("string"!=typeof a&&(a=String(a));d<a.length;){var e,f,g=255&a.charCodeAt(d++),h=255&a.charCodeAt(d++),i=255&a.charCodeAt(d++),j=g>>2,k=(3&g)<<4|h>>4;isNaN(h)?e=f=64:(e=(15&h)<<2|i>>6,f=isNaN(i)?64:63&i),c+=b.charAt(j)+b.charAt(k)+b.charAt(e)+b.charAt(f)}return c}};Y.addInfoReader(/^image/,function(a,b){if(!a.__dimensions){var c=a.__dimensions=Y.defer();Y.readAsImage(a,function(a){var b=a.target;c.resolve("load"==a.type?!1:"error",{width:b.width,height:b.height}),b.src=Y.EMPTY_PNG,b=null})}a.__dimensions.then(b)}),Y.event.dnd=function(a,b,c){var d,e;c||(c=b,b=Y.F),u?(T(a,"dragenter dragleave dragover",b.ff=b.ff||function(a){for(var c=k(a).types,f=c&&c.length,g=!1;f--;)if(~c[f].indexOf("File")){a[P](),e!==a.type&&(e=a.type,"dragleave"!=e&&b.call(a[O],!0,a),g=!0);break}g&&(clearTimeout(d),d=setTimeout(function(){b.call(a[O],"dragleave"!=e,a)},50))}),T(a,"drop",c.ff=c.ff||function(a){a[P](),e=0,b.call(a[O],!1,a),Y.getDropFiles(a,function(b){c.call(a[O],b,a)})})):Y.log("Drag'n'Drop -- not supported")},Y.event.dnd.off=function(a,b,c){U(a,"dragenter dragleave dragover",b.ff),U(a,"drop",c.ff)},x&&!x.fn.dnd&&(x.fn.dnd=function(a,b){return this.each(function(){Y.event.dnd(this,a,b)})},x.fn.offdnd=function(a,b){return this.each(function(){Y.event.dnd.off(this,a,b)})}),a.FileAPI=S(Y,a.FileAPI),Y.log("FileAPI: "+Y.version),Y.log("protocol: "+a.location.protocol),Y.log("doctype: ["+p.name+"] "+p.publicId+" "+p.systemId),R(o.getElementsByTagName("meta"),function(a){/x-ua-compatible/i.test(a.getAttribute("http-equiv"))&&Y.log("meta.http-equiv: "+a.getAttribute("content"))});try{Y._supportConsoleLog=!!console.log,Y._supportConsoleLogApply=!!console.log.apply}catch(Z){}Y.flashUrl||(Y.flashUrl=Y.staticPath+"FileAPI.flash.swf"),Y.flashImageUrl||(Y.flashImageUrl=Y.staticPath+"FileAPI.flash.image.swf"),Y.flashWebcamUrl||(Y.flashWebcamUrl=Y.staticPath+"FileAPI.flash.camera.swf")}(window,void 0),function(a,b,c){"use strict";function d(b){if(b instanceof d){var c=new d(b.file);return a.extend(c.matrix,b.matrix),c}return this instanceof d?(this.file=b,this.size=b.size||100,void(this.matrix={sx:0,sy:0,sw:0,sh:0,dx:0,dy:0,dw:0,dh:0,resize:0,deg:0,quality:1,filter:0})):new d(b)}var e=Math.min,f=Math.round,g=function(){return b.createElement("canvas")},h=!1,i={8:270,3:180,6:90,7:270,4:180,5:90};try{h=g().toDataURL("image/png").indexOf("data:image/png")>-1}catch(j){}d.prototype={image:!0,constructor:d,set:function(b){return a.extend(this.matrix,b),this},crop:function(a,b,d,e){return d===c&&(d=a,e=b,a=b=0),this.set({sx:a,sy:b,sw:d,sh:e||d})},resize:function(a,b,c){return/min|max/.test(b)&&(c=b,b=a),this.set({dw:a,dh:b||a,resize:c})},preview:function(a,b){return this.resize(a,b||a,"preview")},rotate:function(a){return this.set({deg:a})},filter:function(a){return this.set({filter:a})},overlay:function(a){return this.set({overlay:a})},clone:function(){return new d(this)},_load:function(b,c){var d=this;/img|video/i.test(b.nodeName)?c.call(d,null,b):a.readAsImage(b,function(a){c.call(d,"load"!=a.type,a.result)})},_apply:function(b,c){var f,h=g(),i=this.getMatrix(b),j=h.getContext("2d"),k=b.videoWidth||b.width,l=b.videoHeight||b.height,m=i.deg,n=i.dw,o=i.dh,p=k,q=l,r=i.filter,s=b,t=i.overlay,u=a.queue(function(){b.src=a.EMPTY_PNG,c(!1,h)}),v=a.renderImageToCanvas;for(m-=360*Math.floor(m/360),b._type=this.file.type;i.multipass&&e(p/n,q/o)>2;)p=p/2+.5|0,q=q/2+.5|0,f=g(),f.width=p,f.height=q,s!==b?(v(f,s,0,0,s.width,s.height,0,0,p,q),s=f):(s=f,v(s,b,i.sx,i.sy,i.sw,i.sh,0,0,p,q),i.sx=i.sy=i.sw=i.sh=0);h.width=m%180?o:n,h.height=m%180?n:o,h.type=i.type,h.quality=i.quality,j.rotate(m*Math.PI/180),v(j.canvas,s,i.sx,i.sy,i.sw||s.width,i.sh||s.height,180==m||270==m?-n:0,90==m||180==m?-o:0,n,o),n=h.width,o=h.height,t&&a.each([].concat(t),function(b){u.inc();var c=new window.Image,d=function(){var e=0|b.x,f=0|b.y,g=b.w||c.width,h=b.h||c.height,i=b.rel;e=1==i||4==i||7==i?(n-g+e)/2:2==i||5==i||8==i?n-(g+e):e,f=3==i||4==i||5==i?(o-h+f)/2:i>=6?o-(h+f):f,a.event.off(c,"error load abort",d);try{j.globalAlpha=b.opacity||1,j.drawImage(c,e,f,g,h)}catch(k){}u.next()};a.event.on(c,"error load abort",d),c.src=b.src,c.complete&&d()}),r&&(u.inc(),d.applyFilter(h,r,u.next)),u.check()},getMatrix:function(b){var c=a.extend({},this.matrix),d=c.sw=c.sw||b.videoWidth||b.naturalWidth||b.width,g=c.sh=c.sh||b.videoHeight||b.naturalHeight||b.height,h=c.dw=c.dw||d,i=c.dh=c.dh||g,j=d/g,k=h/i,l=c.resize;if("preview"==l){if(h!=d||i!=g){var m,n;k>=j?(m=d,n=m/k):(n=g,m=n*k),(m!=d||n!=g)&&(c.sx=~~((d-m)/2),c.sy=~~((g-n)/2),d=m,g=n)}}else l&&(d>h||g>i?"min"==l?(h=f(k>j?e(d,h):i*j),i=f(k>j?h/j:e(g,i))):(h=f(j>=k?e(d,h):i*j),i=f(j>=k?h/j:e(g,i))):(h=d,i=g));return c.sw=d,c.sh=g,c.dw=h,c.dh=i,c.multipass=a.multiPassResize,c},_trans:function(b){this._load(this.file,function(c,d){if(c)b(c);else try{this._apply(d,b)}catch(c){a.log("[err] FileAPI.Image.fn._apply:",c),b(c)}})},get:function(b){if(a.support.transform){var c=this,d=c.matrix;"auto"==d.deg?a.getInfo(c.file,function(a,e){d.deg=i[e&&e.exif&&e.exif.Orientation]||0,c._trans(b)}):c._trans(b)}else b("not_support_transform");return this},toData:function(a){return this.get(a)}},d.exifOrientation=i,d.transform=function(b,e,f,g){function h(h,i){var j={},k=a.queue(function(a){g(a,j)});h?k.fail():a.each(e,function(a,e){if(!k.isFail()){var g=new d(i.nodeType?i:b),h="function"==typeof a;if(h?a(i,g):a.width?g[a.preview?"preview":"resize"](a.width,a.height,a.strategy):a.maxWidth&&(i.width>a.maxWidth||i.height>a.maxHeight)&&g.resize(a.maxWidth,a.maxHeight,"max"),a.crop){var l=a.crop;g.crop(0|l.x,0|l.y,l.w||l.width,l.h||l.height)}a.rotate===c&&f&&(a.rotate="auto"),g.set({type:g.matrix.type||a.type||b.type||"image/png"}),h||g.set({deg:a.rotate,overlay:a.overlay,filter:a.filter,quality:a.quality||1}),k.inc(),g.toData(function(a,b){a?k.fail():(j[e]=b,k.next())})}})}b.width?h(!1,b):a.getInfo(b,h)},a.each(["TOP","CENTER","BOTTOM"],function(b,c){a.each(["LEFT","CENTER","RIGHT"],function(a,e){d[b+"_"+a]=3*c+e,d[a+"_"+b]=3*c+e})}),d.toCanvas=function(a){var c=b.createElement("canvas");return c.width=a.videoWidth||a.width,c.height=a.videoHeight||a.height,c.getContext("2d").drawImage(a,0,0),c},d.fromDataURL=function(b,c,d){var e=a.newImage(b);a.extend(e,c),d(e)},d.applyFilter=function(b,c,e){"function"==typeof c?c(b,e):window.Caman&&window.Caman("IMG"==b.tagName?d.toCanvas(b):b,function(){"string"==typeof c?this[c]():a.each(c,function(a,b){this[b](a)},this),this.render(e)})},a.renderImageToCanvas=function(b,c,d,e,f,g,h,i,j,k){try{return b.getContext("2d").drawImage(c,d,e,f,g,h,i,j,k)}catch(l){throw a.log("renderImageToCanvas failed"),l}},a.support.canvas=a.support.transform=h,a.Image=d}(FileAPI,document),function(a){"use strict";a(FileAPI)}(function(a){"use strict";if(window.navigator&&window.navigator.platform&&/iP(hone|od|ad)/.test(window.navigator.platform)){var b=a.renderImageToCanvas;a.detectSubsampling=function(a){var b,c;return a.width*a.height>1048576?(b=document.createElement("canvas"),b.width=b.height=1,c=b.getContext("2d"),c.drawImage(a,-a.width+1,0),0===c.getImageData(0,0,1,1).data[3]):!1},a.detectVerticalSquash=function(a,b){var c,d,e,f,g,h=a.naturalHeight||a.height,i=document.createElement("canvas"),j=i.getContext("2d");for(b&&(h/=2),i.width=1,i.height=h,j.drawImage(a,0,0),c=j.getImageData(0,0,1,h).data,d=0,e=h,f=h;f>d;)g=c[4*(f-1)+3],0===g?e=f:d=f,f=e+d>>1;return f/h||1},a.renderImageToCanvas=function(c,d,e,f,g,h,i,j,k,l){if("image/jpeg"===d._type){var m,n,o,p,q=c.getContext("2d"),r=document.createElement("canvas"),s=1024,t=r.getContext("2d");if(r.width=s,r.height=s,q.save(),m=a.detectSubsampling(d),m&&(e/=2,f/=2,g/=2,h/=2),n=a.detectVerticalSquash(d,m),m||1!==n){for(f*=n,k=Math.ceil(s*k/g),l=Math.ceil(s*l/h/n),j=0,p=0;h>p;){for(i=0,o=0;g>o;)t.clearRect(0,0,s,s),t.drawImage(d,e,f,g,h,-o,-p,g,h),q.drawImage(r,0,0,s,s,i,j,k,l),o+=s,i+=k;p+=s,j+=l}return q.restore(),c}}return b(c,d,e,f,g,h,i,j,k,l)}}}),function(a,b){"use strict";function c(b,c,d){var e=b.blob,f=b.file;if(f){if(!e.toDataURL)return void a.readAsBinaryString(e,function(a){"load"==a.type&&c(b,a.result)});var g={"image/jpeg":".jpe?g","image/png":".png"},h=g[b.type]?b.type:"image/png",i=g[h]||".png",j=e.quality||1;f.match(new RegExp(i+"$","i"))||(f+=i.replace("?","")),b.file=f,b.type=h,!d&&e.toBlob?e.toBlob(function(a){c(b,a)},h,j):c(b,a.toBinaryString(e.toDataURL(h,j)))}else c(b,e)}var d=b.document,e=b.FormData,f=function(){this.items=[]},g=b.encodeURIComponent;f.prototype={append:function(a,b,c,d){this.items.push({name:a,blob:b&&b.blob||(void 0==b?"":b),file:b&&(c||b.name),type:b&&(d||b.type)})},each:function(a){for(var b=0,c=this.items.length;c>b;b++)a.call(this,this.items[b])},toData:function(b,c){c._chunked=a.support.chunked&&c.chunkSize>0&&1==a.filter(this.items,function(a){return a.file}).length,a.support.html5?a.formData&&!this.multipart&&e?c._chunked?(a.log("FileAPI.Form.toPlainData"),this.toPlainData(b)):(a.log("FileAPI.Form.toFormData"),this.toFormData(b)):(a.log("FileAPI.Form.toMultipartData"),this.toMultipartData(b)):(a.log("FileAPI.Form.toHtmlData"),this.toHtmlData(b))},_to:function(b,c,d,e){var f=a.queue(function(){c(b)});this.each(function(a){d(a,b,f,e)}),f.check()},toHtmlData:function(b){this._to(d.createDocumentFragment(),b,function(b,c){var e,f=b.blob;b.file?(a.reset(f,!0),f.name=b.name,f.disabled=!1,c.appendChild(f)):(e=d.createElement("input"),e.name=b.name,e.type="hidden",e.value=f,c.appendChild(e))})},toPlainData:function(a){this._to({},a,function(a,b,d){a.file&&(b.type=a.file),a.blob.toBlob?(d.inc(),c(a,function(a,c){b.name=a.name,b.file=c,b.size=c.length,b.type=a.type,d.next()})):a.file?(b.name=a.blob.name,b.file=a.blob,b.size=a.blob.size,b.type=a.type):(b.params||(b.params=[]),b.params.push(g(a.name)+"="+g(a.blob))),b.start=-1,b.end=b.file&&b.file.FileAPIReadPosition||-1,b.retry=0})},toFormData:function(a){this._to(new e,a,function(a,b,d){a.blob&&a.blob.toBlob?(d.inc(),c(a,function(a,c){b.append(a.name,c,a.file),d.next()})):a.file?b.append(a.name,a.blob,a.file):b.append(a.name,a.blob),a.file&&b.append("_"+a.name,a.file)})},toMultipartData:function(b){this._to([],b,function(a,b,d,e){d.inc(),c(a,function(a,c){b.push("--_"+e+('\r\nContent-Disposition: form-data; name="'+a.name+'"'+(a.file?'; filename="'+g(a.file)+'"':"")+(a.file?"\r\nContent-Type: "+(a.type||"application/octet-stream"):"")+"\r\n\r\n"+(a.file?c:g(c))+"\r\n")),d.next()},!0)},a.expando)}},a.Form=f}(FileAPI,window),function(a,b){"use strict";var c=function(){},d=a.document,e=function(a){this.uid=b.uid(),this.xhr={abort:c,getResponseHeader:c,getAllResponseHeaders:c},this.options=a},f={"":1,XML:1,Text:1,Body:1};e.prototype={status:0,statusText:"",constructor:e,getResponseHeader:function(a){return this.xhr.getResponseHeader(a)},getAllResponseHeaders:function(){return this.xhr.getAllResponseHeaders()||{}},end:function(d,e){var f=this,g=f.options;f.end=f.abort=c,f.status=d,e&&(f.statusText=e),b.log("xhr.end:",d,e),g.complete(200==d||201==d?!1:f.statusText||"unknown",f),f.xhr&&f.xhr.node&&setTimeout(function(){var b=f.xhr.node;try{b.parentNode.removeChild(b)}catch(c){}try{delete a[f.uid]}catch(c){}a[f.uid]=f.xhr.node=null},9)},abort:function(){this.end(0,"abort"),this.xhr&&(this.xhr.aborted=!0,this.xhr.abort())},send:function(a){var b=this,c=this.options;a.toData(function(a){c.upload(c,b),b._send.call(b,c,a)},c)},_send:function(c,e){var g,h=this,i=h.uid,j=h.uid+"Load",k=c.url;if(b.log("XHR._send:",e),c.cache||(k+=(~k.indexOf("?")?"&":"?")+b.uid()),e.nodeName){var l=c.jsonp;k=k.replace(/([a-z]+)=(\?)/i,"$1="+i),c.upload(c,h);var m=function(a){if(~k.indexOf(a.origin))try{var c=b.parseJSON(a.data);c.id==i&&n(c.status,c.statusText,c.response)}catch(d){n(0,d.message)}},n=a[i]=function(c,d,e){h.readyState=4,h.responseText=e,h.end(c,d),b.event.off(a,"message",m),a[i]=g=p=a[j]=null};h.xhr.abort=function(){try{p.stop?p.stop():p.contentWindow.stop?p.contentWindow.stop():p.contentWindow.document.execCommand("Stop")}catch(a){}n(0,"abort")},b.event.on(a,"message",m),a[j]=function(){try{var a=p.contentWindow,c=a.document,d=a.result||b.parseJSON(c.body.innerHTML);n(d.status,d.statusText,d.response)}catch(e){b.log("[transport.onload]",e)}},g=d.createElement("div"),g.innerHTML='<form target="'+i+'" action="'+k+'" method="POST" enctype="multipart/form-data" style="position: absolute; top: -1000px; overflow: hidden; width: 1px; height: 1px;"><iframe name="'+i+'" src="javascript:false;" onload="'+j+'()"></iframe>'+(l&&c.url.indexOf("=?")<0?'<input value="'+i+'" name="'+l+'" type="hidden"/>':"")+"</form>";var o=g.getElementsByTagName("form")[0],p=g.getElementsByTagName("iframe")[0];o.appendChild(e),b.log(o.parentNode.innerHTML),d.body.appendChild(g),h.xhr.node=g,h.readyState=2,o.submit(),o=null}else{if(k=k.replace(/([a-z]+)=(\?)&?/i,""),this.xhr&&this.xhr.aborted)return void b.log("Error: already aborted");if(g=h.xhr=b.getXHR(),e.params&&(k+=(k.indexOf("?")<0?"?":"&")+e.params.join("&")),g.open("POST",k,!0),b.withCredentials&&(g.withCredentials="true"),c.headers&&c.headers["X-Requested-With"]||g.setRequestHeader("X-Requested-With","XMLHttpRequest"),b.each(c.headers,function(a,b){g.setRequestHeader(b,a)}),c._chunked){g.upload&&g.upload.addEventListener("progress",b.throttle(function(a){e.retry||c.progress({type:a.type,total:e.size,loaded:e.start+a.loaded,totalSize:e.size},h,c)},100),!1),g.onreadystatechange=function(){var a=parseInt(g.getResponseHeader("X-Last-Known-Byte"),10);if(h.status=g.status,h.statusText=g.statusText,h.readyState=g.readyState,4==g.readyState){try{for(var d in f)h["response"+d]=g["response"+d]}catch(i){}if(g.onreadystatechange=null,!g.status||g.status-201>0)if(b.log("Error: "+g.status),(!g.status&&!g.aborted||500==g.status||416==g.status)&&++e.retry<=c.chunkUploadRetry){var j=g.status?0:b.chunkNetworkDownRetryTimeout;c.pause(e.file,c),b.log("X-Last-Known-Byte: "+a),a?e.end=a:(e.end=e.start-1,416==g.status&&(e.end=e.end-c.chunkSize)),setTimeout(function(){h._send(c,e)},j)}else h.end(g.status);else e.retry=0,e.end==e.size-1?h.end(g.status):(b.log("X-Last-Known-Byte: "+a),a&&(e.end=a),e.file.FileAPIReadPosition=e.end,setTimeout(function(){h._send(c,e)},0));g=null}},e.start=e.end+1,e.end=Math.max(Math.min(e.start+c.chunkSize,e.size)-1,e.start);var q=e.file,r=(q.slice||q.mozSlice||q.webkitSlice).call(q,e.start,e.end+1);e.size&&!r.size?setTimeout(function(){h.end(-1)}):(g.setRequestHeader("Content-Range","bytes "+e.start+"-"+e.end+"/"+e.size),g.setRequestHeader("Content-Disposition","attachment; filename="+encodeURIComponent(e.name)),g.setRequestHeader("Content-Type",e.type||"application/octet-stream"),g.send(r)),q=r=null}else if(g.upload&&g.upload.addEventListener("progress",b.throttle(function(a){c.progress(a,h,c)},100),!1),g.onreadystatechange=function(){if(h.status=g.status,h.statusText=g.statusText,h.readyState=g.readyState,4==g.readyState){for(var a in f)h["response"+a]=g["response"+a];if(g.onreadystatechange=null,!g.status||g.status>201)if(b.log("Error: "+g.status),(!g.status&&!g.aborted||500==g.status)&&(c.retry||0)<c.uploadRetry){c.retry=(c.retry||0)+1;var d=b.networkDownRetryTimeout;c.pause(c.file,c),setTimeout(function(){h._send(c,e)},d)}else h.end(g.status);else h.end(g.status);g=null}},b.isArray(e)){g.setRequestHeader("Content-Type","multipart/form-data; boundary=_"+b.expando);var s=e.join("")+"--_"+b.expando+"--";if(g.sendAsBinary)g.sendAsBinary(s);else{var t=Array.prototype.map.call(s,function(a){return 255&a.charCodeAt(0)});g.send(new Uint8Array(t).buffer)}}else g.send(e)}}},b.XHR=e}(window,FileAPI),function(a,b){"use strict";function c(a){return a>=0?a+"px":a}function d(a){var b,c=f.createElement("canvas"),d=!1;try{b=c.getContext("2d"),b.drawImage(a,0,0,1,1),d=255!=b.getImageData(0,0,1,1).data[4]}catch(e){}return d}var e=a.URL||a.webkitURL,f=a.document,g=a.navigator,h=g.getUserMedia||g.webkitGetUserMedia||g.mozGetUserMedia||g.msGetUserMedia,i=!!h;b.support.media=i;var j=function(a){this.video=a};j.prototype={isActive:function(){return!!this._active},start:function(a){var b,c,f=this,i=f.video,j=function(d){f._active=!d,clearTimeout(c),clearTimeout(b),a&&a(d,f)};h.call(g,{video:!0},function(a){f.stream=a,i.src=e.createObjectURL(a),b=setInterval(function(){d(i)&&j(null)},1e3),c=setTimeout(function(){j("timeout")},5e3),i.play()},j)},stop:function(){try{this._active=!1,this.video.pause(),this.stream.stop()}catch(a){}},shot:function(){return new k(this.video)}},j.get=function(a){return new j(a.firstChild)},j.publish=function(d,e,g){"function"==typeof e&&(g=e,e={}),e=b.extend({},{width:"100%",height:"100%",start:!0},e),d.jquery&&(d=d[0]);var h=function(a){if(a)g(a);else{var b=j.get(d);e.start?b.start(g):g(null,b)}};if(d.style.width=c(e.width),d.style.height=c(e.height),b.html5&&i){var k=f.createElement("video");k.style.width=c(e.width),k.style.height=c(e.height),a.jQuery?jQuery(d).empty():d.innerHTML="",d.appendChild(k),h()}else j.fallback(d,e,h)},j.fallback=function(a,b,c){c("not_support_camera")};var k=function(a){var c=a.nodeName?b.Image.toCanvas(a):a,d=b.Image(c);return d.type="image/png",d.width=c.width,d.height=c.height,d.size=c.width*c.height*4,d};j.Shot=k,b.Camera=j}(window,FileAPI),function(a,b,c){"use strict";var d=a.document,e=a.location,f=a.navigator,g=c.each;c.support.flash=function(){var b=f.mimeTypes,d=!1;if(f.plugins&&"object"==typeof f.plugins["Shockwave Flash"])d=f.plugins["Shockwave Flash"].description&&!(b&&b["application/x-shockwave-flash"]&&!b["application/x-shockwave-flash"].enabledPlugin);
6
+ else try{d=!(!a.ActiveXObject||!new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))}catch(g){c.log("Flash -- does not supported.")}return d&&/^file:/i.test(e)&&c.log("[warn] Flash does not work on `file:` protocol."),d}(),c.support.flash&&(0||!c.html5||!c.support.html5||c.cors&&!c.support.cors||c.media&&!c.support.media)&&function(){function h(a){return('<object id="#id#" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+(a.width||"100%")+'" height="'+(a.height||"100%")+'"><param name="movie" value="#src#" /><param name="flashvars" value="#flashvars#" /><param name="swliveconnect" value="true" /><param name="allowscriptaccess" value="always" /><param name="allownetworking" value="all" /><param name="menu" value="false" /><param name="wmode" value="#wmode#" /><embed flashvars="#flashvars#" swliveconnect="true" allownetworking="all" allowscriptaccess="always" name="#id#" src="#src#" width="'+(a.width||"100%")+'" height="'+(a.height||"100%")+'" menu="false" wmode="transparent" type="application/x-shockwave-flash"></embed></object>').replace(/#(\w+)#/gi,function(b,c){return a[c]})}function i(a,b){if(a&&a.style){var c,d;for(c in b){d=b[c],"number"==typeof d&&(d+="px");try{a.style[c]=d}catch(e){}}}}function j(a,b){g(b,function(b,c){var d=a[c];a[c]=function(){return this.parent=d,b.apply(this,arguments)}})}function k(a){return a&&!a.flashId}function l(a){var b=a.wid=c.uid();return v._fn[b]=a,"FileAPI.Flash._fn."+b}function m(a){try{v._fn[a.wid]=null,delete v._fn[a.wid]}catch(b){}}function n(a,b){if(!u.test(a)){if(/^\.\//.test(a)||"/"!=a.charAt(0)){var c=e.pathname;c=c.substr(0,c.lastIndexOf("/")),a=(c+"/"+a).replace("/./","/")}"//"!=a.substr(0,2)&&(a="//"+e.host+a),u.test(a)||(a=e.protocol+a)}return b&&(a+=(/\?/.test(a)?"&":"?")+b),a}function o(a,b,e){function f(){try{var a=v.get(j);a.setImage(b)}catch(d){c.log('[err] FlashAPI.Preview.setImage -- can not set "base64":',d)}}var g,j=c.uid(),k=d.createElement("div"),o=10;for(g in a)k.setAttribute(g,a[g]),k[g]=a[g];i(k,a),a.width="100%",a.height="100%",k.innerHTML=h(c.extend({id:j,src:n(c.flashImageUrl,"r="+c.uid()),wmode:"opaque",flashvars:"scale="+a.scale+"&callback="+l(function p(){return m(p),--o>0&&f(),!0})},a)),e(!1,k),k=null}function p(a){return{id:a.id,name:a.name,matrix:a.matrix,flashId:a.flashId}}function q(a){function b(a){var b,c;if(b=c=0,a.offsetParent)do b+=a.offsetLeft,c+=a.offsetTop;while(a=a.offsetParent);return{left:b,top:c}}a.getBoundingClientRect(),d.body,(a&&a.ownerDocument).documentElement;return{top:b(a).top,left:b(a).left,width:a.offsetWidth,height:a.offsetHeight}}var r=c.uid(),s=0,t={},u=/^https?:/i,v={_fn:{},publish:function(a,b,d){d=d||{},a.innerHTML=h({id:b,src:n(c.flashUrl,"r="+c.version),wmode:d.camera?"":"transparent",flashvars:"callback="+(d.onEvent||"FileAPI.Flash.onEvent")+"&flashId="+b+"&storeKey="+f.userAgent.match(/\d/gi).join("")+"_"+c.version+(v.isReady||(c.pingUrl?"&ping="+c.pingUrl:""))+"&timeout="+c.flashAbortTimeout+(d.camera?"&useCamera="+n(c.flashWebcamUrl):"")+"&debug="+(c.debug?"1":"")},d)},init:function(){var a=d.body&&d.body.firstChild;if(a)do if(1==a.nodeType){c.log("FlashAPI.state: awaiting");var b=d.createElement("div");return b.id="_"+r,i(b,{top:1,right:1,width:5,height:5,position:"absolute",zIndex:1e6+""}),a.parentNode.insertBefore(b,a),void v.publish(b,r)}while(a=a.nextSibling);10>s&&setTimeout(v.init,50*++s)},ready:function(){c.log("FlashAPI.state: ready"),v.ready=c.F,v.isReady=!0,v.patch(),v.patchCamera&&v.patchCamera(),c.event.on(d,"mouseover",v.mouseover),c.event.on(d,"click",function(a){v.mouseover(a)&&(a.preventDefault?a.preventDefault():a.returnValue=!0)})},getEl:function(){return d.getElementById("_"+r)},getWrapper:function(a){do if(/js-fileapi-wrapper/.test(a.className))return a;while((a=a.parentNode)&&a!==d.body)},disableMouseover:!1,mouseover:function(a){if(!v.disableMouseover){var b=c.event.fix(a).target;if(/input/i.test(b.nodeName)&&"file"==b.type&&!b.disabled){var e=b.getAttribute(r),f=v.getWrapper(b);if(c.multiFlash){if("i"==e||"r"==e)return!1;if("p"!=e){b.setAttribute(r,"i");var g=d.createElement("div");if(!f)return void c.log("[err] FlashAPI.mouseover: js-fileapi-wrapper not found");i(g,{top:0,left:0,width:b.offsetWidth,height:b.offsetHeight,zIndex:1e6+"",position:"absolute"}),f.appendChild(g),v.publish(g,c.uid()),b.setAttribute(r,"p")}return!0}if(f){var h=q(f);i(v.getEl(),h),v.curInp=b}}else/object|embed/i.test(b.nodeName)||i(v.getEl(),{top:1,left:1,width:5,height:5})}},onEvent:function(a){var b=a.type;if("ready"==b){try{v.getInput(a.flashId).setAttribute(r,"r")}catch(d){}return v.ready(),setTimeout(function(){v.mouseenter(a)},50),!0}"ping"===b?c.log("(flash -> js).ping:",[a.status,a.savedStatus],a.error):"log"===b?c.log("(flash -> js).log:",a.target):b in v&&setTimeout(function(){c.log("FlashAPI.event."+a.type+":",a),v[b](a)},1)},mouseDown:function(){v.disableMouseover=!0},cancel:function(){v.disableMouseover=!1},mouseenter:function(a){var b=v.getInput(a.flashId);if(b){v.cmd(a,"multiple",null!=b.getAttribute("multiple"));var d=[],e={};g((b.getAttribute("accept")||"").split(/,\s*/),function(a){c.accept[a]&&g(c.accept[a].split(" "),function(a){e[a]=1})}),g(e,function(a,b){d.push(b)}),v.cmd(a,"accept",d.length?d.join(",")+","+d.join(",").toUpperCase():"*")}},get:function(b){return d[b]||a[b]||d.embeds[b]},getInput:function(a){if(!c.multiFlash)return v.curInp;try{var b=v.getWrapper(v.get(a));if(b)return b.getElementsByTagName("input")[0]}catch(d){c.log('[err] Can not find "input" by flashId:',a,d)}},select:function(a){try{var e,f=v.getInput(a.flashId),h=c.uid(f),i=a.target.files;g(i,function(a){c.checkFileObj(a)}),t[h]=i,d.createEvent?(e=d.createEvent("Event"),e.files=i,e.initEvent("change",!0,!0),f.dispatchEvent(e)):b?b(f).trigger({type:"change",files:i}):(e=d.createEventObject(),e.files=i,f.fireEvent("onchange",e))}finally{v.disableMouseover=!1}},interval:null,cmd:function(a,b,c,d){v.uploadInProgress&&v.readInProgress?setTimeout(function(){v.cmd(a,b,c,d)},100):this.cmdFn(a,b,c,d)},cmdFn:function(a,b,d,e){try{return c.log("(js -> flash)."+b+":",d),v.get(a.flashId||a).cmd(b,d)}catch(f){c.log("(js -> flash).onError:",f),e||setTimeout(function(){v.cmd(a,b,d,!0)},50)}},patch:function(){c.flashEngine=!0,j(c,{readAsDataURL:function(a,b){k(a)?this.parent.apply(this,arguments):(c.log("FlashAPI.readAsBase64"),v.readInProgress=!0,v.cmd(a,"readAsBase64",{id:a.id,callback:l(function d(e,f){v.readInProgress=!1,m(d),c.log("FlashAPI.readAsBase64:",e),b({type:e?"error":"load",error:e,result:"data:"+a.type+";base64,"+f})})}))},readAsText:function(b,d,e){e?c.log("[warn] FlashAPI.readAsText not supported `encoding` param"):e=d,c.readAsDataURL(b,function(b){if("load"==b.type)try{b.result=a.atob(b.result.split(";base64,")[1])}catch(c){b.type="error",b.error=c.toString()}e(b)})},getFiles:function(a,b,d){if(d)return c.filterFiles(c.getFiles(a),b,d),null;var e=c.isArray(a)?a:t[c.uid(a.target||a.srcElement||a)];return e?(b&&(b=c.getFilesFilter(b),e=c.filter(e,function(a){return b.test(a.name)})),e):this.parent.apply(this,arguments)},getInfo:function(a,b){if(k(a))this.parent.apply(this,arguments);else if(a.isShot)b(null,a.info={width:a.width,height:a.height});else{if(!a.__info){var d=a.__info=c.defer();d.resolve(null,a.info=null)}a.__info.then(b)}}}),c.support.transform=!0,c.Image&&j(c.Image.prototype,{get:function(a,b){return this.set({scaleMode:b||"noScale"}),this.parent(a)},_load:function(a,b){if(c.log("FlashAPI.Image._load:",a),k(a))this.parent.apply(this,arguments);else{var d=this;c.getInfo(a,function(c){b.call(d,c,a)})}},_apply:function(a,b){if(c.log("FlashAPI.Image._apply:",a),k(a))this.parent.apply(this,arguments);else{var d=this.getMatrix(a.info),e=b;v.cmd(a,"imageTransform",{id:a.id,matrix:d,callback:l(function f(g,h){c.log("FlashAPI.Image._apply.callback:",g),m(f),g?e(g):c.support.html5||c.support.dataURI&&!(h.length>3e4)?(d.filter&&(e=function(a,e){a?b(a):c.Image.applyFilter(e,d.filter,function(){b(a,this.canvas)})}),c.newImage("data:"+a.type+";base64,"+h,e)):o({width:d.deg%180?d.dh:d.dw,height:d.deg%180?d.dw:d.dh,scale:d.scaleMode},h,e)})})}},toData:function(a){var b=this.file,d=b.info,e=this.getMatrix(d);c.log("FlashAPI.Image.toData"),k(b)?this.parent.apply(this,arguments):("auto"==e.deg&&(e.deg=c.Image.exifOrientation[d&&d.exif&&d.exif.Orientation]||0),a.call(this,!b.info,{id:b.id,flashId:b.flashId,name:b.name,type:b.type,matrix:e}))}}),c.Image&&j(c.Image,{fromDataURL:function(a,b,d){!c.support.dataURI||a.length>3e4?o(c.extend({scale:"exactFit"},b),a.replace(/^data:[^,]+,/,""),function(a,b){d(b)}):this.parent(a,b,d)}}),j(c.Form.prototype,{toData:function(a){for(var b=this.items,d=b.length;d--;)if(b[d].file&&k(b[d].blob))return this.parent.apply(this,arguments);c.log("FlashAPI.Form.toData"),a(b)}}),j(c.XHR.prototype,{_send:function(a,b){if(b.nodeName||b.append&&c.support.html5||c.isArray(b)&&"string"==typeof b[0])return this.parent.apply(this,arguments);var d,e,f={},h={},i=this;if(g(b,function(a){a.file?(h[a.name]=a=p(a.blob),e=a.id,d=a.flashId):f[a.name]=a.blob}),e||(d=r),!d)return c.log("[err] FlashAPI._send: flashId -- undefined"),this.parent.apply(this,arguments);c.log("FlashAPI.XHR._send: "+d+" -> "+e),i.xhr={headers:{},abort:function(){v.uploadInProgress=!1,v.cmd(d,"abort",{id:e})},getResponseHeader:function(a){return this.headers[a]},getAllResponseHeaders:function(){return this.headers}};var j=c.queue(function(){v.uploadInProgress=!0,v.cmd(d,"upload",{url:n(a.url.replace(/([a-z]+)=(\?)&?/i,"")),data:f,files:e?h:null,headers:a.headers||{},callback:l(function b(d){var e=d.type,f=d.result;c.log("FlashAPI.upload."+e),"progress"==e?(d.loaded=Math.min(d.loaded,d.total),d.lengthComputable=!0,a.progress(d)):"complete"==e?(v.uploadInProgress=!1,m(b),"string"==typeof f&&(i.responseText=f.replace(/%22/g,'"').replace(/%5c/g,"\\").replace(/%26/g,"&").replace(/%25/g,"%")),i.end(d.status||200)):("abort"==e||"error"==e)&&(v.uploadInProgress=!1,i.end(d.status||0,d.message),m(b))})})});g(h,function(a){j.inc(),c.getInfo(a,j.next)}),j.check()}})}};c.Flash=v,c.newImage("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",function(a,b){c.support.dataURI=!(1!=b.width||1!=b.height),v.init()})}()}(window,window.jQuery,FileAPI),function(a,b,c){"use strict";var d=c.each,e=[];c.support.flash&&c.media&&!c.support.media&&!function(){function a(a){var b=a.wid=c.uid();return c.Flash._fn[b]=a,"FileAPI.Flash._fn."+b}function b(a){try{c.Flash._fn[a.wid]=null,delete c.Flash._fn[a.wid]}catch(b){}}var f=c.Flash;c.extend(c.Flash,{patchCamera:function(){c.Camera.fallback=function(d,e,g){var h=c.uid();c.log("FlashAPI.Camera.publish: "+h),f.publish(d,h,c.extend(e,{camera:!0,onEvent:a(function i(a){"camera"===a.type&&(b(i),a.error?(c.log("FlashAPI.Camera.publish.error: "+a.error),g(a.error)):(c.log("FlashAPI.Camera.publish.success: "+h),g(null)))})}))},d(e,function(a){c.Camera.fallback.apply(c.Camera,a)}),e=[],c.extend(c.Camera.prototype,{_id:function(){return this.video.id},start:function(d){var e=this;f.cmd(this._id(),"camera.on",{callback:a(function g(a){b(g),a.error?(c.log("FlashAPI.camera.on.error: "+a.error),d(a.error,e)):(c.log("FlashAPI.camera.on.success: "+e._id()),e._active=!0,d(null,e))})})},stop:function(){this._active=!1,f.cmd(this._id(),"camera.off")},shot:function(){c.log("FlashAPI.Camera.shot:",this._id());var a=c.Flash.cmd(this._id(),"shot",{});return a.type="image/png",a.flashId=this._id(),a.isShot=!0,new c.Camera.Shot(a)}})}}),c.Camera.fallback=function(){e.push(arguments)}}()}(window,window.jQuery,FileAPI),"function"==typeof define&&define.amd&&define("FileAPI",[],function(){return FileAPI});
@@ -0,0 +1,2898 @@
1
+ /**!
2
+ * AngularJS file upload directives and services. Supports: file upload/drop/paste, resume, cancel/abort,
3
+ * progress, resize, thumbnail, preview, validation and CORS
4
+ * FileAPI Flash shim for old browsers not supporting FormData
5
+ * @author Danial <danial.farid@gmail.com>
6
+ * @version 12.2.13
7
+ */
8
+
9
+ (function () {
10
+ /** @namespace FileAPI.noContentTimeout */
11
+
12
+ function patchXHR(fnName, newFn) {
13
+ window.XMLHttpRequest.prototype[fnName] = newFn(window.XMLHttpRequest.prototype[fnName]);
14
+ }
15
+
16
+ function redefineProp(xhr, prop, fn) {
17
+ try {
18
+ Object.defineProperty(xhr, prop, {get: fn});
19
+ } catch (e) {/*ignore*/
20
+ }
21
+ }
22
+
23
+ if (!window.FileAPI) {
24
+ window.FileAPI = {};
25
+ }
26
+
27
+ if (!window.XMLHttpRequest) {
28
+ throw 'AJAX is not supported. XMLHttpRequest is not defined.';
29
+ }
30
+
31
+ FileAPI.shouldLoad = !window.FormData || FileAPI.forceLoad;
32
+ if (FileAPI.shouldLoad) {
33
+ var initializeUploadListener = function (xhr) {
34
+ if (!xhr.__listeners) {
35
+ if (!xhr.upload) xhr.upload = {};
36
+ xhr.__listeners = [];
37
+ var origAddEventListener = xhr.upload.addEventListener;
38
+ xhr.upload.addEventListener = function (t, fn) {
39
+ xhr.__listeners[t] = fn;
40
+ if (origAddEventListener) origAddEventListener.apply(this, arguments);
41
+ };
42
+ }
43
+ };
44
+
45
+ patchXHR('open', function (orig) {
46
+ return function (m, url, b) {
47
+ initializeUploadListener(this);
48
+ this.__url = url;
49
+ try {
50
+ orig.apply(this, [m, url, b]);
51
+ } catch (e) {
52
+ if (e.message.indexOf('Access is denied') > -1) {
53
+ this.__origError = e;
54
+ orig.apply(this, [m, '_fix_for_ie_crossdomain__', b]);
55
+ }
56
+ }
57
+ };
58
+ });
59
+
60
+ patchXHR('getResponseHeader', function (orig) {
61
+ return function (h) {
62
+ return this.__fileApiXHR && this.__fileApiXHR.getResponseHeader ? this.__fileApiXHR.getResponseHeader(h) : (orig == null ? null : orig.apply(this, [h]));
63
+ };
64
+ });
65
+
66
+ patchXHR('getAllResponseHeaders', function (orig) {
67
+ return function () {
68
+ return this.__fileApiXHR && this.__fileApiXHR.getAllResponseHeaders ? this.__fileApiXHR.getAllResponseHeaders() : (orig == null ? null : orig.apply(this));
69
+ };
70
+ });
71
+
72
+ patchXHR('abort', function (orig) {
73
+ return function () {
74
+ return this.__fileApiXHR && this.__fileApiXHR.abort ? this.__fileApiXHR.abort() : (orig == null ? null : orig.apply(this));
75
+ };
76
+ });
77
+
78
+ patchXHR('setRequestHeader', function (orig) {
79
+ return function (header, value) {
80
+ if (header === '__setXHR_') {
81
+ initializeUploadListener(this);
82
+ var val = value(this);
83
+ // fix for angular < 1.2.0
84
+ if (val instanceof Function) {
85
+ val(this);
86
+ }
87
+ } else {
88
+ this.__requestHeaders = this.__requestHeaders || {};
89
+ this.__requestHeaders[header] = value;
90
+ orig.apply(this, arguments);
91
+ }
92
+ };
93
+ });
94
+
95
+ patchXHR('send', function (orig) {
96
+ return function () {
97
+ var xhr = this;
98
+ if (arguments[0] && arguments[0].__isFileAPIShim) {
99
+ var formData = arguments[0];
100
+ var config = {
101
+ url: xhr.__url,
102
+ jsonp: false, //removes the callback form param
103
+ cache: true, //removes the ?fileapiXXX in the url
104
+ complete: function (err, fileApiXHR) {
105
+ if (err && angular.isString(err) && err.indexOf('#2174') !== -1) {
106
+ // this error seems to be fine the file is being uploaded properly.
107
+ err = null;
108
+ }
109
+ xhr.__completed = true;
110
+ if (!err && xhr.__listeners.load)
111
+ xhr.__listeners.load({
112
+ type: 'load',
113
+ loaded: xhr.__loaded,
114
+ total: xhr.__total,
115
+ target: xhr,
116
+ lengthComputable: true
117
+ });
118
+ if (!err && xhr.__listeners.loadend)
119
+ xhr.__listeners.loadend({
120
+ type: 'loadend',
121
+ loaded: xhr.__loaded,
122
+ total: xhr.__total,
123
+ target: xhr,
124
+ lengthComputable: true
125
+ });
126
+ if (err === 'abort' && xhr.__listeners.abort)
127
+ xhr.__listeners.abort({
128
+ type: 'abort',
129
+ loaded: xhr.__loaded,
130
+ total: xhr.__total,
131
+ target: xhr,
132
+ lengthComputable: true
133
+ });
134
+ if (fileApiXHR.status !== undefined) redefineProp(xhr, 'status', function () {
135
+ return (fileApiXHR.status === 0 && err && err !== 'abort') ? 500 : fileApiXHR.status;
136
+ });
137
+ if (fileApiXHR.statusText !== undefined) redefineProp(xhr, 'statusText', function () {
138
+ return fileApiXHR.statusText;
139
+ });
140
+ redefineProp(xhr, 'readyState', function () {
141
+ return 4;
142
+ });
143
+ if (fileApiXHR.response !== undefined) redefineProp(xhr, 'response', function () {
144
+ return fileApiXHR.response;
145
+ });
146
+ var resp = fileApiXHR.responseText || (err && fileApiXHR.status === 0 && err !== 'abort' ? err : undefined);
147
+ redefineProp(xhr, 'responseText', function () {
148
+ return resp;
149
+ });
150
+ redefineProp(xhr, 'response', function () {
151
+ return resp;
152
+ });
153
+ if (err) redefineProp(xhr, 'err', function () {
154
+ return err;
155
+ });
156
+ xhr.__fileApiXHR = fileApiXHR;
157
+ if (xhr.onreadystatechange) xhr.onreadystatechange();
158
+ if (xhr.onload) xhr.onload();
159
+ },
160
+ progress: function (e) {
161
+ e.target = xhr;
162
+ if (xhr.__listeners.progress) xhr.__listeners.progress(e);
163
+ xhr.__total = e.total;
164
+ xhr.__loaded = e.loaded;
165
+ if (e.total === e.loaded) {
166
+ // fix flash issue that doesn't call complete if there is no response text from the server
167
+ var _this = this;
168
+ setTimeout(function () {
169
+ if (!xhr.__completed) {
170
+ xhr.getAllResponseHeaders = function () {
171
+ };
172
+ _this.complete(null, {status: 204, statusText: 'No Content'});
173
+ }
174
+ }, FileAPI.noContentTimeout || 10000);
175
+ }
176
+ },
177
+ headers: xhr.__requestHeaders
178
+ };
179
+ config.data = {};
180
+ config.files = {};
181
+ for (var i = 0; i < formData.data.length; i++) {
182
+ var item = formData.data[i];
183
+ if (item.val != null && item.val.name != null && item.val.size != null && item.val.type != null) {
184
+ config.files[item.key] = item.val;
185
+ } else {
186
+ config.data[item.key] = item.val;
187
+ }
188
+ }
189
+
190
+ setTimeout(function () {
191
+ if (!FileAPI.hasFlash) {
192
+ throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
193
+ }
194
+ xhr.__fileApiXHR = FileAPI.upload(config);
195
+ }, 1);
196
+ } else {
197
+ if (this.__origError) {
198
+ throw this.__origError;
199
+ }
200
+ orig.apply(xhr, arguments);
201
+ }
202
+ };
203
+ });
204
+ window.XMLHttpRequest.__isFileAPIShim = true;
205
+ window.FormData = FormData = function () {
206
+ return {
207
+ append: function (key, val, name) {
208
+ if (val.__isFileAPIBlobShim) {
209
+ val = val.data[0];
210
+ }
211
+ this.data.push({
212
+ key: key,
213
+ val: val,
214
+ name: name
215
+ });
216
+ },
217
+ data: [],
218
+ __isFileAPIShim: true
219
+ };
220
+ };
221
+
222
+ window.Blob = Blob = function (b) {
223
+ return {
224
+ data: b,
225
+ __isFileAPIBlobShim: true
226
+ };
227
+ };
228
+ }
229
+
230
+ })();
231
+
232
+ (function () {
233
+ /** @namespace FileAPI.forceLoad */
234
+ /** @namespace window.FileAPI.jsUrl */
235
+ /** @namespace window.FileAPI.jsPath */
236
+
237
+ function isInputTypeFile(elem) {
238
+ return elem[0].tagName.toLowerCase() === 'input' && elem.attr('type') && elem.attr('type').toLowerCase() === 'file';
239
+ }
240
+
241
+ function hasFlash() {
242
+ try {
243
+ var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
244
+ if (fo) return true;
245
+ } catch (e) {
246
+ if (navigator.mimeTypes['application/x-shockwave-flash'] !== undefined) return true;
247
+ }
248
+ return false;
249
+ }
250
+
251
+ function getOffset(obj) {
252
+ var left = 0, top = 0;
253
+
254
+ if (window.jQuery) {
255
+ return jQuery(obj).offset();
256
+ }
257
+
258
+ if (obj.offsetParent) {
259
+ do {
260
+ left += (obj.offsetLeft - obj.scrollLeft);
261
+ top += (obj.offsetTop - obj.scrollTop);
262
+ obj = obj.offsetParent;
263
+ } while (obj);
264
+ }
265
+ return {
266
+ left: left,
267
+ top: top
268
+ };
269
+ }
270
+
271
+ if (FileAPI.shouldLoad) {
272
+ FileAPI.hasFlash = hasFlash();
273
+
274
+ //load FileAPI
275
+ if (FileAPI.forceLoad) {
276
+ FileAPI.html5 = false;
277
+ }
278
+
279
+ if (!FileAPI.upload) {
280
+ var jsUrl, basePath, script = document.createElement('script'), allScripts = document.getElementsByTagName('script'), i, index, src;
281
+ if (window.FileAPI.jsUrl) {
282
+ jsUrl = window.FileAPI.jsUrl;
283
+ } else if (window.FileAPI.jsPath) {
284
+ basePath = window.FileAPI.jsPath;
285
+ } else {
286
+ for (i = 0; i < allScripts.length; i++) {
287
+ src = allScripts[i].src;
288
+ index = src.search(/\/ng\-file\-upload[\-a-zA-z0-9\.]*\.js/);
289
+ if (index > -1) {
290
+ basePath = src.substring(0, index + 1);
291
+ break;
292
+ }
293
+ }
294
+ }
295
+
296
+ if (FileAPI.staticPath == null) FileAPI.staticPath = basePath;
297
+ script.setAttribute('src', jsUrl || basePath + 'FileAPI.min.js');
298
+ document.getElementsByTagName('head')[0].appendChild(script);
299
+ }
300
+
301
+ FileAPI.ngfFixIE = function (elem, fileElem, changeFn) {
302
+ if (!hasFlash()) {
303
+ throw 'Adode Flash Player need to be installed. To check ahead use "FileAPI.hasFlash"';
304
+ }
305
+ var fixInputStyle = function () {
306
+ var label = fileElem.parent();
307
+ if (elem.attr('disabled')) {
308
+ if (label) label.removeClass('js-fileapi-wrapper');
309
+ } else {
310
+ if (!fileElem.attr('__ngf_flash_')) {
311
+ fileElem.unbind('change');
312
+ fileElem.unbind('click');
313
+ fileElem.bind('change', function (evt) {
314
+ fileApiChangeFn.apply(this, [evt]);
315
+ changeFn.apply(this, [evt]);
316
+ });
317
+ fileElem.attr('__ngf_flash_', 'true');
318
+ }
319
+ label.addClass('js-fileapi-wrapper');
320
+ if (!isInputTypeFile(elem)) {
321
+ label.css('position', 'absolute')
322
+ .css('top', getOffset(elem[0]).top + 'px').css('left', getOffset(elem[0]).left + 'px')
323
+ .css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px')
324
+ .css('filter', 'alpha(opacity=0)').css('display', elem.css('display'))
325
+ .css('overflow', 'hidden').css('z-index', '900000')
326
+ .css('visibility', 'visible');
327
+ fileElem.css('width', elem[0].offsetWidth + 'px').css('height', elem[0].offsetHeight + 'px')
328
+ .css('position', 'absolute').css('top', '0px').css('left', '0px');
329
+ }
330
+ }
331
+ };
332
+
333
+ elem.bind('mouseenter', fixInputStyle);
334
+
335
+ var fileApiChangeFn = function (evt) {
336
+ var files = FileAPI.getFiles(evt);
337
+ //just a double check for #233
338
+ for (var i = 0; i < files.length; i++) {
339
+ if (files[i].size === undefined) files[i].size = 0;
340
+ if (files[i].name === undefined) files[i].name = 'file';
341
+ if (files[i].type === undefined) files[i].type = 'undefined';
342
+ }
343
+ if (!evt.target) {
344
+ evt.target = {};
345
+ }
346
+ evt.target.files = files;
347
+ // if evt.target.files is not writable use helper field
348
+ if (evt.target.files !== files) {
349
+ evt.__files_ = files;
350
+ }
351
+ (evt.__files_ || evt.target.files).item = function (i) {
352
+ return (evt.__files_ || evt.target.files)[i] || null;
353
+ };
354
+ };
355
+ };
356
+
357
+ FileAPI.disableFileInput = function (elem, disable) {
358
+ if (disable) {
359
+ elem.removeClass('js-fileapi-wrapper');
360
+ } else {
361
+ elem.addClass('js-fileapi-wrapper');
362
+ }
363
+ };
364
+ }
365
+ })();
366
+
367
+ if (!window.FileReader) {
368
+ window.FileReader = function () {
369
+ var _this = this, loadStarted = false;
370
+ this.listeners = {};
371
+ this.addEventListener = function (type, fn) {
372
+ _this.listeners[type] = _this.listeners[type] || [];
373
+ _this.listeners[type].push(fn);
374
+ };
375
+ this.removeEventListener = function (type, fn) {
376
+ if (_this.listeners[type]) _this.listeners[type].splice(_this.listeners[type].indexOf(fn), 1);
377
+ };
378
+ this.dispatchEvent = function (evt) {
379
+ var list = _this.listeners[evt.type];
380
+ if (list) {
381
+ for (var i = 0; i < list.length; i++) {
382
+ list[i].call(_this, evt);
383
+ }
384
+ }
385
+ };
386
+ this.onabort = this.onerror = this.onload = this.onloadstart = this.onloadend = this.onprogress = null;
387
+
388
+ var constructEvent = function (type, evt) {
389
+ var e = {type: type, target: _this, loaded: evt.loaded, total: evt.total, error: evt.error};
390
+ if (evt.result != null) e.target.result = evt.result;
391
+ return e;
392
+ };
393
+ var listener = function (evt) {
394
+ if (!loadStarted) {
395
+ loadStarted = true;
396
+ if (_this.onloadstart) _this.onloadstart(constructEvent('loadstart', evt));
397
+ }
398
+ var e;
399
+ if (evt.type === 'load') {
400
+ if (_this.onloadend) _this.onloadend(constructEvent('loadend', evt));
401
+ e = constructEvent('load', evt);
402
+ if (_this.onload) _this.onload(e);
403
+ _this.dispatchEvent(e);
404
+ } else if (evt.type === 'progress') {
405
+ e = constructEvent('progress', evt);
406
+ if (_this.onprogress) _this.onprogress(e);
407
+ _this.dispatchEvent(e);
408
+ } else {
409
+ e = constructEvent('error', evt);
410
+ if (_this.onerror) _this.onerror(e);
411
+ _this.dispatchEvent(e);
412
+ }
413
+ };
414
+ this.readAsDataURL = function (file) {
415
+ FileAPI.readAsDataURL(file, listener);
416
+ };
417
+ this.readAsText = function (file) {
418
+ FileAPI.readAsText(file, listener);
419
+ };
420
+ };
421
+ }
422
+
423
+ /**!
424
+ * AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
425
+ * progress, resize, thumbnail, preview, validation and CORS
426
+ * @author Danial <danial.farid@gmail.com>
427
+ * @version 12.2.13
428
+ */
429
+
430
+ if (window.XMLHttpRequest && !(window.FileAPI && FileAPI.shouldLoad)) {
431
+ window.XMLHttpRequest.prototype.setRequestHeader = (function (orig) {
432
+ return function (header, value) {
433
+ if (header === '__setXHR_') {
434
+ var val = value(this);
435
+ // fix for angular < 1.2.0
436
+ if (val instanceof Function) {
437
+ val(this);
438
+ }
439
+ } else {
440
+ orig.apply(this, arguments);
441
+ }
442
+ };
443
+ })(window.XMLHttpRequest.prototype.setRequestHeader);
444
+ }
445
+
446
+ var ngFileUpload = angular.module('ngFileUpload', []);
447
+
448
+ ngFileUpload.version = '12.2.13';
449
+
450
+ ngFileUpload.service('UploadBase', ['$http', '$q', '$timeout', function ($http, $q, $timeout) {
451
+ var upload = this;
452
+ upload.promisesCount = 0;
453
+
454
+ this.isResumeSupported = function () {
455
+ return window.Blob && window.Blob.prototype.slice;
456
+ };
457
+
458
+ var resumeSupported = this.isResumeSupported();
459
+
460
+ function sendHttp(config) {
461
+ config.method = config.method || 'POST';
462
+ config.headers = config.headers || {};
463
+
464
+ var deferred = config._deferred = config._deferred || $q.defer();
465
+ var promise = deferred.promise;
466
+
467
+ function notifyProgress(e) {
468
+ if (deferred.notify) {
469
+ deferred.notify(e);
470
+ }
471
+ if (promise.progressFunc) {
472
+ $timeout(function () {
473
+ promise.progressFunc(e);
474
+ });
475
+ }
476
+ }
477
+
478
+ function getNotifyEvent(n) {
479
+ if (config._start != null && resumeSupported) {
480
+ return {
481
+ loaded: n.loaded + config._start,
482
+ total: (config._file && config._file.size) || n.total,
483
+ type: n.type, config: config,
484
+ lengthComputable: true, target: n.target
485
+ };
486
+ } else {
487
+ return n;
488
+ }
489
+ }
490
+
491
+ if (!config.disableProgress) {
492
+ config.headers.__setXHR_ = function () {
493
+ return function (xhr) {
494
+ if (!xhr || !xhr.upload || !xhr.upload.addEventListener) return;
495
+ config.__XHR = xhr;
496
+ if (config.xhrFn) config.xhrFn(xhr);
497
+ xhr.upload.addEventListener('progress', function (e) {
498
+ e.config = config;
499
+ notifyProgress(getNotifyEvent(e));
500
+ }, false);
501
+ //fix for firefox not firing upload progress end, also IE8-9
502
+ xhr.upload.addEventListener('load', function (e) {
503
+ if (e.lengthComputable) {
504
+ e.config = config;
505
+ notifyProgress(getNotifyEvent(e));
506
+ }
507
+ }, false);
508
+ };
509
+ };
510
+ }
511
+
512
+ function uploadWithAngular() {
513
+ $http(config).then(function (r) {
514
+ if (resumeSupported && config._chunkSize && !config._finished && config._file) {
515
+ var fileSize = config._file && config._file.size || 0;
516
+ notifyProgress({
517
+ loaded: Math.min(config._end, fileSize),
518
+ total: fileSize,
519
+ config: config,
520
+ type: 'progress'
521
+ }
522
+ );
523
+ upload.upload(config, true);
524
+ } else {
525
+ if (config._finished) delete config._finished;
526
+ deferred.resolve(r);
527
+ }
528
+ }, function (e) {
529
+ deferred.reject(e);
530
+ }, function (n) {
531
+ deferred.notify(n);
532
+ }
533
+ );
534
+ }
535
+
536
+ if (!resumeSupported) {
537
+ uploadWithAngular();
538
+ } else if (config._chunkSize && config._end && !config._finished) {
539
+ config._start = config._end;
540
+ config._end += config._chunkSize;
541
+ uploadWithAngular();
542
+ } else if (config.resumeSizeUrl) {
543
+ $http.get(config.resumeSizeUrl).then(function (resp) {
544
+ if (config.resumeSizeResponseReader) {
545
+ config._start = config.resumeSizeResponseReader(resp.data);
546
+ } else {
547
+ config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString());
548
+ }
549
+ if (config._chunkSize) {
550
+ config._end = config._start + config._chunkSize;
551
+ }
552
+ uploadWithAngular();
553
+ }, function (e) {
554
+ throw e;
555
+ });
556
+ } else if (config.resumeSize) {
557
+ config.resumeSize().then(function (size) {
558
+ config._start = size;
559
+ if (config._chunkSize) {
560
+ config._end = config._start + config._chunkSize;
561
+ }
562
+ uploadWithAngular();
563
+ }, function (e) {
564
+ throw e;
565
+ });
566
+ } else {
567
+ if (config._chunkSize) {
568
+ config._start = 0;
569
+ config._end = config._start + config._chunkSize;
570
+ }
571
+ uploadWithAngular();
572
+ }
573
+
574
+
575
+ promise.success = function (fn) {
576
+ promise.then(function (response) {
577
+ fn(response.data, response.status, response.headers, config);
578
+ });
579
+ return promise;
580
+ };
581
+
582
+ promise.error = function (fn) {
583
+ promise.then(null, function (response) {
584
+ fn(response.data, response.status, response.headers, config);
585
+ });
586
+ return promise;
587
+ };
588
+
589
+ promise.progress = function (fn) {
590
+ promise.progressFunc = fn;
591
+ promise.then(null, null, function (n) {
592
+ fn(n);
593
+ });
594
+ return promise;
595
+ };
596
+ promise.abort = promise.pause = function () {
597
+ if (config.__XHR) {
598
+ $timeout(function () {
599
+ config.__XHR.abort();
600
+ });
601
+ }
602
+ return promise;
603
+ };
604
+ promise.xhr = function (fn) {
605
+ config.xhrFn = (function (origXhrFn) {
606
+ return function () {
607
+ if (origXhrFn) origXhrFn.apply(promise, arguments);
608
+ fn.apply(promise, arguments);
609
+ };
610
+ })(config.xhrFn);
611
+ return promise;
612
+ };
613
+
614
+ upload.promisesCount++;
615
+ if (promise['finally'] && promise['finally'] instanceof Function) {
616
+ promise['finally'](function () {
617
+ upload.promisesCount--;
618
+ });
619
+ }
620
+ return promise;
621
+ }
622
+
623
+ this.isUploadInProgress = function () {
624
+ return upload.promisesCount > 0;
625
+ };
626
+
627
+ this.rename = function (file, name) {
628
+ file.ngfName = name;
629
+ return file;
630
+ };
631
+
632
+ this.jsonBlob = function (val) {
633
+ if (val != null && !angular.isString(val)) {
634
+ val = JSON.stringify(val);
635
+ }
636
+ var blob = new window.Blob([val], {type: 'application/json'});
637
+ blob._ngfBlob = true;
638
+ return blob;
639
+ };
640
+
641
+ this.json = function (val) {
642
+ return angular.toJson(val);
643
+ };
644
+
645
+ function copy(obj) {
646
+ var clone = {};
647
+ for (var key in obj) {
648
+ if (obj.hasOwnProperty(key)) {
649
+ clone[key] = obj[key];
650
+ }
651
+ }
652
+ return clone;
653
+ }
654
+
655
+ this.isFile = function (file) {
656
+ return file != null && (file instanceof window.Blob || (file.flashId && file.name && file.size));
657
+ };
658
+
659
+ this.upload = function (config, internal) {
660
+ function toResumeFile(file, formData) {
661
+ if (file._ngfBlob) return file;
662
+ config._file = config._file || file;
663
+ if (config._start != null && resumeSupported) {
664
+ if (config._end && config._end >= file.size) {
665
+ config._finished = true;
666
+ config._end = file.size;
667
+ }
668
+ var slice = file.slice(config._start, config._end || file.size);
669
+ slice.name = file.name;
670
+ slice.ngfName = file.ngfName;
671
+ if (config._chunkSize) {
672
+ formData.append('_chunkSize', config._chunkSize);
673
+ formData.append('_currentChunkSize', config._end - config._start);
674
+ formData.append('_chunkNumber', Math.floor(config._start / config._chunkSize));
675
+ formData.append('_totalSize', config._file.size);
676
+ }
677
+ return slice;
678
+ }
679
+ return file;
680
+ }
681
+
682
+ function addFieldToFormData(formData, val, key) {
683
+ if (val !== undefined) {
684
+ if (angular.isDate(val)) {
685
+ val = val.toISOString();
686
+ }
687
+ if (angular.isString(val)) {
688
+ formData.append(key, val);
689
+ } else if (upload.isFile(val)) {
690
+ var file = toResumeFile(val, formData);
691
+ var split = key.split(',');
692
+ if (split[1]) {
693
+ file.ngfName = split[1].replace(/^\s+|\s+$/g, '');
694
+ key = split[0];
695
+ }
696
+ config._fileKey = config._fileKey || key;
697
+ formData.append(key, file, file.ngfName || file.name);
698
+ } else {
699
+ if (angular.isObject(val)) {
700
+ if (val.$$ngfCircularDetection) throw 'ngFileUpload: Circular reference in config.data. Make sure specified data for Upload.upload() has no circular reference: ' + key;
701
+
702
+ val.$$ngfCircularDetection = true;
703
+ try {
704
+ for (var k in val) {
705
+ if (val.hasOwnProperty(k) && k !== '$$ngfCircularDetection') {
706
+ var objectKey = config.objectKey == null ? '[i]' : config.objectKey;
707
+ if (val.length && parseInt(k) > -1) {
708
+ objectKey = config.arrayKey == null ? objectKey : config.arrayKey;
709
+ }
710
+ addFieldToFormData(formData, val[k], key + objectKey.replace(/[ik]/g, k));
711
+ }
712
+ }
713
+ } finally {
714
+ delete val.$$ngfCircularDetection;
715
+ }
716
+ } else {
717
+ formData.append(key, val);
718
+ }
719
+ }
720
+ }
721
+ }
722
+
723
+ function digestConfig() {
724
+ config._chunkSize = upload.translateScalars(config.resumeChunkSize);
725
+ config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
726
+
727
+ config.headers = config.headers || {};
728
+ config.headers['Content-Type'] = undefined;
729
+ config.transformRequest = config.transformRequest ?
730
+ (angular.isArray(config.transformRequest) ?
731
+ config.transformRequest : [config.transformRequest]) : [];
732
+ config.transformRequest.push(function (data) {
733
+ var formData = new window.FormData(), key;
734
+ data = data || config.fields || {};
735
+ if (config.file) {
736
+ data.file = config.file;
737
+ }
738
+ for (key in data) {
739
+ if (data.hasOwnProperty(key)) {
740
+ var val = data[key];
741
+ if (config.formDataAppender) {
742
+ config.formDataAppender(formData, key, val);
743
+ } else {
744
+ addFieldToFormData(formData, val, key);
745
+ }
746
+ }
747
+ }
748
+
749
+ return formData;
750
+ });
751
+ }
752
+
753
+ if (!internal) config = copy(config);
754
+ if (!config._isDigested) {
755
+ config._isDigested = true;
756
+ digestConfig();
757
+ }
758
+
759
+ return sendHttp(config);
760
+ };
761
+
762
+ this.http = function (config) {
763
+ config = copy(config);
764
+ config.transformRequest = config.transformRequest || function (data) {
765
+ if ((window.ArrayBuffer && data instanceof window.ArrayBuffer) || data instanceof window.Blob) {
766
+ return data;
767
+ }
768
+ return $http.defaults.transformRequest[0].apply(this, arguments);
769
+ };
770
+ config._chunkSize = upload.translateScalars(config.resumeChunkSize);
771
+ config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
772
+
773
+ return sendHttp(config);
774
+ };
775
+
776
+ this.translateScalars = function (str) {
777
+ if (angular.isString(str)) {
778
+ if (str.search(/kb/i) === str.length - 2) {
779
+ return parseFloat(str.substring(0, str.length - 2) * 1024);
780
+ } else if (str.search(/mb/i) === str.length - 2) {
781
+ return parseFloat(str.substring(0, str.length - 2) * 1048576);
782
+ } else if (str.search(/gb/i) === str.length - 2) {
783
+ return parseFloat(str.substring(0, str.length - 2) * 1073741824);
784
+ } else if (str.search(/b/i) === str.length - 1) {
785
+ return parseFloat(str.substring(0, str.length - 1));
786
+ } else if (str.search(/s/i) === str.length - 1) {
787
+ return parseFloat(str.substring(0, str.length - 1));
788
+ } else if (str.search(/m/i) === str.length - 1) {
789
+ return parseFloat(str.substring(0, str.length - 1) * 60);
790
+ } else if (str.search(/h/i) === str.length - 1) {
791
+ return parseFloat(str.substring(0, str.length - 1) * 3600);
792
+ }
793
+ }
794
+ return str;
795
+ };
796
+
797
+ this.urlToBlob = function(url) {
798
+ var defer = $q.defer();
799
+ $http({url: url, method: 'get', responseType: 'arraybuffer'}).then(function (resp) {
800
+ var arrayBufferView = new Uint8Array(resp.data);
801
+ var type = resp.headers('content-type') || 'image/WebP';
802
+ var blob = new window.Blob([arrayBufferView], {type: type});
803
+ var matches = url.match(/.*\/(.+?)(\?.*)?$/);
804
+ if (matches.length > 1) {
805
+ blob.name = matches[1];
806
+ }
807
+ defer.resolve(blob);
808
+ }, function (e) {
809
+ defer.reject(e);
810
+ });
811
+ return defer.promise;
812
+ };
813
+
814
+ this.setDefaults = function (defaults) {
815
+ this.defaults = defaults || {};
816
+ };
817
+
818
+ this.defaults = {};
819
+ this.version = ngFileUpload.version;
820
+ }
821
+
822
+ ]);
823
+
824
+ ngFileUpload.service('Upload', ['$parse', '$timeout', '$compile', '$q', 'UploadExif', function ($parse, $timeout, $compile, $q, UploadExif) {
825
+ var upload = UploadExif;
826
+ upload.getAttrWithDefaults = function (attr, name) {
827
+ if (attr[name] != null) return attr[name];
828
+ var def = upload.defaults[name];
829
+ return (def == null ? def : (angular.isString(def) ? def : JSON.stringify(def)));
830
+ };
831
+
832
+ upload.attrGetter = function (name, attr, scope, params) {
833
+ var attrVal = this.getAttrWithDefaults(attr, name);
834
+ if (scope) {
835
+ try {
836
+ if (params) {
837
+ return $parse(attrVal)(scope, params);
838
+ } else {
839
+ return $parse(attrVal)(scope);
840
+ }
841
+ } catch (e) {
842
+ // hangle string value without single qoute
843
+ if (name.search(/min|max|pattern/i)) {
844
+ return attrVal;
845
+ } else {
846
+ throw e;
847
+ }
848
+ }
849
+ } else {
850
+ return attrVal;
851
+ }
852
+ };
853
+
854
+ upload.shouldUpdateOn = function (type, attr, scope) {
855
+ var modelOptions = upload.attrGetter('ngfModelOptions', attr, scope);
856
+ if (modelOptions && modelOptions.updateOn) {
857
+ return modelOptions.updateOn.split(' ').indexOf(type) > -1;
858
+ }
859
+ return true;
860
+ };
861
+
862
+ upload.emptyPromise = function () {
863
+ var d = $q.defer();
864
+ var args = arguments;
865
+ $timeout(function () {
866
+ d.resolve.apply(d, args);
867
+ });
868
+ return d.promise;
869
+ };
870
+
871
+ upload.rejectPromise = function () {
872
+ var d = $q.defer();
873
+ var args = arguments;
874
+ $timeout(function () {
875
+ d.reject.apply(d, args);
876
+ });
877
+ return d.promise;
878
+ };
879
+
880
+ upload.happyPromise = function (promise, data) {
881
+ var d = $q.defer();
882
+ promise.then(function (result) {
883
+ d.resolve(result);
884
+ }, function (error) {
885
+ $timeout(function () {
886
+ throw error;
887
+ });
888
+ d.resolve(data);
889
+ });
890
+ return d.promise;
891
+ };
892
+
893
+ function applyExifRotations(files, attr, scope) {
894
+ var promises = [upload.emptyPromise()];
895
+ angular.forEach(files, function (f, i) {
896
+ if (f.type.indexOf('image/jpeg') === 0 && upload.attrGetter('ngfFixOrientation', attr, scope, {$file: f})) {
897
+ promises.push(upload.happyPromise(upload.applyExifRotation(f), f).then(function (fixedFile) {
898
+ files.splice(i, 1, fixedFile);
899
+ }));
900
+ }
901
+ });
902
+ return $q.all(promises);
903
+ }
904
+
905
+ function resizeFile(files, attr, scope, ngModel) {
906
+ var resizeVal = upload.attrGetter('ngfResize', attr, scope);
907
+ if (!resizeVal || !upload.isResizeSupported() || !files.length) return upload.emptyPromise();
908
+ if (resizeVal instanceof Function) {
909
+ var defer = $q.defer();
910
+ return resizeVal(files).then(function (p) {
911
+ resizeWithParams(p, files, attr, scope, ngModel).then(function (r) {
912
+ defer.resolve(r);
913
+ }, function (e) {
914
+ defer.reject(e);
915
+ });
916
+ }, function (e) {
917
+ defer.reject(e);
918
+ });
919
+ } else {
920
+ return resizeWithParams(resizeVal, files, attr, scope, ngModel);
921
+ }
922
+ }
923
+
924
+ function resizeWithParams(params, files, attr, scope, ngModel) {
925
+ var promises = [upload.emptyPromise()];
926
+
927
+ function handleFile(f, i) {
928
+ if (f.type.indexOf('image') === 0) {
929
+ if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
930
+ params.resizeIf = function (width, height) {
931
+ return upload.attrGetter('ngfResizeIf', attr, scope,
932
+ {$width: width, $height: height, $file: f});
933
+ };
934
+ var promise = upload.resize(f, params);
935
+ promises.push(promise);
936
+ promise.then(function (resizedFile) {
937
+ files.splice(i, 1, resizedFile);
938
+ }, function (e) {
939
+ f.$error = 'resize';
940
+ (f.$errorMessages = (f.$errorMessages || {})).resize = true;
941
+ f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
942
+ ngModel.$ngfValidations.push({name: 'resize', valid: false});
943
+ upload.applyModelValidation(ngModel, files);
944
+ });
945
+ }
946
+ }
947
+
948
+ for (var i = 0; i < files.length; i++) {
949
+ handleFile(files[i], i);
950
+ }
951
+ return $q.all(promises);
952
+ }
953
+
954
+ upload.updateModel = function (ngModel, attr, scope, fileChange, files, evt, noDelay) {
955
+ function update(files, invalidFiles, newFiles, dupFiles, isSingleModel) {
956
+ attr.$$ngfPrevValidFiles = files;
957
+ attr.$$ngfPrevInvalidFiles = invalidFiles;
958
+ var file = files && files.length ? files[0] : null;
959
+ var invalidFile = invalidFiles && invalidFiles.length ? invalidFiles[0] : null;
960
+
961
+ if (ngModel) {
962
+ upload.applyModelValidation(ngModel, files);
963
+ ngModel.$setViewValue(isSingleModel ? file : files);
964
+ }
965
+
966
+ if (fileChange) {
967
+ $parse(fileChange)(scope, {
968
+ $files: files,
969
+ $file: file,
970
+ $newFiles: newFiles,
971
+ $duplicateFiles: dupFiles,
972
+ $invalidFiles: invalidFiles,
973
+ $invalidFile: invalidFile,
974
+ $event: evt
975
+ });
976
+ }
977
+
978
+ var invalidModel = upload.attrGetter('ngfModelInvalid', attr);
979
+ if (invalidModel) {
980
+ $timeout(function () {
981
+ $parse(invalidModel).assign(scope, isSingleModel ? invalidFile : invalidFiles);
982
+ });
983
+ }
984
+ $timeout(function () {
985
+ // scope apply changes
986
+ });
987
+ }
988
+
989
+ var allNewFiles, dupFiles = [], prevValidFiles, prevInvalidFiles,
990
+ invalids = [], valids = [];
991
+
992
+ function removeDuplicates() {
993
+ function equals(f1, f2) {
994
+ return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
995
+ f1.type === f2.type;
996
+ }
997
+
998
+ function isInPrevFiles(f) {
999
+ var j;
1000
+ for (j = 0; j < prevValidFiles.length; j++) {
1001
+ if (equals(f, prevValidFiles[j])) {
1002
+ return true;
1003
+ }
1004
+ }
1005
+ for (j = 0; j < prevInvalidFiles.length; j++) {
1006
+ if (equals(f, prevInvalidFiles[j])) {
1007
+ return true;
1008
+ }
1009
+ }
1010
+ return false;
1011
+ }
1012
+
1013
+ if (files) {
1014
+ allNewFiles = [];
1015
+ dupFiles = [];
1016
+ for (var i = 0; i < files.length; i++) {
1017
+ if (isInPrevFiles(files[i])) {
1018
+ dupFiles.push(files[i]);
1019
+ } else {
1020
+ allNewFiles.push(files[i]);
1021
+ }
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ function toArray(v) {
1027
+ return angular.isArray(v) ? v : [v];
1028
+ }
1029
+
1030
+ function resizeAndUpdate() {
1031
+ function updateModel() {
1032
+ $timeout(function () {
1033
+ update(keep ? prevValidFiles.concat(valids) : valids,
1034
+ keep ? prevInvalidFiles.concat(invalids) : invalids,
1035
+ files, dupFiles, isSingleModel);
1036
+ }, options && options.debounce ? options.debounce.change || options.debounce : 0);
1037
+ }
1038
+
1039
+ var resizingFiles = validateAfterResize ? allNewFiles : valids;
1040
+ resizeFile(resizingFiles, attr, scope, ngModel).then(function () {
1041
+ if (validateAfterResize) {
1042
+ upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
1043
+ .then(function (validationResult) {
1044
+ valids = validationResult.validsFiles;
1045
+ invalids = validationResult.invalidsFiles;
1046
+ updateModel();
1047
+ });
1048
+ } else {
1049
+ updateModel();
1050
+ }
1051
+ }, function () {
1052
+ for (var i = 0; i < resizingFiles.length; i++) {
1053
+ var f = resizingFiles[i];
1054
+ if (f.$error === 'resize') {
1055
+ var index = valids.indexOf(f);
1056
+ if (index > -1) {
1057
+ valids.splice(index, 1);
1058
+ invalids.push(f);
1059
+ }
1060
+ updateModel();
1061
+ }
1062
+ }
1063
+ });
1064
+ }
1065
+
1066
+ prevValidFiles = attr.$$ngfPrevValidFiles || [];
1067
+ prevInvalidFiles = attr.$$ngfPrevInvalidFiles || [];
1068
+ if (ngModel && ngModel.$modelValue) {
1069
+ prevValidFiles = toArray(ngModel.$modelValue);
1070
+ }
1071
+
1072
+ var keep = upload.attrGetter('ngfKeep', attr, scope);
1073
+ allNewFiles = (files || []).slice(0);
1074
+ if (keep === 'distinct' || upload.attrGetter('ngfKeepDistinct', attr, scope) === true) {
1075
+ removeDuplicates(attr, scope);
1076
+ }
1077
+
1078
+ var isSingleModel = !keep && !upload.attrGetter('ngfMultiple', attr, scope) && !upload.attrGetter('multiple', attr);
1079
+
1080
+ if (keep && !allNewFiles.length) return;
1081
+
1082
+ upload.attrGetter('ngfBeforeModelChange', attr, scope, {
1083
+ $files: files,
1084
+ $file: files && files.length ? files[0] : null,
1085
+ $newFiles: allNewFiles,
1086
+ $duplicateFiles: dupFiles,
1087
+ $event: evt
1088
+ });
1089
+
1090
+ var validateAfterResize = upload.attrGetter('ngfValidateAfterResize', attr, scope);
1091
+
1092
+ var options = upload.attrGetter('ngfModelOptions', attr, scope);
1093
+ upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
1094
+ .then(function (validationResult) {
1095
+ if (noDelay) {
1096
+ update(allNewFiles, [], files, dupFiles, isSingleModel);
1097
+ } else {
1098
+ if ((!options || !options.allowInvalid) && !validateAfterResize) {
1099
+ valids = validationResult.validFiles;
1100
+ invalids = validationResult.invalidFiles;
1101
+ } else {
1102
+ valids = allNewFiles;
1103
+ }
1104
+ if (upload.attrGetter('ngfFixOrientation', attr, scope) && upload.isExifSupported()) {
1105
+ applyExifRotations(valids, attr, scope).then(function () {
1106
+ resizeAndUpdate();
1107
+ });
1108
+ } else {
1109
+ resizeAndUpdate();
1110
+ }
1111
+ }
1112
+ });
1113
+ };
1114
+
1115
+ return upload;
1116
+ }]);
1117
+
1118
+ ngFileUpload.directive('ngfSelect', ['$parse', '$timeout', '$compile', 'Upload', function ($parse, $timeout, $compile, Upload) {
1119
+ var generatedElems = [];
1120
+
1121
+ function isDelayedClickSupported(ua) {
1122
+ // fix for android native browser < 4.4 and safari windows
1123
+ var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/);
1124
+ if (m && m.length > 2) {
1125
+ var v = Upload.defaults.androidFixMinorVersion || 4;
1126
+ return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v);
1127
+ }
1128
+
1129
+ // safari on windows
1130
+ return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua);
1131
+ }
1132
+
1133
+ function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) {
1134
+ /** @namespace attr.ngfSelect */
1135
+ /** @namespace attr.ngfChange */
1136
+ /** @namespace attr.ngModel */
1137
+ /** @namespace attr.ngfModelOptions */
1138
+ /** @namespace attr.ngfMultiple */
1139
+ /** @namespace attr.ngfCapture */
1140
+ /** @namespace attr.ngfValidate */
1141
+ /** @namespace attr.ngfKeep */
1142
+ var attrGetter = function (name, scope) {
1143
+ return upload.attrGetter(name, attr, scope);
1144
+ };
1145
+
1146
+ function isInputTypeFile() {
1147
+ return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file';
1148
+ }
1149
+
1150
+ function fileChangeAttr() {
1151
+ return attrGetter('ngfChange') || attrGetter('ngfSelect');
1152
+ }
1153
+
1154
+ function changeFn(evt) {
1155
+ if (upload.shouldUpdateOn('change', attr, scope)) {
1156
+ var fileList = evt.__files_ || (evt.target && evt.target.files), files = [];
1157
+ /* Handle duplicate call in IE11 */
1158
+ if (!fileList) return;
1159
+ for (var i = 0; i < fileList.length; i++) {
1160
+ files.push(fileList[i]);
1161
+ }
1162
+ upload.updateModel(ngModel, attr, scope, fileChangeAttr(),
1163
+ files.length ? files : null, evt);
1164
+ }
1165
+ }
1166
+
1167
+ upload.registerModelChangeValidator(ngModel, attr, scope);
1168
+
1169
+ var unwatches = [];
1170
+ if (attrGetter('ngfMultiple')) {
1171
+ unwatches.push(scope.$watch(attrGetter('ngfMultiple'), function () {
1172
+ fileElem.attr('multiple', attrGetter('ngfMultiple', scope));
1173
+ }));
1174
+ }
1175
+ if (attrGetter('ngfCapture')) {
1176
+ unwatches.push(scope.$watch(attrGetter('ngfCapture'), function () {
1177
+ fileElem.attr('capture', attrGetter('ngfCapture', scope));
1178
+ }));
1179
+ }
1180
+ if (attrGetter('ngfAccept')) {
1181
+ unwatches.push(scope.$watch(attrGetter('ngfAccept'), function () {
1182
+ fileElem.attr('accept', attrGetter('ngfAccept', scope));
1183
+ }));
1184
+ }
1185
+ unwatches.push(attr.$observe('accept', function () {
1186
+ fileElem.attr('accept', attrGetter('accept'));
1187
+ }));
1188
+ function bindAttrToFileInput(fileElem, label) {
1189
+ function updateId(val) {
1190
+ fileElem.attr('id', 'ngf-' + val);
1191
+ label.attr('id', 'ngf-label-' + val);
1192
+ }
1193
+
1194
+ for (var i = 0; i < elem[0].attributes.length; i++) {
1195
+ var attribute = elem[0].attributes[i];
1196
+ if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'style') {
1197
+ if (attribute.name === 'id') {
1198
+ updateId(attribute.value);
1199
+ unwatches.push(attr.$observe('id', updateId));
1200
+ } else {
1201
+ fileElem.attr(attribute.name, (!attribute.value && (attribute.name === 'required' ||
1202
+ attribute.name === 'multiple')) ? attribute.name : attribute.value);
1203
+ }
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ function createFileInput() {
1209
+ if (isInputTypeFile()) {
1210
+ return elem;
1211
+ }
1212
+
1213
+ var fileElem = angular.element('<input type="file">');
1214
+
1215
+ var label = angular.element('<label>upload</label>');
1216
+ label.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden')
1217
+ .css('width', '0px').css('height', '0px').css('border', 'none')
1218
+ .css('margin', '0px').css('padding', '0px').attr('tabindex', '-1');
1219
+ bindAttrToFileInput(fileElem, label);
1220
+
1221
+ generatedElems.push({el: elem, ref: label});
1222
+
1223
+ document.body.appendChild(label.append(fileElem)[0]);
1224
+
1225
+ return fileElem;
1226
+ }
1227
+
1228
+ function clickHandler(evt) {
1229
+ if (elem.attr('disabled')) return false;
1230
+ if (attrGetter('ngfSelectDisabled', scope)) return;
1231
+
1232
+ var r = detectSwipe(evt);
1233
+ // prevent the click if it is a swipe
1234
+ if (r != null) return r;
1235
+
1236
+ resetModel(evt);
1237
+
1238
+ // fix for md when the element is removed from the DOM and added back #460
1239
+ try {
1240
+ if (!isInputTypeFile() && !document.body.contains(fileElem[0])) {
1241
+ generatedElems.push({el: elem, ref: fileElem.parent()});
1242
+ document.body.appendChild(fileElem.parent()[0]);
1243
+ fileElem.bind('change', changeFn);
1244
+ }
1245
+ } catch (e) {/*ignore*/
1246
+ }
1247
+
1248
+ if (isDelayedClickSupported(navigator.userAgent)) {
1249
+ setTimeout(function () {
1250
+ fileElem[0].click();
1251
+ }, 0);
1252
+ } else {
1253
+ fileElem[0].click();
1254
+ }
1255
+
1256
+ return false;
1257
+ }
1258
+
1259
+
1260
+ var initialTouchStartY = 0;
1261
+ var initialTouchStartX = 0;
1262
+
1263
+ function detectSwipe(evt) {
1264
+ var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
1265
+ if (touches) {
1266
+ if (evt.type === 'touchstart') {
1267
+ initialTouchStartX = touches[0].clientX;
1268
+ initialTouchStartY = touches[0].clientY;
1269
+ return true; // don't block event default
1270
+ } else {
1271
+ // prevent scroll from triggering event
1272
+ if (evt.type === 'touchend') {
1273
+ var currentX = touches[0].clientX;
1274
+ var currentY = touches[0].clientY;
1275
+ if ((Math.abs(currentX - initialTouchStartX) > 20) ||
1276
+ (Math.abs(currentY - initialTouchStartY) > 20)) {
1277
+ evt.stopPropagation();
1278
+ evt.preventDefault();
1279
+ return false;
1280
+ }
1281
+ }
1282
+ return true;
1283
+ }
1284
+ }
1285
+ }
1286
+
1287
+ var fileElem = elem;
1288
+
1289
+ function resetModel(evt) {
1290
+ if (upload.shouldUpdateOn('click', attr, scope) && fileElem.val()) {
1291
+ fileElem.val(null);
1292
+ upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true);
1293
+ }
1294
+ }
1295
+
1296
+ if (!isInputTypeFile()) {
1297
+ fileElem = createFileInput();
1298
+ }
1299
+ fileElem.bind('change', changeFn);
1300
+
1301
+ if (!isInputTypeFile()) {
1302
+ elem.bind('click touchstart touchend', clickHandler);
1303
+ } else {
1304
+ elem.bind('click', resetModel);
1305
+ }
1306
+
1307
+ function ie10SameFileSelectFix(evt) {
1308
+ if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) {
1309
+ if (!fileElem[0].parentNode) {
1310
+ fileElem = null;
1311
+ return;
1312
+ }
1313
+ evt.preventDefault();
1314
+ evt.stopPropagation();
1315
+ fileElem.unbind('click');
1316
+ var clone = fileElem.clone();
1317
+ fileElem.replaceWith(clone);
1318
+ fileElem = clone;
1319
+ fileElem.attr('__ngf_ie10_Fix_', 'true');
1320
+ fileElem.bind('change', changeFn);
1321
+ fileElem.bind('click', ie10SameFileSelectFix);
1322
+ fileElem[0].click();
1323
+ return false;
1324
+ } else {
1325
+ fileElem.removeAttr('__ngf_ie10_Fix_');
1326
+ }
1327
+ }
1328
+
1329
+ if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
1330
+ fileElem.bind('click', ie10SameFileSelectFix);
1331
+ }
1332
+
1333
+ if (ngModel) ngModel.$formatters.push(function (val) {
1334
+ if (val == null || val.length === 0) {
1335
+ if (fileElem.val()) {
1336
+ fileElem.val(null);
1337
+ }
1338
+ }
1339
+ return val;
1340
+ });
1341
+
1342
+ scope.$on('$destroy', function () {
1343
+ if (!isInputTypeFile()) fileElem.parent().remove();
1344
+ angular.forEach(unwatches, function (unwatch) {
1345
+ unwatch();
1346
+ });
1347
+ });
1348
+
1349
+ $timeout(function () {
1350
+ for (var i = 0; i < generatedElems.length; i++) {
1351
+ var g = generatedElems[i];
1352
+ if (!document.body.contains(g.el[0])) {
1353
+ generatedElems.splice(i, 1);
1354
+ g.ref.remove();
1355
+ }
1356
+ }
1357
+ });
1358
+
1359
+ if (window.FileAPI && window.FileAPI.ngfFixIE) {
1360
+ window.FileAPI.ngfFixIE(elem, fileElem, changeFn);
1361
+ }
1362
+ }
1363
+
1364
+ return {
1365
+ restrict: 'AEC',
1366
+ require: '?ngModel',
1367
+ link: function (scope, elem, attr, ngModel) {
1368
+ linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, Upload);
1369
+ }
1370
+ };
1371
+ }]);
1372
+
1373
+ (function () {
1374
+
1375
+ ngFileUpload.service('UploadDataUrl', ['UploadBase', '$timeout', '$q', function (UploadBase, $timeout, $q) {
1376
+ var upload = UploadBase;
1377
+ upload.base64DataUrl = function (file) {
1378
+ if (angular.isArray(file)) {
1379
+ var d = $q.defer(), count = 0;
1380
+ angular.forEach(file, function (f) {
1381
+ upload.dataUrl(f, true)['finally'](function () {
1382
+ count++;
1383
+ if (count === file.length) {
1384
+ var urls = [];
1385
+ angular.forEach(file, function (ff) {
1386
+ urls.push(ff.$ngfDataUrl);
1387
+ });
1388
+ d.resolve(urls, file);
1389
+ }
1390
+ });
1391
+ });
1392
+ return d.promise;
1393
+ } else {
1394
+ return upload.dataUrl(file, true);
1395
+ }
1396
+ };
1397
+ upload.dataUrl = function (file, disallowObjectUrl) {
1398
+ if (!file) return upload.emptyPromise(file, file);
1399
+ if ((disallowObjectUrl && file.$ngfDataUrl != null) || (!disallowObjectUrl && file.$ngfBlobUrl != null)) {
1400
+ return upload.emptyPromise(disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl, file);
1401
+ }
1402
+ var p = disallowObjectUrl ? file.$$ngfDataUrlPromise : file.$$ngfBlobUrlPromise;
1403
+ if (p) return p;
1404
+
1405
+ var deferred = $q.defer();
1406
+ $timeout(function () {
1407
+ if (window.FileReader && file &&
1408
+ (!window.FileAPI || navigator.userAgent.indexOf('MSIE 8') === -1 || file.size < 20000) &&
1409
+ (!window.FileAPI || navigator.userAgent.indexOf('MSIE 9') === -1 || file.size < 4000000)) {
1410
+ //prefer URL.createObjectURL for handling refrences to files of all sizes
1411
+ //since it doesn´t build a large string in memory
1412
+ var URL = window.URL || window.webkitURL;
1413
+ if (URL && URL.createObjectURL && !disallowObjectUrl) {
1414
+ var url;
1415
+ try {
1416
+ url = URL.createObjectURL(file);
1417
+ } catch (e) {
1418
+ $timeout(function () {
1419
+ file.$ngfBlobUrl = '';
1420
+ deferred.reject();
1421
+ });
1422
+ return;
1423
+ }
1424
+ $timeout(function () {
1425
+ file.$ngfBlobUrl = url;
1426
+ if (url) {
1427
+ deferred.resolve(url, file);
1428
+ upload.blobUrls = upload.blobUrls || [];
1429
+ upload.blobUrlsTotalSize = upload.blobUrlsTotalSize || 0;
1430
+ upload.blobUrls.push({url: url, size: file.size});
1431
+ upload.blobUrlsTotalSize += file.size || 0;
1432
+ var maxMemory = upload.defaults.blobUrlsMaxMemory || 268435456;
1433
+ var maxLength = upload.defaults.blobUrlsMaxQueueSize || 200;
1434
+ while ((upload.blobUrlsTotalSize > maxMemory || upload.blobUrls.length > maxLength) && upload.blobUrls.length > 1) {
1435
+ var obj = upload.blobUrls.splice(0, 1)[0];
1436
+ URL.revokeObjectURL(obj.url);
1437
+ upload.blobUrlsTotalSize -= obj.size;
1438
+ }
1439
+ }
1440
+ });
1441
+ } else {
1442
+ var fileReader = new FileReader();
1443
+ fileReader.onload = function (e) {
1444
+ $timeout(function () {
1445
+ file.$ngfDataUrl = e.target.result;
1446
+ deferred.resolve(e.target.result, file);
1447
+ $timeout(function () {
1448
+ delete file.$ngfDataUrl;
1449
+ }, 1000);
1450
+ });
1451
+ };
1452
+ fileReader.onerror = function () {
1453
+ $timeout(function () {
1454
+ file.$ngfDataUrl = '';
1455
+ deferred.reject();
1456
+ });
1457
+ };
1458
+ fileReader.readAsDataURL(file);
1459
+ }
1460
+ } else {
1461
+ $timeout(function () {
1462
+ file[disallowObjectUrl ? '$ngfDataUrl' : '$ngfBlobUrl'] = '';
1463
+ deferred.reject();
1464
+ });
1465
+ }
1466
+ });
1467
+
1468
+ if (disallowObjectUrl) {
1469
+ p = file.$$ngfDataUrlPromise = deferred.promise;
1470
+ } else {
1471
+ p = file.$$ngfBlobUrlPromise = deferred.promise;
1472
+ }
1473
+ p['finally'](function () {
1474
+ delete file[disallowObjectUrl ? '$$ngfDataUrlPromise' : '$$ngfBlobUrlPromise'];
1475
+ });
1476
+ return p;
1477
+ };
1478
+ return upload;
1479
+ }]);
1480
+
1481
+ function getTagType(el) {
1482
+ if (el.tagName.toLowerCase() === 'img') return 'image';
1483
+ if (el.tagName.toLowerCase() === 'audio') return 'audio';
1484
+ if (el.tagName.toLowerCase() === 'video') return 'video';
1485
+ return /./;
1486
+ }
1487
+
1488
+ function linkFileDirective(Upload, $timeout, scope, elem, attr, directiveName, resizeParams, isBackground) {
1489
+ function constructDataUrl(file) {
1490
+ var disallowObjectUrl = Upload.attrGetter('ngfNoObjectUrl', attr, scope);
1491
+ Upload.dataUrl(file, disallowObjectUrl)['finally'](function () {
1492
+ $timeout(function () {
1493
+ var src = (disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl;
1494
+ if (isBackground) {
1495
+ elem.css('background-image', 'url(\'' + (src || '') + '\')');
1496
+ } else {
1497
+ elem.attr('src', src);
1498
+ }
1499
+ if (src) {
1500
+ elem.removeClass('ng-hide');
1501
+ } else {
1502
+ elem.addClass('ng-hide');
1503
+ }
1504
+ });
1505
+ });
1506
+ }
1507
+
1508
+ $timeout(function () {
1509
+ var unwatch = scope.$watch(attr[directiveName], function (file) {
1510
+ var size = resizeParams;
1511
+ if (directiveName === 'ngfThumbnail') {
1512
+ if (!size) {
1513
+ size = {
1514
+ width: elem[0].naturalWidth || elem[0].clientWidth,
1515
+ height: elem[0].naturalHeight || elem[0].clientHeight
1516
+ };
1517
+ }
1518
+ if (size.width === 0 && window.getComputedStyle) {
1519
+ var style = getComputedStyle(elem[0]);
1520
+ if (style.width && style.width.indexOf('px') > -1 && style.height && style.height.indexOf('px') > -1) {
1521
+ size = {
1522
+ width: parseInt(style.width.slice(0, -2)),
1523
+ height: parseInt(style.height.slice(0, -2))
1524
+ };
1525
+ }
1526
+ }
1527
+ }
1528
+
1529
+ if (angular.isString(file)) {
1530
+ elem.removeClass('ng-hide');
1531
+ if (isBackground) {
1532
+ return elem.css('background-image', 'url(\'' + file + '\')');
1533
+ } else {
1534
+ return elem.attr('src', file);
1535
+ }
1536
+ }
1537
+ if (file && file.type && file.type.search(getTagType(elem[0])) === 0 &&
1538
+ (!isBackground || file.type.indexOf('image') === 0)) {
1539
+ if (size && Upload.isResizeSupported()) {
1540
+ size.resizeIf = function (width, height) {
1541
+ return Upload.attrGetter('ngfResizeIf', attr, scope,
1542
+ {$width: width, $height: height, $file: file});
1543
+ };
1544
+ Upload.resize(file, size).then(
1545
+ function (f) {
1546
+ constructDataUrl(f);
1547
+ }, function (e) {
1548
+ throw e;
1549
+ }
1550
+ );
1551
+ } else {
1552
+ constructDataUrl(file);
1553
+ }
1554
+ } else {
1555
+ elem.addClass('ng-hide');
1556
+ }
1557
+ });
1558
+
1559
+ scope.$on('$destroy', function () {
1560
+ unwatch();
1561
+ });
1562
+ });
1563
+ }
1564
+
1565
+
1566
+ /** @namespace attr.ngfSrc */
1567
+ /** @namespace attr.ngfNoObjectUrl */
1568
+ ngFileUpload.directive('ngfSrc', ['Upload', '$timeout', function (Upload, $timeout) {
1569
+ return {
1570
+ restrict: 'AE',
1571
+ link: function (scope, elem, attr) {
1572
+ linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfSrc',
1573
+ Upload.attrGetter('ngfResize', attr, scope), false);
1574
+ }
1575
+ };
1576
+ }]);
1577
+
1578
+ /** @namespace attr.ngfBackground */
1579
+ /** @namespace attr.ngfNoObjectUrl */
1580
+ ngFileUpload.directive('ngfBackground', ['Upload', '$timeout', function (Upload, $timeout) {
1581
+ return {
1582
+ restrict: 'AE',
1583
+ link: function (scope, elem, attr) {
1584
+ linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfBackground',
1585
+ Upload.attrGetter('ngfResize', attr, scope), true);
1586
+ }
1587
+ };
1588
+ }]);
1589
+
1590
+ /** @namespace attr.ngfThumbnail */
1591
+ /** @namespace attr.ngfAsBackground */
1592
+ /** @namespace attr.ngfSize */
1593
+ /** @namespace attr.ngfNoObjectUrl */
1594
+ ngFileUpload.directive('ngfThumbnail', ['Upload', '$timeout', function (Upload, $timeout) {
1595
+ return {
1596
+ restrict: 'AE',
1597
+ link: function (scope, elem, attr) {
1598
+ var size = Upload.attrGetter('ngfSize', attr, scope);
1599
+ linkFileDirective(Upload, $timeout, scope, elem, attr, 'ngfThumbnail', size,
1600
+ Upload.attrGetter('ngfAsBackground', attr, scope));
1601
+ }
1602
+ };
1603
+ }]);
1604
+
1605
+ ngFileUpload.config(['$compileProvider', function ($compileProvider) {
1606
+ if ($compileProvider.imgSrcSanitizationWhitelist) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|webcal|local|file|data|blob):/);
1607
+ if ($compileProvider.aHrefSanitizationWhitelist) $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|webcal|local|file|data|blob):/);
1608
+ }]);
1609
+
1610
+ ngFileUpload.filter('ngfDataUrl', ['UploadDataUrl', '$sce', function (UploadDataUrl, $sce) {
1611
+ return function (file, disallowObjectUrl, trustedUrl) {
1612
+ if (angular.isString(file)) {
1613
+ return $sce.trustAsResourceUrl(file);
1614
+ }
1615
+ var src = file && ((disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl) || file.$ngfDataUrl);
1616
+ if (file && !src) {
1617
+ if (!file.$ngfDataUrlFilterInProgress && angular.isObject(file)) {
1618
+ file.$ngfDataUrlFilterInProgress = true;
1619
+ UploadDataUrl.dataUrl(file, disallowObjectUrl);
1620
+ }
1621
+ return '';
1622
+ }
1623
+ if (file) delete file.$ngfDataUrlFilterInProgress;
1624
+ return (file && src ? (trustedUrl ? $sce.trustAsResourceUrl(src) : src) : file) || '';
1625
+ };
1626
+ }]);
1627
+
1628
+ })();
1629
+
1630
+ ngFileUpload.service('UploadValidate', ['UploadDataUrl', '$q', '$timeout', function (UploadDataUrl, $q, $timeout) {
1631
+ var upload = UploadDataUrl;
1632
+
1633
+ function globStringToRegex(str) {
1634
+ var regexp = '', excludes = [];
1635
+ if (str.length > 2 && str[0] === '/' && str[str.length - 1] === '/') {
1636
+ regexp = str.substring(1, str.length - 1);
1637
+ } else {
1638
+ var split = str.split(',');
1639
+ if (split.length > 1) {
1640
+ for (var i = 0; i < split.length; i++) {
1641
+ var r = globStringToRegex(split[i]);
1642
+ if (r.regexp) {
1643
+ regexp += '(' + r.regexp + ')';
1644
+ if (i < split.length - 1) {
1645
+ regexp += '|';
1646
+ }
1647
+ } else {
1648
+ excludes = excludes.concat(r.excludes);
1649
+ }
1650
+ }
1651
+ } else {
1652
+ if (str.indexOf('!') === 0) {
1653
+ excludes.push('^((?!' + globStringToRegex(str.substring(1)).regexp + ').)*$');
1654
+ } else {
1655
+ if (str.indexOf('.') === 0) {
1656
+ str = '*' + str;
1657
+ }
1658
+ regexp = '^' + str.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g'), '\\$&') + '$';
1659
+ regexp = regexp.replace(/\\\*/g, '.*').replace(/\\\?/g, '.');
1660
+ }
1661
+ }
1662
+ }
1663
+ return {regexp: regexp, excludes: excludes};
1664
+ }
1665
+
1666
+ upload.validatePattern = function (file, val) {
1667
+ if (!val) {
1668
+ return true;
1669
+ }
1670
+ var pattern = globStringToRegex(val), valid = true;
1671
+ if (pattern.regexp && pattern.regexp.length) {
1672
+ var regexp = new RegExp(pattern.regexp, 'i');
1673
+ valid = (file.type != null && regexp.test(file.type)) ||
1674
+ (file.name != null && regexp.test(file.name));
1675
+ }
1676
+ var len = pattern.excludes.length;
1677
+ while (len--) {
1678
+ var exclude = new RegExp(pattern.excludes[len], 'i');
1679
+ valid = valid && (file.type == null || exclude.test(file.type)) &&
1680
+ (file.name == null || exclude.test(file.name));
1681
+ }
1682
+ return valid;
1683
+ };
1684
+
1685
+ upload.ratioToFloat = function (val) {
1686
+ var r = val.toString(), xIndex = r.search(/[x:]/i);
1687
+ if (xIndex > -1) {
1688
+ r = parseFloat(r.substring(0, xIndex)) / parseFloat(r.substring(xIndex + 1));
1689
+ } else {
1690
+ r = parseFloat(r);
1691
+ }
1692
+ return r;
1693
+ };
1694
+
1695
+ upload.registerModelChangeValidator = function (ngModel, attr, scope) {
1696
+ if (ngModel) {
1697
+ ngModel.$formatters.push(function (files) {
1698
+ if (ngModel.$dirty) {
1699
+ var filesArray = files;
1700
+ if (files && !angular.isArray(files)) {
1701
+ filesArray = [files];
1702
+ }
1703
+ upload.validate(filesArray, 0, ngModel, attr, scope).then(function () {
1704
+ upload.applyModelValidation(ngModel, filesArray);
1705
+ });
1706
+ }
1707
+ return files;
1708
+ });
1709
+ }
1710
+ };
1711
+
1712
+ function markModelAsDirty(ngModel, files) {
1713
+ if (files != null && !ngModel.$dirty) {
1714
+ if (ngModel.$setDirty) {
1715
+ ngModel.$setDirty();
1716
+ } else {
1717
+ ngModel.$dirty = true;
1718
+ }
1719
+ }
1720
+ }
1721
+
1722
+ upload.applyModelValidation = function (ngModel, files) {
1723
+ markModelAsDirty(ngModel, files);
1724
+ angular.forEach(ngModel.$ngfValidations, function (validation) {
1725
+ ngModel.$setValidity(validation.name, validation.valid);
1726
+ });
1727
+ };
1728
+
1729
+ upload.getValidationAttr = function (attr, scope, name, validationName, file) {
1730
+ var dName = 'ngf' + name[0].toUpperCase() + name.substr(1);
1731
+ var val = upload.attrGetter(dName, attr, scope, {$file: file});
1732
+ if (val == null) {
1733
+ val = upload.attrGetter('ngfValidate', attr, scope, {$file: file});
1734
+ if (val) {
1735
+ var split = (validationName || name).split('.');
1736
+ val = val[split[0]];
1737
+ if (split.length > 1) {
1738
+ val = val && val[split[1]];
1739
+ }
1740
+ }
1741
+ }
1742
+ return val;
1743
+ };
1744
+
1745
+ upload.validate = function (files, prevLength, ngModel, attr, scope) {
1746
+ ngModel = ngModel || {};
1747
+ ngModel.$ngfValidations = ngModel.$ngfValidations || [];
1748
+
1749
+ angular.forEach(ngModel.$ngfValidations, function (v) {
1750
+ v.valid = true;
1751
+ });
1752
+
1753
+ var attrGetter = function (name, params) {
1754
+ return upload.attrGetter(name, attr, scope, params);
1755
+ };
1756
+
1757
+ var ignoredErrors = (upload.attrGetter('ngfIgnoreInvalid', attr, scope) || '').split(' ');
1758
+ var runAllValidation = upload.attrGetter('ngfRunAllValidations', attr, scope);
1759
+
1760
+ if (files == null || files.length === 0) {
1761
+ return upload.emptyPromise({'validFiles': files, 'invalidFiles': []});
1762
+ }
1763
+
1764
+ files = files.length === undefined ? [files] : files.slice(0);
1765
+ var invalidFiles = [];
1766
+
1767
+ function validateSync(name, validationName, fn) {
1768
+ if (files) {
1769
+ var i = files.length, valid = null;
1770
+ while (i--) {
1771
+ var file = files[i];
1772
+ if (file) {
1773
+ var val = upload.getValidationAttr(attr, scope, name, validationName, file);
1774
+ if (val != null) {
1775
+ if (!fn(file, val, i)) {
1776
+ if (ignoredErrors.indexOf(name) === -1) {
1777
+ file.$error = name;
1778
+ (file.$errorMessages = (file.$errorMessages || {}))[name] = true;
1779
+ file.$errorParam = val;
1780
+ if (invalidFiles.indexOf(file) === -1) {
1781
+ invalidFiles.push(file);
1782
+ }
1783
+ if (!runAllValidation) {
1784
+ files.splice(i, 1);
1785
+ }
1786
+ valid = false;
1787
+ } else {
1788
+ files.splice(i, 1);
1789
+ }
1790
+ }
1791
+ }
1792
+ }
1793
+ }
1794
+ if (valid !== null) {
1795
+ ngModel.$ngfValidations.push({name: name, valid: valid});
1796
+ }
1797
+ }
1798
+ }
1799
+
1800
+ validateSync('pattern', null, upload.validatePattern);
1801
+ validateSync('minSize', 'size.min', function (file, val) {
1802
+ return file.size + 0.1 >= upload.translateScalars(val);
1803
+ });
1804
+ validateSync('maxSize', 'size.max', function (file, val) {
1805
+ return file.size - 0.1 <= upload.translateScalars(val);
1806
+ });
1807
+ var totalSize = 0;
1808
+ validateSync('maxTotalSize', null, function (file, val) {
1809
+ totalSize += file.size;
1810
+ if (totalSize > upload.translateScalars(val)) {
1811
+ files.splice(0, files.length);
1812
+ return false;
1813
+ }
1814
+ return true;
1815
+ });
1816
+
1817
+ validateSync('validateFn', null, function (file, r) {
1818
+ return r === true || r === null || r === '';
1819
+ });
1820
+
1821
+ if (!files.length) {
1822
+ return upload.emptyPromise({'validFiles': [], 'invalidFiles': invalidFiles});
1823
+ }
1824
+
1825
+ function validateAsync(name, validationName, type, asyncFn, fn) {
1826
+ function resolveResult(defer, file, val) {
1827
+ function resolveInternal(fn) {
1828
+ if (fn()) {
1829
+ if (ignoredErrors.indexOf(name) === -1) {
1830
+ file.$error = name;
1831
+ (file.$errorMessages = (file.$errorMessages || {}))[name] = true;
1832
+ file.$errorParam = val;
1833
+ if (invalidFiles.indexOf(file) === -1) {
1834
+ invalidFiles.push(file);
1835
+ }
1836
+ if (!runAllValidation) {
1837
+ var i = files.indexOf(file);
1838
+ if (i > -1) files.splice(i, 1);
1839
+ }
1840
+ defer.resolve(false);
1841
+ } else {
1842
+ var j = files.indexOf(file);
1843
+ if (j > -1) files.splice(j, 1);
1844
+ defer.resolve(true);
1845
+ }
1846
+ } else {
1847
+ defer.resolve(true);
1848
+ }
1849
+ }
1850
+
1851
+ if (val != null) {
1852
+ asyncFn(file, val).then(function (d) {
1853
+ resolveInternal(function () {
1854
+ return !fn(d, val);
1855
+ });
1856
+ }, function () {
1857
+ resolveInternal(function () {
1858
+ return attrGetter('ngfValidateForce', {$file: file});
1859
+ });
1860
+ });
1861
+ } else {
1862
+ defer.resolve(true);
1863
+ }
1864
+ }
1865
+
1866
+ var promises = [upload.emptyPromise(true)];
1867
+ if (files) {
1868
+ files = files.length === undefined ? [files] : files;
1869
+ angular.forEach(files, function (file) {
1870
+ var defer = $q.defer();
1871
+ promises.push(defer.promise);
1872
+ if (type && (file.type == null || file.type.search(type) !== 0)) {
1873
+ defer.resolve(true);
1874
+ return;
1875
+ }
1876
+ if (name === 'dimensions' && upload.attrGetter('ngfDimensions', attr) != null) {
1877
+ upload.imageDimensions(file).then(function (d) {
1878
+ resolveResult(defer, file,
1879
+ attrGetter('ngfDimensions', {$file: file, $width: d.width, $height: d.height}));
1880
+ }, function () {
1881
+ defer.resolve(false);
1882
+ });
1883
+ } else if (name === 'duration' && upload.attrGetter('ngfDuration', attr) != null) {
1884
+ upload.mediaDuration(file).then(function (d) {
1885
+ resolveResult(defer, file,
1886
+ attrGetter('ngfDuration', {$file: file, $duration: d}));
1887
+ }, function () {
1888
+ defer.resolve(false);
1889
+ });
1890
+ } else {
1891
+ resolveResult(defer, file,
1892
+ upload.getValidationAttr(attr, scope, name, validationName, file));
1893
+ }
1894
+ });
1895
+ }
1896
+ var deffer = $q.defer();
1897
+ $q.all(promises).then(function (values) {
1898
+ var isValid = true;
1899
+ for (var i = 0; i < values.length; i++) {
1900
+ if (!values[i]) {
1901
+ isValid = false;
1902
+ break;
1903
+ }
1904
+ }
1905
+ ngModel.$ngfValidations.push({name: name, valid: isValid});
1906
+ deffer.resolve(isValid);
1907
+ });
1908
+ return deffer.promise;
1909
+ }
1910
+
1911
+ var deffer = $q.defer();
1912
+ var promises = [];
1913
+
1914
+ promises.push(validateAsync('maxHeight', 'height.max', /image/,
1915
+ this.imageDimensions, function (d, val) {
1916
+ return d.height <= val;
1917
+ }));
1918
+ promises.push(validateAsync('minHeight', 'height.min', /image/,
1919
+ this.imageDimensions, function (d, val) {
1920
+ return d.height >= val;
1921
+ }));
1922
+ promises.push(validateAsync('maxWidth', 'width.max', /image/,
1923
+ this.imageDimensions, function (d, val) {
1924
+ return d.width <= val;
1925
+ }));
1926
+ promises.push(validateAsync('minWidth', 'width.min', /image/,
1927
+ this.imageDimensions, function (d, val) {
1928
+ return d.width >= val;
1929
+ }));
1930
+ promises.push(validateAsync('dimensions', null, /image/,
1931
+ function (file, val) {
1932
+ return upload.emptyPromise(val);
1933
+ }, function (r) {
1934
+ return r;
1935
+ }));
1936
+ promises.push(validateAsync('ratio', null, /image/,
1937
+ this.imageDimensions, function (d, val) {
1938
+ var split = val.toString().split(','), valid = false;
1939
+ for (var i = 0; i < split.length; i++) {
1940
+ if (Math.abs((d.width / d.height) - upload.ratioToFloat(split[i])) < 0.01) {
1941
+ valid = true;
1942
+ }
1943
+ }
1944
+ return valid;
1945
+ }));
1946
+ promises.push(validateAsync('maxRatio', 'ratio.max', /image/,
1947
+ this.imageDimensions, function (d, val) {
1948
+ return (d.width / d.height) - upload.ratioToFloat(val) < 0.0001;
1949
+ }));
1950
+ promises.push(validateAsync('minRatio', 'ratio.min', /image/,
1951
+ this.imageDimensions, function (d, val) {
1952
+ return (d.width / d.height) - upload.ratioToFloat(val) > -0.0001;
1953
+ }));
1954
+ promises.push(validateAsync('maxDuration', 'duration.max', /audio|video/,
1955
+ this.mediaDuration, function (d, val) {
1956
+ return d <= upload.translateScalars(val);
1957
+ }));
1958
+ promises.push(validateAsync('minDuration', 'duration.min', /audio|video/,
1959
+ this.mediaDuration, function (d, val) {
1960
+ return d >= upload.translateScalars(val);
1961
+ }));
1962
+ promises.push(validateAsync('duration', null, /audio|video/,
1963
+ function (file, val) {
1964
+ return upload.emptyPromise(val);
1965
+ }, function (r) {
1966
+ return r;
1967
+ }));
1968
+
1969
+ promises.push(validateAsync('validateAsyncFn', null, null,
1970
+ function (file, val) {
1971
+ return val;
1972
+ }, function (r) {
1973
+ return r === true || r === null || r === '';
1974
+ }));
1975
+
1976
+ $q.all(promises).then(function () {
1977
+
1978
+ if (runAllValidation) {
1979
+ for (var i = 0; i < files.length; i++) {
1980
+ var file = files[i];
1981
+ if (file.$error) {
1982
+ files.splice(i--, 1);
1983
+ }
1984
+ }
1985
+ }
1986
+
1987
+ runAllValidation = false;
1988
+ validateSync('maxFiles', null, function (file, val, i) {
1989
+ return prevLength + i < val;
1990
+ });
1991
+
1992
+ deffer.resolve({'validFiles': files, 'invalidFiles': invalidFiles});
1993
+ });
1994
+ return deffer.promise;
1995
+ };
1996
+
1997
+ upload.imageDimensions = function (file) {
1998
+ if (file.$ngfWidth && file.$ngfHeight) {
1999
+ var d = $q.defer();
2000
+ $timeout(function () {
2001
+ d.resolve({width: file.$ngfWidth, height: file.$ngfHeight});
2002
+ });
2003
+ return d.promise;
2004
+ }
2005
+ if (file.$ngfDimensionPromise) return file.$ngfDimensionPromise;
2006
+
2007
+ var deferred = $q.defer();
2008
+ $timeout(function () {
2009
+ if (file.type.indexOf('image') !== 0) {
2010
+ deferred.reject('not image');
2011
+ return;
2012
+ }
2013
+ upload.dataUrl(file).then(function (dataUrl) {
2014
+ var img = angular.element('<img>').attr('src', dataUrl)
2015
+ .css('visibility', 'hidden').css('position', 'fixed')
2016
+ .css('max-width', 'none !important').css('max-height', 'none !important');
2017
+
2018
+ function success() {
2019
+ var width = img[0].naturalWidth || img[0].clientWidth;
2020
+ var height = img[0].naturalHeight || img[0].clientHeight;
2021
+ img.remove();
2022
+ file.$ngfWidth = width;
2023
+ file.$ngfHeight = height;
2024
+ deferred.resolve({width: width, height: height});
2025
+ }
2026
+
2027
+ function error() {
2028
+ img.remove();
2029
+ deferred.reject('load error');
2030
+ }
2031
+
2032
+ img.on('load', success);
2033
+ img.on('error', error);
2034
+
2035
+ var secondsCounter = 0;
2036
+ function checkLoadErrorInCaseOfNoCallback() {
2037
+ $timeout(function () {
2038
+ if (img[0].parentNode) {
2039
+ if (img[0].clientWidth) {
2040
+ success();
2041
+ } else if (secondsCounter++ > 10) {
2042
+ error();
2043
+ } else {
2044
+ checkLoadErrorInCaseOfNoCallback();
2045
+ }
2046
+ }
2047
+ }, 1000);
2048
+ }
2049
+
2050
+ checkLoadErrorInCaseOfNoCallback();
2051
+
2052
+ angular.element(document.getElementsByTagName('body')[0]).append(img);
2053
+ }, function () {
2054
+ deferred.reject('load error');
2055
+ });
2056
+ });
2057
+
2058
+ file.$ngfDimensionPromise = deferred.promise;
2059
+ file.$ngfDimensionPromise['finally'](function () {
2060
+ delete file.$ngfDimensionPromise;
2061
+ });
2062
+ return file.$ngfDimensionPromise;
2063
+ };
2064
+
2065
+ upload.mediaDuration = function (file) {
2066
+ if (file.$ngfDuration) {
2067
+ var d = $q.defer();
2068
+ $timeout(function () {
2069
+ d.resolve(file.$ngfDuration);
2070
+ });
2071
+ return d.promise;
2072
+ }
2073
+ if (file.$ngfDurationPromise) return file.$ngfDurationPromise;
2074
+
2075
+ var deferred = $q.defer();
2076
+ $timeout(function () {
2077
+ if (file.type.indexOf('audio') !== 0 && file.type.indexOf('video') !== 0) {
2078
+ deferred.reject('not media');
2079
+ return;
2080
+ }
2081
+ upload.dataUrl(file).then(function (dataUrl) {
2082
+ var el = angular.element(file.type.indexOf('audio') === 0 ? '<audio>' : '<video>')
2083
+ .attr('src', dataUrl).css('visibility', 'none').css('position', 'fixed');
2084
+
2085
+ function success() {
2086
+ var duration = el[0].duration;
2087
+ file.$ngfDuration = duration;
2088
+ el.remove();
2089
+ deferred.resolve(duration);
2090
+ }
2091
+
2092
+ function error() {
2093
+ el.remove();
2094
+ deferred.reject('load error');
2095
+ }
2096
+
2097
+ el.on('loadedmetadata', success);
2098
+ el.on('error', error);
2099
+ var count = 0;
2100
+
2101
+ function checkLoadError() {
2102
+ $timeout(function () {
2103
+ if (el[0].parentNode) {
2104
+ if (el[0].duration) {
2105
+ success();
2106
+ } else if (count > 10) {
2107
+ error();
2108
+ } else {
2109
+ checkLoadError();
2110
+ }
2111
+ }
2112
+ }, 1000);
2113
+ }
2114
+
2115
+ checkLoadError();
2116
+
2117
+ angular.element(document.body).append(el);
2118
+ }, function () {
2119
+ deferred.reject('load error');
2120
+ });
2121
+ });
2122
+
2123
+ file.$ngfDurationPromise = deferred.promise;
2124
+ file.$ngfDurationPromise['finally'](function () {
2125
+ delete file.$ngfDurationPromise;
2126
+ });
2127
+ return file.$ngfDurationPromise;
2128
+ };
2129
+ return upload;
2130
+ }
2131
+ ]);
2132
+
2133
+ ngFileUpload.service('UploadResize', ['UploadValidate', '$q', function (UploadValidate, $q) {
2134
+ var upload = UploadValidate;
2135
+
2136
+ /**
2137
+ * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
2138
+ * images to fit into a certain area.
2139
+ * Source: http://stackoverflow.com/a/14731922
2140
+ *
2141
+ * @param {Number} srcWidth Source area width
2142
+ * @param {Number} srcHeight Source area height
2143
+ * @param {Number} maxWidth Nestable area maximum available width
2144
+ * @param {Number} maxHeight Nestable area maximum available height
2145
+ * @return {Object} { width, height }
2146
+ */
2147
+ var calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) {
2148
+ var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) :
2149
+ Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
2150
+ return {
2151
+ width: srcWidth * ratio, height: srcHeight * ratio,
2152
+ marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight
2153
+ };
2154
+ };
2155
+
2156
+ // Extracted from https://github.com/romelgomez/angular-firebase-image-upload/blob/master/app/scripts/fileUpload.js#L89
2157
+ var resize = function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
2158
+ var deferred = $q.defer();
2159
+ var canvasElement = document.createElement('canvas');
2160
+ var imageElement = document.createElement('img');
2161
+ imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
2162
+ document.body.appendChild(imageElement);
2163
+
2164
+ imageElement.onload = function () {
2165
+ var imgWidth = imageElement.width, imgHeight = imageElement.height;
2166
+ imageElement.parentNode.removeChild(imageElement);
2167
+ if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
2168
+ deferred.reject('resizeIf');
2169
+ return;
2170
+ }
2171
+ try {
2172
+ if (ratio) {
2173
+ var ratioFloat = upload.ratioToFloat(ratio);
2174
+ var imgRatio = imgWidth / imgHeight;
2175
+ if (imgRatio < ratioFloat) {
2176
+ width = imgWidth;
2177
+ height = width / ratioFloat;
2178
+ } else {
2179
+ height = imgHeight;
2180
+ width = height * ratioFloat;
2181
+ }
2182
+ }
2183
+ if (!width) {
2184
+ width = imgWidth;
2185
+ }
2186
+ if (!height) {
2187
+ height = imgHeight;
2188
+ }
2189
+ var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
2190
+ canvasElement.width = Math.min(dimensions.width, width);
2191
+ canvasElement.height = Math.min(dimensions.height, height);
2192
+ var context = canvasElement.getContext('2d');
2193
+ context.drawImage(imageElement,
2194
+ Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
2195
+ dimensions.width, dimensions.height);
2196
+ deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
2197
+ } catch (e) {
2198
+ deferred.reject(e);
2199
+ }
2200
+ };
2201
+ imageElement.onerror = function () {
2202
+ imageElement.parentNode.removeChild(imageElement);
2203
+ deferred.reject();
2204
+ };
2205
+ imageElement.src = imagen;
2206
+ return deferred.promise;
2207
+ };
2208
+
2209
+ upload.dataUrltoBlob = function (dataurl, name, origSize) {
2210
+ var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
2211
+ bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
2212
+ while (n--) {
2213
+ u8arr[n] = bstr.charCodeAt(n);
2214
+ }
2215
+ var blob = new window.Blob([u8arr], {type: mime});
2216
+ blob.name = name;
2217
+ blob.$ngfOrigSize = origSize;
2218
+ return blob;
2219
+ };
2220
+
2221
+ upload.isResizeSupported = function () {
2222
+ var elem = document.createElement('canvas');
2223
+ return window.atob && elem.getContext && elem.getContext('2d') && window.Blob;
2224
+ };
2225
+
2226
+ if (upload.isResizeSupported()) {
2227
+ // add name getter to the blob constructor prototype
2228
+ Object.defineProperty(window.Blob.prototype, 'name', {
2229
+ get: function () {
2230
+ return this.$ngfName;
2231
+ },
2232
+ set: function (v) {
2233
+ this.$ngfName = v;
2234
+ },
2235
+ configurable: true
2236
+ });
2237
+ }
2238
+
2239
+ upload.resize = function (file, options) {
2240
+ if (file.type.indexOf('image') !== 0) return upload.emptyPromise(file);
2241
+
2242
+ var deferred = $q.defer();
2243
+ upload.dataUrl(file, true).then(function (url) {
2244
+ resize(url, options.width, options.height, options.quality, options.type || file.type,
2245
+ options.ratio, options.centerCrop, options.resizeIf)
2246
+ .then(function (dataUrl) {
2247
+ if (file.type === 'image/jpeg' && options.restoreExif !== false) {
2248
+ try {
2249
+ dataUrl = upload.restoreExif(url, dataUrl);
2250
+ } catch (e) {
2251
+ setTimeout(function () {throw e;}, 1);
2252
+ }
2253
+ }
2254
+ try {
2255
+ var blob = upload.dataUrltoBlob(dataUrl, file.name, file.size);
2256
+ deferred.resolve(blob);
2257
+ } catch (e) {
2258
+ deferred.reject(e);
2259
+ }
2260
+ }, function (r) {
2261
+ if (r === 'resizeIf') {
2262
+ deferred.resolve(file);
2263
+ }
2264
+ deferred.reject(r);
2265
+ });
2266
+ }, function (e) {
2267
+ deferred.reject(e);
2268
+ });
2269
+ return deferred.promise;
2270
+ };
2271
+
2272
+ return upload;
2273
+ }]);
2274
+
2275
+ (function () {
2276
+ ngFileUpload.directive('ngfDrop', ['$parse', '$timeout', '$window', 'Upload', '$http', '$q',
2277
+ function ($parse, $timeout, $window, Upload, $http, $q) {
2278
+ return {
2279
+ restrict: 'AEC',
2280
+ require: '?ngModel',
2281
+ link: function (scope, elem, attr, ngModel) {
2282
+ linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, Upload, $http, $q);
2283
+ }
2284
+ };
2285
+ }]);
2286
+
2287
+ ngFileUpload.directive('ngfNoFileDrop', function () {
2288
+ return function (scope, elem) {
2289
+ if (dropAvailable()) elem.css('display', 'none');
2290
+ };
2291
+ });
2292
+
2293
+ ngFileUpload.directive('ngfDropAvailable', ['$parse', '$timeout', 'Upload', function ($parse, $timeout, Upload) {
2294
+ return function (scope, elem, attr) {
2295
+ if (dropAvailable()) {
2296
+ var model = $parse(Upload.attrGetter('ngfDropAvailable', attr));
2297
+ $timeout(function () {
2298
+ model(scope);
2299
+ if (model.assign) {
2300
+ model.assign(scope, true);
2301
+ }
2302
+ });
2303
+ }
2304
+ };
2305
+ }]);
2306
+
2307
+ function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, upload, $http, $q) {
2308
+ var available = dropAvailable();
2309
+
2310
+ var attrGetter = function (name, scope, params) {
2311
+ return upload.attrGetter(name, attr, scope, params);
2312
+ };
2313
+
2314
+ if (attrGetter('dropAvailable')) {
2315
+ $timeout(function () {
2316
+ if (scope[attrGetter('dropAvailable')]) {
2317
+ scope[attrGetter('dropAvailable')].value = available;
2318
+ } else {
2319
+ scope[attrGetter('dropAvailable')] = available;
2320
+ }
2321
+ });
2322
+ }
2323
+ if (!available) {
2324
+ if (attrGetter('ngfHideOnDropNotAvailable', scope) === true) {
2325
+ elem.css('display', 'none');
2326
+ }
2327
+ return;
2328
+ }
2329
+
2330
+ function isDisabled() {
2331
+ return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
2332
+ }
2333
+
2334
+ if (attrGetter('ngfSelect') == null) {
2335
+ upload.registerModelChangeValidator(ngModel, attr, scope);
2336
+ }
2337
+
2338
+ var leaveTimeout = null;
2339
+ var stopPropagation = $parse(attrGetter('ngfStopPropagation'));
2340
+ var dragOverDelay = 1;
2341
+ var actualDragOverClass;
2342
+
2343
+ elem[0].addEventListener('dragover', function (evt) {
2344
+ if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
2345
+ evt.preventDefault();
2346
+ if (stopPropagation(scope)) evt.stopPropagation();
2347
+ // handling dragover events from the Chrome download bar
2348
+ if (navigator.userAgent.indexOf('Chrome') > -1) {
2349
+ var b = evt.dataTransfer.effectAllowed;
2350
+ evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
2351
+ }
2352
+ $timeout.cancel(leaveTimeout);
2353
+ if (!actualDragOverClass) {
2354
+ actualDragOverClass = 'C';
2355
+ calculateDragOverClass(scope, attr, evt, function (clazz) {
2356
+ actualDragOverClass = clazz;
2357
+ elem.addClass(actualDragOverClass);
2358
+ attrGetter('ngfDrag', scope, {$isDragging: true, $class: actualDragOverClass, $event: evt});
2359
+ });
2360
+ }
2361
+ }, false);
2362
+ elem[0].addEventListener('dragenter', function (evt) {
2363
+ if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
2364
+ evt.preventDefault();
2365
+ if (stopPropagation(scope)) evt.stopPropagation();
2366
+ }, false);
2367
+ elem[0].addEventListener('dragleave', function (evt) {
2368
+ if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
2369
+ evt.preventDefault();
2370
+ if (stopPropagation(scope)) evt.stopPropagation();
2371
+ leaveTimeout = $timeout(function () {
2372
+ if (actualDragOverClass) elem.removeClass(actualDragOverClass);
2373
+ actualDragOverClass = null;
2374
+ attrGetter('ngfDrag', scope, {$isDragging: false, $event: evt});
2375
+ }, dragOverDelay || 100);
2376
+ }, false);
2377
+ elem[0].addEventListener('drop', function (evt) {
2378
+ if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
2379
+ evt.preventDefault();
2380
+ if (stopPropagation(scope)) evt.stopPropagation();
2381
+ if (actualDragOverClass) elem.removeClass(actualDragOverClass);
2382
+ actualDragOverClass = null;
2383
+ extractFilesAndUpdateModel(evt.dataTransfer, evt, 'dropUrl');
2384
+ }, false);
2385
+ elem[0].addEventListener('paste', function (evt) {
2386
+ if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
2387
+ attrGetter('ngfEnableFirefoxPaste', scope)) {
2388
+ evt.preventDefault();
2389
+ }
2390
+ if (isDisabled() || !upload.shouldUpdateOn('paste', attr, scope)) return;
2391
+ extractFilesAndUpdateModel(evt.clipboardData || evt.originalEvent.clipboardData, evt, 'pasteUrl');
2392
+ }, false);
2393
+
2394
+ if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
2395
+ attrGetter('ngfEnableFirefoxPaste', scope)) {
2396
+ elem.attr('contenteditable', true);
2397
+ elem.on('keypress', function (e) {
2398
+ if (!e.metaKey && !e.ctrlKey) {
2399
+ e.preventDefault();
2400
+ }
2401
+ });
2402
+ }
2403
+
2404
+ function extractFilesAndUpdateModel(source, evt, updateOnType) {
2405
+ if (!source) return;
2406
+ // html needs to be calculated on the same process otherwise the data will be wiped
2407
+ // after promise resolve or setTimeout.
2408
+ var html;
2409
+ try {
2410
+ html = source && source.getData && source.getData('text/html');
2411
+ } catch (e) {/* Fix IE11 that throw error calling getData */
2412
+ }
2413
+ extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
2414
+ attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
2415
+ if (files.length) {
2416
+ updateModel(files, evt);
2417
+ } else {
2418
+ extractFilesFromHtml(updateOnType, html).then(function (files) {
2419
+ updateModel(files, evt);
2420
+ });
2421
+ }
2422
+ });
2423
+ }
2424
+
2425
+ function updateModel(files, evt) {
2426
+ upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
2427
+ }
2428
+
2429
+ function extractFilesFromHtml(updateOn, html) {
2430
+ if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
2431
+ var urls = [];
2432
+ html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
2433
+ urls.push(src);
2434
+ });
2435
+ var promises = [], files = [];
2436
+ if (urls.length) {
2437
+ angular.forEach(urls, function (url) {
2438
+ promises.push(upload.urlToBlob(url).then(function (blob) {
2439
+ files.push(blob);
2440
+ }));
2441
+ });
2442
+ var defer = $q.defer();
2443
+ $q.all(promises).then(function () {
2444
+ defer.resolve(files);
2445
+ }, function (e) {
2446
+ defer.reject(e);
2447
+ });
2448
+ return defer.promise;
2449
+ }
2450
+ return upload.emptyPromise();
2451
+ }
2452
+
2453
+ function calculateDragOverClass(scope, attr, evt, callback) {
2454
+ var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
2455
+ if (angular.isString(obj)) {
2456
+ dClass = obj;
2457
+ } else if (obj) {
2458
+ if (obj.delay) dragOverDelay = obj.delay;
2459
+ if (obj.accept || obj.reject) {
2460
+ var items = evt.dataTransfer.items;
2461
+ if (items == null || !items.length) {
2462
+ dClass = obj.accept;
2463
+ } else {
2464
+ var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
2465
+ var len = items.length;
2466
+ while (len--) {
2467
+ if (!upload.validatePattern(items[len], pattern)) {
2468
+ dClass = obj.reject;
2469
+ break;
2470
+ } else {
2471
+ dClass = obj.accept;
2472
+ }
2473
+ }
2474
+ }
2475
+ }
2476
+ }
2477
+ callback(dClass);
2478
+ }
2479
+
2480
+ function extractFiles(items, fileList, allowDir, multiple) {
2481
+ var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
2482
+ if (maxFiles == null) {
2483
+ maxFiles = Number.MAX_VALUE;
2484
+ }
2485
+ var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
2486
+ if (maxTotalSize == null) {
2487
+ maxTotalSize = Number.MAX_VALUE;
2488
+ }
2489
+ var includeDir = attrGetter('ngfIncludeDir', scope);
2490
+ var files = [], totalSize = 0;
2491
+
2492
+ function traverseFileTree(entry, path) {
2493
+ var defer = $q.defer();
2494
+ if (entry != null) {
2495
+ if (entry.isDirectory) {
2496
+ var promises = [upload.emptyPromise()];
2497
+ if (includeDir) {
2498
+ var file = {type: 'directory'};
2499
+ file.name = file.path = (path || '') + entry.name;
2500
+ files.push(file);
2501
+ }
2502
+ var dirReader = entry.createReader();
2503
+ var entries = [];
2504
+ var readEntries = function () {
2505
+ dirReader.readEntries(function (results) {
2506
+ try {
2507
+ if (!results.length) {
2508
+ angular.forEach(entries.slice(0), function (e) {
2509
+ if (files.length <= maxFiles && totalSize <= maxTotalSize) {
2510
+ promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
2511
+ }
2512
+ });
2513
+ $q.all(promises).then(function () {
2514
+ defer.resolve();
2515
+ }, function (e) {
2516
+ defer.reject(e);
2517
+ });
2518
+ } else {
2519
+ entries = entries.concat(Array.prototype.slice.call(results || [], 0));
2520
+ readEntries();
2521
+ }
2522
+ } catch (e) {
2523
+ defer.reject(e);
2524
+ }
2525
+ }, function (e) {
2526
+ defer.reject(e);
2527
+ });
2528
+ };
2529
+ readEntries();
2530
+ } else {
2531
+ entry.file(function (file) {
2532
+ try {
2533
+ file.path = (path ? path : '') + file.name;
2534
+ if (includeDir) {
2535
+ file = upload.rename(file, file.path);
2536
+ }
2537
+ files.push(file);
2538
+ totalSize += file.size;
2539
+ defer.resolve();
2540
+ } catch (e) {
2541
+ defer.reject(e);
2542
+ }
2543
+ }, function (e) {
2544
+ defer.reject(e);
2545
+ });
2546
+ }
2547
+ }
2548
+ return defer.promise;
2549
+ }
2550
+
2551
+ var promises = [upload.emptyPromise()];
2552
+
2553
+ if (items && items.length > 0 && $window.location.protocol !== 'file:') {
2554
+ for (var i = 0; i < items.length; i++) {
2555
+ if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
2556
+ var entry = items[i].webkitGetAsEntry();
2557
+ if (entry.isDirectory && !allowDir) {
2558
+ continue;
2559
+ }
2560
+ if (entry != null) {
2561
+ promises.push(traverseFileTree(entry));
2562
+ }
2563
+ } else {
2564
+ var f = items[i].getAsFile();
2565
+ if (f != null) {
2566
+ files.push(f);
2567
+ totalSize += f.size;
2568
+ }
2569
+ }
2570
+ if (files.length > maxFiles || totalSize > maxTotalSize ||
2571
+ (!multiple && files.length > 0)) break;
2572
+ }
2573
+ } else {
2574
+ if (fileList != null) {
2575
+ for (var j = 0; j < fileList.length; j++) {
2576
+ var file = fileList.item(j);
2577
+ if (file.type || file.size > 0) {
2578
+ files.push(file);
2579
+ totalSize += file.size;
2580
+ }
2581
+ if (files.length > maxFiles || totalSize > maxTotalSize ||
2582
+ (!multiple && files.length > 0)) break;
2583
+ }
2584
+ }
2585
+ }
2586
+
2587
+ var defer = $q.defer();
2588
+ $q.all(promises).then(function () {
2589
+ if (!multiple && !includeDir && files.length) {
2590
+ var i = 0;
2591
+ while (files[i] && files[i].type === 'directory') i++;
2592
+ defer.resolve([files[i]]);
2593
+ } else {
2594
+ defer.resolve(files);
2595
+ }
2596
+ }, function (e) {
2597
+ defer.reject(e);
2598
+ });
2599
+
2600
+ return defer.promise;
2601
+ }
2602
+ }
2603
+
2604
+ function dropAvailable() {
2605
+ var div = document.createElement('div');
2606
+ return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent);
2607
+ }
2608
+
2609
+ })();
2610
+
2611
+ // customized version of https://github.com/exif-js/exif-js
2612
+ ngFileUpload.service('UploadExif', ['UploadResize', '$q', function (UploadResize, $q) {
2613
+ var upload = UploadResize;
2614
+
2615
+ upload.isExifSupported = function () {
2616
+ return window.FileReader && new FileReader().readAsArrayBuffer && upload.isResizeSupported();
2617
+ };
2618
+
2619
+ function applyTransform(ctx, orientation, width, height) {
2620
+ switch (orientation) {
2621
+ case 2:
2622
+ return ctx.transform(-1, 0, 0, 1, width, 0);
2623
+ case 3:
2624
+ return ctx.transform(-1, 0, 0, -1, width, height);
2625
+ case 4:
2626
+ return ctx.transform(1, 0, 0, -1, 0, height);
2627
+ case 5:
2628
+ return ctx.transform(0, 1, 1, 0, 0, 0);
2629
+ case 6:
2630
+ return ctx.transform(0, 1, -1, 0, height, 0);
2631
+ case 7:
2632
+ return ctx.transform(0, -1, -1, 0, height, width);
2633
+ case 8:
2634
+ return ctx.transform(0, -1, 1, 0, 0, width);
2635
+ }
2636
+ }
2637
+
2638
+ upload.readOrientation = function (file) {
2639
+ var defer = $q.defer();
2640
+ var reader = new FileReader();
2641
+ var slicedFile = file.slice ? file.slice(0, 64 * 1024) : file;
2642
+ reader.readAsArrayBuffer(slicedFile);
2643
+ reader.onerror = function (e) {
2644
+ return defer.reject(e);
2645
+ };
2646
+ reader.onload = function (e) {
2647
+ var result = {orientation: 1};
2648
+ var view = new DataView(this.result);
2649
+ if (view.getUint16(0, false) !== 0xFFD8) return defer.resolve(result);
2650
+
2651
+ var length = view.byteLength,
2652
+ offset = 2;
2653
+ while (offset < length) {
2654
+ var marker = view.getUint16(offset, false);
2655
+ offset += 2;
2656
+ if (marker === 0xFFE1) {
2657
+ if (view.getUint32(offset += 2, false) !== 0x45786966) return defer.resolve(result);
2658
+
2659
+ var little = view.getUint16(offset += 6, false) === 0x4949;
2660
+ offset += view.getUint32(offset + 4, little);
2661
+ var tags = view.getUint16(offset, little);
2662
+ offset += 2;
2663
+ for (var i = 0; i < tags; i++)
2664
+ if (view.getUint16(offset + (i * 12), little) === 0x0112) {
2665
+ var orientation = view.getUint16(offset + (i * 12) + 8, little);
2666
+ if (orientation >= 2 && orientation <= 8) {
2667
+ view.setUint16(offset + (i * 12) + 8, 1, little);
2668
+ result.fixedArrayBuffer = e.target.result;
2669
+ }
2670
+ result.orientation = orientation;
2671
+ return defer.resolve(result);
2672
+ }
2673
+ } else if ((marker & 0xFF00) !== 0xFF00) break;
2674
+ else offset += view.getUint16(offset, false);
2675
+ }
2676
+ return defer.resolve(result);
2677
+ };
2678
+ return defer.promise;
2679
+ };
2680
+
2681
+ function arrayBufferToBase64(buffer) {
2682
+ var binary = '';
2683
+ var bytes = new Uint8Array(buffer);
2684
+ var len = bytes.byteLength;
2685
+ for (var i = 0; i < len; i++) {
2686
+ binary += String.fromCharCode(bytes[i]);
2687
+ }
2688
+ return window.btoa(binary);
2689
+ }
2690
+
2691
+ upload.applyExifRotation = function (file) {
2692
+ if (file.type.indexOf('image/jpeg') !== 0) {
2693
+ return upload.emptyPromise(file);
2694
+ }
2695
+
2696
+ var deferred = $q.defer();
2697
+ upload.readOrientation(file).then(function (result) {
2698
+ if (result.orientation < 2 || result.orientation > 8) {
2699
+ return deferred.resolve(file);
2700
+ }
2701
+ upload.dataUrl(file, true).then(function (url) {
2702
+ var canvas = document.createElement('canvas');
2703
+ var img = document.createElement('img');
2704
+
2705
+ img.onload = function () {
2706
+ try {
2707
+ canvas.width = result.orientation > 4 ? img.height : img.width;
2708
+ canvas.height = result.orientation > 4 ? img.width : img.height;
2709
+ var ctx = canvas.getContext('2d');
2710
+ applyTransform(ctx, result.orientation, img.width, img.height);
2711
+ ctx.drawImage(img, 0, 0);
2712
+ var dataUrl = canvas.toDataURL(file.type || 'image/WebP', 0.934);
2713
+ dataUrl = upload.restoreExif(arrayBufferToBase64(result.fixedArrayBuffer), dataUrl);
2714
+ var blob = upload.dataUrltoBlob(dataUrl, file.name);
2715
+ deferred.resolve(blob);
2716
+ } catch (e) {
2717
+ return deferred.reject(e);
2718
+ }
2719
+ };
2720
+ img.onerror = function () {
2721
+ deferred.reject();
2722
+ };
2723
+ img.src = url;
2724
+ }, function (e) {
2725
+ deferred.reject(e);
2726
+ });
2727
+ }, function (e) {
2728
+ deferred.reject(e);
2729
+ });
2730
+ return deferred.promise;
2731
+ };
2732
+
2733
+ upload.restoreExif = function (orig, resized) {
2734
+ var ExifRestorer = {};
2735
+
2736
+ ExifRestorer.KEY_STR = 'ABCDEFGHIJKLMNOP' +
2737
+ 'QRSTUVWXYZabcdef' +
2738
+ 'ghijklmnopqrstuv' +
2739
+ 'wxyz0123456789+/' +
2740
+ '=';
2741
+
2742
+ ExifRestorer.encode64 = function (input) {
2743
+ var output = '',
2744
+ chr1, chr2, chr3 = '',
2745
+ enc1, enc2, enc3, enc4 = '',
2746
+ i = 0;
2747
+
2748
+ do {
2749
+ chr1 = input[i++];
2750
+ chr2 = input[i++];
2751
+ chr3 = input[i++];
2752
+
2753
+ enc1 = chr1 >> 2;
2754
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
2755
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
2756
+ enc4 = chr3 & 63;
2757
+
2758
+ if (isNaN(chr2)) {
2759
+ enc3 = enc4 = 64;
2760
+ } else if (isNaN(chr3)) {
2761
+ enc4 = 64;
2762
+ }
2763
+
2764
+ output = output +
2765
+ this.KEY_STR.charAt(enc1) +
2766
+ this.KEY_STR.charAt(enc2) +
2767
+ this.KEY_STR.charAt(enc3) +
2768
+ this.KEY_STR.charAt(enc4);
2769
+ chr1 = chr2 = chr3 = '';
2770
+ enc1 = enc2 = enc3 = enc4 = '';
2771
+ } while (i < input.length);
2772
+
2773
+ return output;
2774
+ };
2775
+
2776
+ ExifRestorer.restore = function (origFileBase64, resizedFileBase64) {
2777
+ if (origFileBase64.match('data:image/jpeg;base64,')) {
2778
+ origFileBase64 = origFileBase64.replace('data:image/jpeg;base64,', '');
2779
+ }
2780
+
2781
+ var rawImage = this.decode64(origFileBase64);
2782
+ var segments = this.slice2Segments(rawImage);
2783
+
2784
+ var image = this.exifManipulation(resizedFileBase64, segments);
2785
+
2786
+ return 'data:image/jpeg;base64,' + this.encode64(image);
2787
+ };
2788
+
2789
+
2790
+ ExifRestorer.exifManipulation = function (resizedFileBase64, segments) {
2791
+ var exifArray = this.getExifArray(segments),
2792
+ newImageArray = this.insertExif(resizedFileBase64, exifArray);
2793
+ return new Uint8Array(newImageArray);
2794
+ };
2795
+
2796
+
2797
+ ExifRestorer.getExifArray = function (segments) {
2798
+ var seg;
2799
+ for (var x = 0; x < segments.length; x++) {
2800
+ seg = segments[x];
2801
+ if (seg[0] === 255 & seg[1] === 225) //(ff e1)
2802
+ {
2803
+ return seg;
2804
+ }
2805
+ }
2806
+ return [];
2807
+ };
2808
+
2809
+
2810
+ ExifRestorer.insertExif = function (resizedFileBase64, exifArray) {
2811
+ var imageData = resizedFileBase64.replace('data:image/jpeg;base64,', ''),
2812
+ buf = this.decode64(imageData),
2813
+ separatePoint = buf.indexOf(255, 3),
2814
+ mae = buf.slice(0, separatePoint),
2815
+ ato = buf.slice(separatePoint),
2816
+ array = mae;
2817
+
2818
+ array = array.concat(exifArray);
2819
+ array = array.concat(ato);
2820
+ return array;
2821
+ };
2822
+
2823
+
2824
+ ExifRestorer.slice2Segments = function (rawImageArray) {
2825
+ var head = 0,
2826
+ segments = [];
2827
+
2828
+ while (1) {
2829
+ if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 218) {
2830
+ break;
2831
+ }
2832
+ if (rawImageArray[head] === 255 & rawImageArray[head + 1] === 216) {
2833
+ head += 2;
2834
+ }
2835
+ else {
2836
+ var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3],
2837
+ endPoint = head + length + 2,
2838
+ seg = rawImageArray.slice(head, endPoint);
2839
+ segments.push(seg);
2840
+ head = endPoint;
2841
+ }
2842
+ if (head > rawImageArray.length) {
2843
+ break;
2844
+ }
2845
+ }
2846
+
2847
+ return segments;
2848
+ };
2849
+
2850
+
2851
+ ExifRestorer.decode64 = function (input) {
2852
+ var chr1, chr2, chr3 = '',
2853
+ enc1, enc2, enc3, enc4 = '',
2854
+ i = 0,
2855
+ buf = [];
2856
+
2857
+ // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
2858
+ var base64test = /[^A-Za-z0-9\+\/\=]/g;
2859
+ if (base64test.exec(input)) {
2860
+ console.log('There were invalid base64 characters in the input text.\n' +
2861
+ 'Valid base64 characters are A-Z, a-z, 0-9, ' + ', ' / ',and "="\n' +
2862
+ 'Expect errors in decoding.');
2863
+ }
2864
+ input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
2865
+
2866
+ do {
2867
+ enc1 = this.KEY_STR.indexOf(input.charAt(i++));
2868
+ enc2 = this.KEY_STR.indexOf(input.charAt(i++));
2869
+ enc3 = this.KEY_STR.indexOf(input.charAt(i++));
2870
+ enc4 = this.KEY_STR.indexOf(input.charAt(i++));
2871
+
2872
+ chr1 = (enc1 << 2) | (enc2 >> 4);
2873
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
2874
+ chr3 = ((enc3 & 3) << 6) | enc4;
2875
+
2876
+ buf.push(chr1);
2877
+
2878
+ if (enc3 !== 64) {
2879
+ buf.push(chr2);
2880
+ }
2881
+ if (enc4 !== 64) {
2882
+ buf.push(chr3);
2883
+ }
2884
+
2885
+ chr1 = chr2 = chr3 = '';
2886
+ enc1 = enc2 = enc3 = enc4 = '';
2887
+
2888
+ } while (i < input.length);
2889
+
2890
+ return buf;
2891
+ };
2892
+
2893
+ return ExifRestorer.restore(orig, resized); //<= EXIF
2894
+ };
2895
+
2896
+ return upload;
2897
+ }]);
2898
+