<commit_before>!function(e,n){"use strict";function t(){}function r(e,n){if(e){"object"==typeof e&&(e=[].slice.call(e));for(var t=0,r=e.length;r>t;t++)n.call(e,e[t],t)}}function o(e,t){var r=Object.prototype.toString.call(t).slice(8,-1);return t!==n&&null!==t&&r===e}function a(e){return o("Function",e)}function c(e){return o("Array",e)}function i(e){var n=e.split("/"),t=n[n.length-1],r=t.indexOf("?");return-1!==r?t.substring(0,r):t}function u(e){e=e||t,e._done||(e(),e._done=1)}function l(e,n,r,o){var a="object"==typeof e?e:{test:e,success:n?c(n)?n:[n]:!1,failure:r?c(r)?r:[r]:!1,callback:o||t},i=!!a.test;return i&&a.success?(a.success.push(a.callback),A.load.apply(null,a.success)):!i&&a.failure?(a.failure.push(a.callback),A.load.apply(null,a.failure)):o(),A}function d(e){var n={};if("object"==typeof e)for(var t in e)e[t]&&(n={name:t,url:e[t]});else n={name:i(e),url:e};var r=C[n.name];return r&&r.url===n.url?r:(C[n.name]=n,n)}function s(e){e=e||C;for(var n in e)if(e.hasOwnProperty(n)&&e[n].state!==U)return!1;return!0}function f(e){e.state=k,r(e.onpreload,function(e){e.call()})}function m(e){e.state===n&&(e.state=S,e.onpreload=[],g({url:e.url,type:"cache"},function(){f(e)}))}function p(){var e=arguments,n=e[e.length-1],t=[].slice.call(e,1),o=t[0];return a(n)||(n=null),c(e[0])?(e[0].push(n),A.load.apply(null,e[0]),A):(o?(r(t,function(e){!a(e)&&e&&m(d(e))}),v(d(e[0]),a(o)?o:function(){A.load.apply(null,t)})):v(d(e[0])),A)}function y(){var e=arguments,n=e[e.length-1],t={};return a(n)||(n=null),c(e[0])?(e[0].push(n),A.load.apply(null,e[0]),A):(r(e,function(e){e!==n&&(e=d(e),t[e.name]=e)}),r(e,function(e){e!==n&&(e=d(e),v(e,function(){s(t)&&u(n)}))}),A)}function v(e,n){return n=n||t,e.state===U?void n():e.state===I?void A.ready(e.name,n):e.state===S?void e.onpreload.push(function(){v(e,n)}):(e.state=I,void g(e,function(){e.state=U,n(),r(w[e.name],function(e){u(e)}),L&&s()&&r(w.ALL,function(e){u(e)})}))}function h(e){e=e||"";var n=e.split("?")[0].split(".");return n[n.length-1].toLowerCase()}function g(n,r){function o(n){n=n||e.event,i.onload=i.onreadystatechange=i.onerror=null,r()}function a(t){t=t||e.event,("load"===t.type||/loaded|complete/.test(i.readyState)&&(!q.documentMode||q.documentMode<9))&&(e.clearTimeout(n.errorTimeout),e.clearTimeout(n.cssTimeout),i.onload=i.onreadystatechange=i.onerror=null,r())}function c(){if(n.state!==U&&n.cssRetries<=20){for(var t=0,r=q.styleSheets.length;r>t;t++)if(q.styleSheets[t].href===i.href)return void a({type:"load"});n.cssRetries++,n.cssTimeout=e.setTimeout(c,250)}}r=r||t;var i,u=h(n.url);"css"===u?(i=q.createElement("link"),i.type="text/"+(n.type||"css"),i.rel="stylesheet",i.href=n.url,n.cssRetries=0,n.cssTimeout=e.setTimeout(c,500)):(i=q.createElement("script"),i.type="text/"+(n.type||"javascript"),i.src=n.url),i.onload=i.onreadystatechange=a,i.onerror=o,i.async=!1,i.defer=!1,n.errorTimeout=e.setTimeout(function(){o({type:"timeout"})},7e3);var l=q.head||q.getElementsByTagName("head")[0];l.insertBefore(i,l.lastChild)}function j(){for(var e=q.getElementsByTagName("script"),n=0,t=e.length;t>n;n++){var r=e[n].getAttribute("data-headjs-load");if(r)return void A.load(r)}}function T(e,n){if(e===q)return L?u(n):x.push(n),A;if(a(e)&&(n=e,e="ALL"),c(e)){var t={};return r(e,function(e){t[e]=C[e],A.ready(e,function(){s(t)&&u(n)})}),A}if("string"!=typeof e||!a(n))return A;var o=C[e];if(o&&o.state===U||"ALL"===e&&s()&&L)return u(n),A;var i=w[e];return i?i.push(n):i=w[e]=[n],A}function b(){return q.body?void(L||(L=!0,j(),r(x,function(e){u(e)}))):(e.clearTimeout(A.readyTimeout),void(A.readyTimeout=e.setTimeout(b,50)))}function E(){q.addEventListener?(q.removeEventListener("DOMContentLoaded",E,!1),b()):"complete"===q.readyState&&(q.detachEvent("onreadystatechange",E),b())}var L,q=e.document,x=[],w={},C={},M="async"in q.createElement("script")||"MozAppearance"in q.documentElement.style||e.opera,O=e.head_conf&&e.head_conf.head||"head",A=e[O]=e[O]||function(){A.ready.apply(null,arguments)},S=1,k=2,I=3,U=4;if("complete"===q.readyState)b();else if(q.addEventListener)q.addEventListener("DOMContentLoaded",E,!1),e.addEventListener("load",b,!1);else{q.attachEvent("onreadystatechange",E),e.attachEvent("onload",b);var B=!1;try{B=!e.frameElement&&q.documentElement}catch(_){}B&&B.doScroll&&!function D(){if(!L){try{B.doScroll("left")}catch(n){return e.clearTimeout(A.readyTimeout),void(A.readyTimeout=e.setTimeout(D,50))}b()}}()}A.load=A.js=M?y:p,A.test=l,A.ready=T,A.ready(q,function(){s()&&r(w.ALL,function(e){u(e)}),A.feature&&A.feature("domloaded",!0)})}(window);var oc=oc||{};!function(e,n,t){oc.conf=oc.conf||{},oc.cmd=oc.cmd||[];var r,o="https://cdnjs.cloudflare.com/ajax/libs/",a=o+"jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js",c=o+"handlebars.js/3.0.1/handlebars.runtime.js",i=o+"jade/1.9.2/runtime.min.js",u=o+"jquery/1.11.2/jquery.min.js",l=oc.conf.retryInterval||5e3,d=oc.conf.pollingInterval||500,s=oc.conf.tag||"oc-component",f="Href parameter missing",m="Error getting compiled view: {0}",p="Error rendering component: {0}, error: {1}",y="Failed to retrieve the component. Retrying in {0} seconds...".replace("{0}",l/1e3),v='Error loading component: view engine "{0}" not supported',h="Loading...",g="Component '{0}' correctly rendered",j="Unrendered component found. Trying to retrieve it...",T=oc.conf.debug||!1,b=function(){},E=t.navigator.userAgent,L=!!E.match(/MSIE 8/),q=!!E.match(/MSIE 9/),x=!1,w=!1,C={error:function(e){return console.log(e)},info:function(e){return T?console.log(e):!1}};oc.require=function(n,r,o){"function"==typeof r&&(o=r,r=n,n=void 0),"string"==typeof n&&(n=[n]);var a=function(){var e=t;if("undefined"==typeof n)return!0;for(var r=0;r<n.length;r++)if(e=e[n[r]],!e)return!0;return!1},c=function(){var e=t;if("undefined"==typeof n)return void 0;for(var r=0;r<n.length;r++)if(e=e[n[r]],!e)return void 0;return e};a()?e.load(r,function(){o(c())}):o(c())};var M=function(e,n,t){var r=Math.floor(9999999999*Math.random());e.html(n.html),e.attr("id",r),e.attr("data-rendered",!0),e.attr("data-rendering",!1),e.attr("data-version",n.version),n.key&&e.attr("data-hash",n.key),t()};oc.build=function(e){if(!e.baseUrl)throw"baseUrl parameter is required";if(!e.name)throw"name parameter is required";var n=function(e){return e=e||"","/"!==e.slice(-1)&&(e+="/"),e},t=n(e.baseUrl)+n(e.name);if(e.version&&(t+=n(e.version)),e.parameters){t+="?";for(var r in e.parameters)e.parameters.hasOwnProperty(r)&&(t+=r+"="+e.parameters[r]+"&");t=t.slice(0,-1)}return"<"+s+' href="'+t+'"></'+s+">"},oc.ready=function(e){if(x)return e();if(w)oc.cmd.push(e);else{w=!0;var n=function(e){!L&&!q||r.IE_POLYFILL_LOADED?e():oc.require(a,e)},t=function(){x=!0,w=!1,e();for(var n=0;n<oc.cmd.length;n++)oc.cmd[n](oc)};oc.require("jQuery",u,function(e){r=e,n(t)})}},oc.render=function(e,n,t){oc.ready(function(){e.type.match(/jade|handlebars/g)?oc.require(["oc","components",e.key],e.src,function(r){r?"handlebars"===e.type?oc.require("Handlebars",c,function(e){var o=e.template(r,[]);t(null,o(n))}):"jade"===e.type&&oc.require("jade",i,function(){t(null,r(n))}):t(m.replace("{0}",e.src))}):t(v.replace("{0}",e.type))})},oc.renderNestedComponent=function(e,n){oc.ready(function(){var t=e.attr("data-rendering"),r=e.attr("data-rendered"),o="boolean"==typeof t?t:"true"===t,a="boolean"==typeof r?r:"true"===r;o||a?setTimeout(n,d):(C.info(j),e.attr("data-rendering",!0),e.html('
'+h+"
"),oc.renderByHref(e.attr("href"),function(t,r){return!t&&r&&r.html?void M(e,r,n):C.error(t)}))})},oc.renderByHref=function(e,n){oc.ready(function(){return""===e?n(p.replace("{1}",f)):void r.ajax({url:e,headers:{Accept:"application/vnd.oc.prerendered+json"},contentType:"text/plain",crossDomain:!0,async:!0,success:function(e){if("pre-rendered"===e.renderMode)oc.render(e.template,e.data,function(t,r){return t?n(p.replace("{0}",e.href).replace("{1}",t)):(C.info(g.replace("{0}",e.template.src)),void n(null,{html:r,key:e.template.key,version:e.version}))});else if("rendered"===e.renderMode){if(C.info(g.replace("{0}",e.href)),0===e.html.indexOf("<"+s)){var t=e.html.slice(e.html.indexOf(">")+1),r=t.slice(0,t.lastIndexOf("<"));e.html=r}n(null,{html:e.html,version:e.version})}},error:function(){C.error(y),setTimeout(function(){oc.renderByHref(e,n)},l)}})})},oc.renderUnloadedComponents=function(){oc.ready(function(){var e=L?"div[data-oc-component=true]":s,n=r(e+"[data-rendered!=true]"),t=function(e,n){oc.renderNestedComponent(r(e[n]),function(){n++,n<e.length?t(e,n):oc.renderUnloadedComponents()})};n.length>0&&t(n,0)})},oc.load=function(e,n,t){oc.ready(function(){if("function"!=typeof t&&(t=b),r(e)){r(e).html("<"+s+' href="'+n+'" />');var o=r(s,e);oc.renderNestedComponent(o,function(){t(o)})}})},oc.ready(oc.renderUnloadedComponents)}(head,document,window),oc.clientVersion="0.16.12";
<commit_msg>:tada: Update oc-client<commit_after>!function(e,n){"use strict";function t(){}function r(e,n){if(e){"object"==typeof e&&(e=[].slice.call(e));for(var t=0,r=e.length;r>t;t++)n.call(e,e[t],t)}}function o(e,t){var r=Object.prototype.toString.call(t).slice(8,-1);return t!==n&&null!==t&&r===e}function a(e){return o("Function",e)}function c(e){return o("Array",e)}function i(e){var n=e.split("/"),t=n[n.length-1],r=t.indexOf("?");return-1!==r?t.substring(0,r):t}function u(e){e=e||t,e._done||(e(),e._done=1)}function d(e,n,r,o){var a="object"==typeof e?e:{test:e,success:n?c(n)?n:[n]:!1,failure:r?c(r)?r:[r]:!1,callback:o||t},i=!!a.test;return i&&a.success?(a.success.push(a.callback),S.load.apply(null,a.success)):!i&&a.failure?(a.failure.push(a.callback),S.load.apply(null,a.failure)):o(),S}function l(e){var n={};if("object"==typeof e)for(var t in e)e[t]&&(n={name:t,url:e[t]});else n={name:i(e),url:e};var r=O[n.name];return r&&r.url===n.url?r:(O[n.name]=n,n)}function s(e){e=e||O;for(var n in e)if(e.hasOwnProperty(n)&&e[n].state!==_)return!1;return!0}function f(e){e.state=A,r(e.onpreload,function(e){e.call()})}function m(e,t){e.state===n&&(e.state=$,e.onpreload=[],g({url:e.url,type:"cache"},function(){f(e)}))}function p(){var e=arguments,n=e[e.length-1],t=[].slice.call(e,1),o=t[0];return a(n)||(n=null),c(e[0])?(e[0].push(n),S.load.apply(null,e[0]),S):(o?(r(t,function(e){!a(e)&&e&&m(l(e))}),y(l(e[0]),a(o)?o:function(){S.load.apply(null,t)})):y(l(e[0])),S)}function v(){var e=arguments,n=e[e.length-1],t={};return a(n)||(n=null),c(e[0])?(e[0].push(n),S.load.apply(null,e[0]),S):(r(e,function(e,r){e!==n&&(e=l(e),t[e.name]=e)}),r(e,function(e,r){e!==n&&(e=l(e),y(e,function(){s(t)&&u(n)}))}),S)}function y(e,n){return n=n||t,e.state===_?void n():e.state===k?void S.ready(e.name,n):e.state===$?void e.onpreload.push(function(){y(e,n)}):(e.state=k,void g(e,function(){e.state=_,n(),r(x[e.name],function(e){u(e)}),L&&s()&&r(x.ALL,function(e){u(e)})}))}function h(e){e=e||"";var n=e.split("?")[0].split(".");return n[n.length-1].toLowerCase()}function g(n,r){function o(n){n=n||e.event,i.onload=i.onreadystatechange=i.onerror=null,r()}function a(t){t=t||e.event,("load"===t.type||/loaded|complete/.test(i.readyState)&&(!C.documentMode||C.documentMode<9))&&(e.clearTimeout(n.errorTimeout),e.clearTimeout(n.cssTimeout),i.onload=i.onreadystatechange=i.onerror=null,r())}function c(){if(n.state!==_&&n.cssRetries<=20){for(var t=0,r=C.styleSheets.length;r>t;t++)if(C.styleSheets[t].href===i.href)return void a({type:"load"});n.cssRetries++,n.cssTimeout=e.setTimeout(c,250)}}r=r||t;var i,u=h(n.url);"css"===u?(i=C.createElement("link"),i.type="text/"+(n.type||"css"),i.rel="stylesheet",i.href=n.url,n.cssRetries=0,n.cssTimeout=e.setTimeout(c,500)):(i=C.createElement("script"),i.type="text/"+(n.type||"javascript"),i.src=n.url),i.onload=i.onreadystatechange=a,i.onerror=o,i.async=!1,i.defer=!1,n.errorTimeout=e.setTimeout(function(){o({type:"timeout"})},7e3);var d=C.head||C.getElementsByTagName("head")[0];d.insertBefore(i,d.lastChild)}function j(){for(var e=C.getElementsByTagName("script"),n=0,t=e.length;t>n;n++){var r=e[n].getAttribute("data-headjs-load");if(r)return void S.load(r)}}function T(e,n){if(e===C)return L?u(n):q.push(n),S;if(a(e)&&(n=e,e="ALL"),c(e)){var t={};return r(e,function(e){t[e]=O[e],S.ready(e,function(){s(t)&&u(n)})}),S}if("string"!=typeof e||!a(n))return S;var o=O[e];if(o&&o.state===_||"ALL"===e&&s()&&L)return u(n),S;var i=x[e];return i?i.push(n):i=x[e]=[n],S}function b(){return C.body?void(L||(L=!0,j(),r(q,function(e){u(e)}))):(e.clearTimeout(S.readyTimeout),void(S.readyTimeout=e.setTimeout(b,50)))}function E(){C.addEventListener?(C.removeEventListener("DOMContentLoaded",E,!1),b()):"complete"===C.readyState&&(C.detachEvent("onreadystatechange",E),b())}var L,C=e.document,q=[],x={},O={},w="async"in C.createElement("script")||"MozAppearance"in C.documentElement.style||e.opera,M=e.head_conf&&e.head_conf.head||"head",S=e[M]=e[M]||function(){S.ready.apply(null,arguments)},$=1,A=2,k=3,_=4;if("complete"===C.readyState)b();else if(C.addEventListener)C.addEventListener("DOMContentLoaded",E,!1),e.addEventListener("load",b,!1);else{C.attachEvent("onreadystatechange",E),e.attachEvent("onload",b);var I=!1;try{I=!e.frameElement&&C.documentElement}catch(U){}I&&I.doScroll&&!function B(){if(!L){try{I.doScroll("left")}catch(n){return e.clearTimeout(S.readyTimeout),void(S.readyTimeout=e.setTimeout(B,50))}b()}}()}S.load=S.js=w?v:p,S.test=d,S.ready=T,S.ready(C,function(){s()&&r(x.ALL,function(e){u(e)}),S.feature&&S.feature("domloaded",!0)})}(window);var oc=oc||{};!function(e,n,t){if(oc.conf=oc.conf||{},oc.cmd=oc.cmd||[],oc.renderedComponents=oc.renderedComponents||{},oc.status=oc.status||!1,oc.status)return oc;oc.status="loading";var r="https://cdnjs.cloudflare.com/ajax/libs/",o=r+"jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js",a=r+"handlebars.js/3.0.1/handlebars.runtime.js",c=r+"jade/1.9.2/runtime.min.js",i=r+"jquery/1.11.2/jquery.min.js",u=oc.conf.retryInterval||5e3,d=oc.conf.retryLimit||30,l=oc.conf.retrySendNumber||!0,s=oc.conf.pollingInterval||500,f=oc.conf.tag||"oc-component",m="baseUrl parameter is required",p="Href parameter missing",v="name parameter is required",y="Failed to load {0} component {1} times. Giving up".replace("{1}",d),h="Error getting compiled view: {0}",g="Error rendering component: {0}, error: {1}",j="Failed to retrieve the component. Retrying in {0} seconds...".replace("{0}",u/1e3),T='Error loading component: view engine "{0}" not supported',b="Loading...",E="Component '{0}' correctly rendered",L="Unrendered component found. Trying to retrieve it...",C=oc.conf.debug||!1,q=function(){},x=t.navigator.userAgent,O=!!x.match(/MSIE 8/),w=!!x.match(/MSIE 9/),M=!1,S=!1,$={},A=function(e){return"boolean"==typeof e},k={error:function(e){return console.log(e)},info:function(e){return C?console.log(e):!1}},_=function(e,n,t){return void 0===$[e]&&($[e]=d),$[e]<=0?t():(setTimeout(function(){n(d-$[e]+1)},u),void $[e]--)},I=function(e,n){if(e&&n){var t=oc.$.param(n);return e.indexOf("?")>-1?e+"&"+t:e+"?"+t}return e};oc.require=function(n,r,o){"function"==typeof r&&(o=r,r=n,n=void 0),"string"==typeof n&&(n=[n]);var a=function(){var e=t;if("undefined"==typeof n)return!0;for(var r=0;r<n.length;r++)if(e=e[n[r]],!e)return!0;return!1},c=function(){var e=t;if("undefined"!=typeof n){for(var r=0;r<n.length;r++)if(e=e[n[r]],!e)return;return e}};a()?e.load(r,function(){o(c())}):o(c())};var U=function(e,n,t){n.id=Math.floor(9999999999*Math.random()),e.html(n.html),e.attr("id",n.id),e.attr("data-rendered",!0),e.attr("data-rendering",!1),e.attr("data-version",n.version),n.key&&e.attr("data-hash",n.key),n.name&&(e.attr("data-name",n.name),oc.renderedComponents[n.name]=n.version,oc.events.fire("oc:rendered",n)),t()};oc.build=function(e){if(!e.baseUrl)throw m;if(!e.name)throw v;var n=function(e){return e=e||"","/"!==e.slice(-1)&&(e+="/"),e},t=n(e.baseUrl)+n(e.name);if(e.version&&(t+=n(e.version)),e.parameters){t+="?";for(var r in e.parameters)e.parameters.hasOwnProperty(r)&&(t+=r+"="+e.parameters[r]+"&");t=t.slice(0,-1)}return O?'

':"<"+f+' href="'+t+'"></'+f+">"},oc.events={},oc.ready=function(e){if(M)return e();if(S)oc.cmd.push(e);else{S=!0;var n=function(e,n){!O&&!w||e.IE_POLYFILL_LOADED?n():oc.require(o,n)},r=function(){M=!0,S=!1,oc.events=function(){var e=oc.$({});return{fire:function(n,t){return e.trigger(n,t)},on:function(n,t){return e.on(n,t||q)},reset:function(){return e.off()}}}(),e(),oc.events.fire("oc:ready",oc),oc.status="ready";for(var n=0;n<oc.cmd.length;n++)oc.cmd[n](oc);oc.cmd={push:function(e){e(oc)}}},a=!!t.$;oc.require("jQuery",i,function(e){n(e,function(){a?oc.$=e:oc.$=e.noConflict(),r()})})}},oc.render=function(e,n,t){oc.ready(function(){e.type.match(/jade|handlebars/g)?oc.require(["oc","components",e.key],e.src,function(r){r?"handlebars"===e.type?oc.require("Handlebars",a,function(e){var o=e.template(r,[]);t(null,o(n))}):"jade"===e.type&&oc.require("jade",c,function(e){t(null,r(n))}):t(h.replace("{0}",e.src))}):t(T.replace("{0}",e.type))})},oc.renderNestedComponent=function(e,n){oc.ready(function(){var t=e.attr("data-rendering"),r=e.attr("data-rendered"),o=A(t)?t:"true"===t,a=A(r)?r:"true"===r;o||a?setTimeout(n,s):(k.info(L),e.attr("data-rendering",!0),e.html('
'+b+"
"),oc.renderByHref(e.attr("href"),function(t,r){return t||!r?(k.error(t),n()):void U(e,r,n)}))})},oc.renderByHref=function(e,n,t){var r=t,o=n;"function"==typeof n&&(r=n,o=0),oc.ready(function(){if(""===e)return r(g.replace("{1}",p));var n=e;l&&(n=I(n,{__oc_Retry:o})),oc.$.ajax({url:n,headers:{Accept:"application/vnd.oc.unrendered+json"},contentType:"text/plain",crossDomain:!0,async:!0,success:function(e){if("unrendered"===e.renderMode)oc.render(e.template,e.data,function(n,t){return n?r(g.replace("{0}",e.href).replace("{1}",n)):(k.info(E.replace("{0}",e.template.src)),void r(null,{html:t,key:e.template.key,version:e.version,name:e.name}))});else if("rendered"===e.renderMode){if(k.info(E.replace("{0}",e.href)),0===e.html.indexOf("<"+f)){var n=e.html.slice(e.html.indexOf(">")+1),t=n.slice(0,n.lastIndexOf("<"));e.html=t}r(null,{html:e.html,version:e.version,name:e.name})}},error:function(){k.error(j),_(e,function(n){oc.renderByHref(e,n,r)},function(){r(y.replace("{0}",e))})}})})},oc.renderUnloadedComponents=function(){oc.ready(function(){var e=O?"div[data-oc-component=true]":f,n=oc.$(e+"[data-rendered!=true]"),t=n.length,r=function(e){t--,t||oc.renderUnloadedComponents()};if(t>0)for(var o=0;o<n.length;o++)oc.renderNestedComponent(oc.$(n[o]),r)})},oc.load=function(e,n,t){oc.ready(function(){if("function"!=typeof t&&(t=q),oc.$(e)){oc.$(e).html("<"+f+' href="'+n+'" />');var r=oc.$(f,e);oc.renderNestedComponent(r,function(){t(r)})}})},oc.ready(oc.renderUnloadedComponents)}(head,document,window),oc.clientVersion="0.27.9";
//# sourceMappingURL=oc-client.min.map
<|endoftext|>


<commit_before>(function (Uploads) {
    'use strict';

    var async      = require('async'),
        fse        = require('fs-extra'),
        multer     = require('multer'),
        path       = require('path'),
        shortId    = require('shortid'),

        constants  = require('./constants'),
        controller = require('./controller'),
        nodebb     = require('./nodebb');

    var files = {},
        nconf = nodebb.nconf;

    // Multer File Object - https://github.com/expressjs/multer#multer-file-object

    Uploads.init = function (router, middleware, done) {
        async.waterfall([
            async.apply(createTemporalStorage),
            function (storage, next) {
                addRoute(storage, router, middleware, next);
            }
        ], done);
    };

    function addRoute(storage, router, middleware, done) {
        var route = path.join(
            constants.API_PATH,
            constants.PLUGIN_PATH,
            constants.IMAGE_SERVICE_PATH
        );
        var fileMiddleware = multer({storage: storage}).single('award');

        router.post(route, [fileMiddleware, middleware.applyCSRF, middleware.authenticate], function (req, res, next) {
            let entityId = req.headers['x-ns-award-entity-id'];

            storeLocal(req.file, function (error, file) {
                if (error) {
                    return res.status(500).json(error);
                }

                files[entityId] = file;

                res.json({
                    entityId: entityId,
                    file    : file,
                    storage : 'local'
                });
            });
        });

        done(null);
    }

    function createTemporalStorage(done) {
        let storage = multer.diskStorage({
            destination: function (req, file, next) {
                next(null, path.resolve(__dirname, '../public/uploads/'));
            },
            filename   : function (req, file, next) {
                next(null, 'award-' + shortId.generate() + path.extname(file.originalname));
            }
        });
        done(null, storage);
    }

    Uploads.getFileById = function (id, done) {
        done(null, files[id]);
    };

    Uploads.getUploadPath = function (fileName) {
        return path.join(nconf.get('base_dir'), nconf.get('upload_path'), constants.UPLOAD_DIR, fileName);
    };

    function storeLocal(file, done) {
        var uploadPath = Uploads.getUploadPath(file.filename);

        async.series([
            async.apply(fse.copy, file.path, uploadPath),
            async.apply(fse.remove, file.path)
        ], function (error) {
            if (error) {
                return done(error);
            }
            done(null, Object.assign({}, file, {path: uploadPath}));
        });
    }

})(module.exports);
<commit_msg>user part of original name in the asset<commit_after>(function (Uploads) {
    'use strict';

    var async      = require('async'),
        fse        = require('fs-extra'),
        multer     = require('multer'),
        path       = require('path'),
        shortId    = require('shortid'),

        constants  = require('./constants'),
        controller = require('./controller'),
        nodebb     = require('./nodebb');

    var files = {},
        nconf = nodebb.nconf;

    // Multer File Object - https://github.com/expressjs/multer#multer-file-object

    Uploads.init = function (router, middleware, done) {
        async.waterfall([
            async.apply(createTemporalStorage),
            function (storage, next) {
                addRoute(storage, router, middleware, next);
            }
        ], done);
    };

    function addRoute(storage, router, middleware, done) {
        var route = path.join(
            constants.API_PATH,
            constants.PLUGIN_PATH,
            constants.IMAGE_SERVICE_PATH
        );
        var fileMiddleware = multer({storage: storage}).single('award');

        router.post(route, [fileMiddleware, middleware.applyCSRF, middleware.authenticate], function (req, res, next) {
            let entityId = req.headers['x-ns-award-entity-id'];

            storeLocal(req.file, function (error, file) {
                if (error) {
                    return res.status(500).json(error);
                }

                files[entityId] = file;

                res.json({
                    entityId: entityId,
                    file    : file,
                    storage : 'local'
                });
            });
        });

        done(null);
    }

    function createTemporalStorage(done) {
        let storage = multer.diskStorage({
            destination: function (req, file, next) {
                next(null, path.resolve(__dirname, '../public/uploads/'));
            },
            filename   : function (req, file, next) {
                var name = 'award-';
                // Use first 8 characters from the original file
                name += file.originalname.slice(0, 8) + '-';
                name += shortId.generate();
                // Append image extension
                name += path.extname(file.originalname);
                next(null, name);
            }
        });
        done(null, storage);
    }

    Uploads.getFileById = function (id, done) {
        done(null, files[id]);
    };

    Uploads.getUploadPath = function (fileName) {
        return path.join(nconf.get('base_dir'), nconf.get('upload_path'), constants.UPLOAD_DIR, fileName);
    };

    function storeLocal(file, done) {
        var uploadPath = Uploads.getUploadPath(file.filename);

        async.series([
            async.apply(fse.copy, file.path, uploadPath),
            async.apply(fse.remove, file.path)
        ], function (error) {
            if (error) {
                return done(error);
            }
            done(null, Object.assign({}, file, {path: uploadPath}));
        });
    }

})(module.exports);
<|endoftext|>


<commit_before>var request = require("request");

function ChoosePlugin(bot) {
	var self = this;
	self.name = "choose";
	self.help = "Random chooser plugin";
	self.depend = ["cmd"];

	self.events = {
		"cmd#choose": function(nick, to, args) {
			var choices = args[0].split(",");
			if (choices.length == 1 && choices[0].trim() == "") {
				bot.say(to, "Nothing to choose from");
			}
			else if (choices.length == 1) {
				bot.say(to, "random.org chose '\x02" + choices[0].trim() + "\x02'");
				bot.say(to, "ANU chose '\x02" + choices[0].trim() + "\x02'");
			}
			else {
				request("http://www.random.org/integers/?num=1&min=0&max=" + (choices.length - 1) + "&col=1&base=10&format=plain&rnd=new", function(err, res, body) {
					if (!err && res.statusCode == 200) {
						var i = parseInt(body.toString().trim());
						bot.say(to, "random.org chose '\x02" + choices[i].trim() + "\x02'");
					}
				});

				request("http://qrng.anu.edu.au/form_handler.php?numofsets=1&num_per_set=1&repeats=no&min_num=0&max_num=" + (choices.length - 1) + "&time=" + Date.now(), function(err, res, body) {
					if (!err && res.statusCode == 200) {
						var re = /Set 1: (\d+)/;
						var match = body.match(re);
						if (match) {
							var i = parseInt(match[1]);
							bot.say(to, "ANU chose '\x02" + choices[i].trim() + "\x02'");
						}
					}
				});
			}
		},

		"message": function(nick, to, text) {
			var dotRe = /^\.choose(.*)/;
			var match = text.match(dotRe);
			if (match && match[1].split(",").length > 1) {
				bot.emit("cmd#choose", nick, to, [match[1]]);
			}
		}
	};
}

module.exports = ChoosePlugin;
<commit_msg>choose: organize random functions<commit_after>var request = require("request");

function ChoosePlugin(bot) {
	var self = this;
	self.name = "choose";
	self.help = "Random chooser plugin";
	self.depend = ["cmd"];

	self.randoms = {
		"random.org": function(n, callback) {
			request("http://www.random.org/integers/?num=1&min=0&max=" + (n - 1) + "&col=1&base=10&format=plain&rnd=new", function(err, res, body) {
				if (!err && res.statusCode == 200) {
					var i = parseInt(body.toString().trim());
					callback(i);
				}
			});
		},

		"ANU": function(n, callback) {
			request("http://qrng.anu.edu.au/form_handler.php?numofsets=1&num_per_set=1&repeats=no&min_num=0&max_num=" + (n - 1) + "&time=" + Date.now(), function(err, res, body) {
				if (!err && res.statusCode == 200) {
					var re = /Set 1: (\d+)/;
					var match = body.match(re);
					if (match) {
						var i = parseInt(match[1]);
						callback(i);
					}
				}
			});
		}
	};

	self.events = {
		"cmd#choose": function(nick, to, args) {
			var choices = args[0].split(",");
			if (choices.length == 1 && choices[0].trim() == "") {
				bot.say(to, "Nothing to choose from");
			}
			else if (choices.length == 1) {
				for (var name in self.randoms)
					bot.say(to, name + " chose '\x02" + choices[0].trim() + "\x02'");
			}
			else {
				for (var name in self.randoms) {
					(function(name) {
						self.randoms[name](choices.length, function(i) {
							bot.say(to, name + " chose '\x02" + choices[i].trim() + "\x02'");
						});
					})(name);
				}
			}
		},

		"message": function(nick, to, text) {
			var dotRe = /^\.choose(.*)/;
			var match = text.match(dotRe);
			if (match && match[1].split(",").length > 1) {
				bot.emit("cmd#choose", nick, to, [match[1]]);
			}
		}
	};
}

module.exports = ChoosePlugin;
<|endoftext|>


<commit_before>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  Automatically minify code before it is sent to Espruino
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  var minifyUrl = "http://closure-compiler.appspot.com/compile";
  var minifyCache = [];

  function init() {
    Espruino.Core.Config.addSection("Minification", {
      sortOrder:600,
      description: "Minification takes your JavaScript code and makes it smaller by removing comments and whitespace. "+
                   "It can make your code execute faster and will save memory, but it will also make it harder to debug.\n"+
                   "Esprima is a minifier built in to the Web IDE, so it can be used without an internet connection. "+
                   "The Closure Compiler is an online service offered by Google. It produces more efficient code, but you need an internet connection to use it."
    });

    Espruino.Core.Config.add("MINIFICATION_LEVEL", {
      section : "Minification",
      name : "Minification",
      description : "Automatically minify code from the Editor window?",
      type : { "":"No Minification",
               "ESPRIMA":"Esprima (offline)",
               "WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
      defaultValue : ""
    });
    Espruino.Core.Config.add("MODULE_MINIFICATION_LEVEL", {
      section : "Minification",
      name : "Module Minification",
      description : "Automatically minify modules? Only modules with a .js extension will be minified - if a file with a .min.js extension exists then it will be used instead.",
      type : { "":"No Minification",
               "ESPRIMA":"Esprima (offline)",
               "WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
      defaultValue : "ESPRIMA"
    });

    Espruino.Core.Config.add("MINIFICATION_Mangle",{
      section : "Minification",
      name : "Esprima: Mangle",
      description : "Shorten variable name",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Unreachable",{
      section : "Minification",
      name : "Esprima: Unreachable branches",
      description : "Remove unreachable branches",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Unused",{
      section : "Minification",
      name : "Esprima: Unused variables",
      description : "Remove unused variables",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Literal",{
      section : "Minification",
      name : "Esprima: Fold constants",
      description : "Fold (literal) constants",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_DeadCode",{
      section : "Minification",
      name : "Esprima: Dead Code",
      description : "Eliminate dead code",
      type : "boolean",
      defaultValue : true
    });

    // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformForEspruino", function(code, callback) {
      minify(code, callback, Espruino.Config.MINIFICATION_LEVEL, false);
    });
   // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformModuleForEspruino", function(code, callback) {
      minify(code, callback, Espruino.Config.MODULE_MINIFICATION_LEVEL, true);
    });
  }

  // Use the 'offline' Esprima compile
  function minifyCodeEsprima(code,callback) {
    if ((typeof esprima == "undefined") ||
        (typeof esmangle == "undefined") ||
        (typeof escodegen == "undefined")) {
      console.warn("esprima/esmangle/escodegen not defined - not minifying")
      return callback(code);
    }

    var code, syntax, option, str, before, after;
    var options = {};
    options["mangle"] = Espruino.Config.MINIFICATION_Mangle;
    options["remove-unreachable-branch"] = Espruino.Config.MINIFICATION_Unreachable;
    options["remove-unused-vars"] = Espruino.Config.MINIFICATION_Unused;
    options["fold-constant"] = Espruino.Config.MINIFICATION_Literal;
    options["eliminate-dead-code"] = Espruino.Config.MINIFICATION_DeadCode;
    option = {format: {indent: {style: ''},quotes: 'auto',compact: true}};
    str = '';
    try {
        before = code.length;
        syntax = esprima.parse(code, { raw: true, loc: true });
        syntax = obfuscate(syntax,options);
        code = escodegen.generate(syntax, option);
        after = code.length;
        if (before > after) {
          Espruino.Core.Notifications.info('No error. Minifying ' + before + ' bytes to ' + after + ' bytes.');
          callback(code);
        } else {
          Espruino.Core.Notifications.warning('Can not minify further, code is already optimized.');
        }
    } catch (e) {
      Espruino.Core.Notifications.error(e.toString());
      console.error(e.stack);
      callback(code);
    } finally { }
  }
  function obfuscate(syntax,options) {
    // hack for random changes between version we have included for Web IDE and node.js version
    if (typeof esmangle.require == "undefined")
      esmangle.require = esmangle.pass.require;
    var result = esmangle.optimize(syntax, createPipeline(options));
    if (options.mangle) { result = esmangle.mangle(result);}
    return result;
  }
  function createPipeline(options) {
    var passes, pipeline, inputs, i, el, optimizer;
    passes = {
      'eliminate-dead-code': 'pass/dead-code-elimination',
      'fold-constant': 'pass/tree-based-constant-folding',
      'remove-unreachable-branch': 'pass/remove-unreachable-branch',
      'remove-unused-vars': 'pass/drop-variable-definition'
    };
    pipeline = [
      'pass/hoist-variable-to-arguments',
      'pass/transform-dynamic-to-static-property-access',
      'pass/transform-dynamic-to-static-property-definition',
      'pass/transform-immediate-function-call',
      'pass/transform-logical-association',
      'pass/reordering-function-declarations',
      'pass/remove-unused-label',
      'pass/remove-empty-statement',
      'pass/remove-wasted-blocks',
      'pass/transform-to-compound-assignment',
      'pass/transform-to-sequence-expression',
      'pass/transform-branch-to-expression',
      'pass/transform-typeof-undefined',
      'pass/reduce-sequence-expression',
      'pass/reduce-branch-jump',
      'pass/reduce-multiple-if-statements',
      'pass/dead-code-elimination',
      'pass/remove-side-effect-free-expressions',
      'pass/remove-context-sensitive-expressions',
      'pass/tree-based-constant-folding',
      'pass/drop-variable-definition',
      'pass/remove-unreachable-branch'
    ];
    for(var i in passes){if(!options[i]){delete(passes[i])};}
    pipeline = pipeline.map(esmangle.require);
    pipeline = [pipeline];
    pipeline.push({
      once: true,
      pass: [
        'post/transform-static-to-dynamic-property-access',
        'post/transform-infinity',
        'post/rewrite-boolean',
        'post/rewrite-conditional-expression'
      ].map(esmangle.require)
    });
    return pipeline;
  }

  // Use the 'online' Closure compiler
  function minifyCodeGoogle(code, callback, minificationLevel){
    for (var i in minifyCache) {
      var item = minifyCache[i];
      if (item.code==code && item.level==minificationLevel) {
        console.log("Found code in minification cache - using that");
        // move to front of cache
        minifyCache.splice(i,1); // remove old
        minifyCache.push(item); // add at front
        // callback
        callback(item.minified);
        return;
      }
    }
    closureCompilerGoogle(code,  minificationLevel, 'compiled_code', function(minified) {
      if (minified.trim()!="") {
        Espruino.Core.Notifications.info('No error. Minifying ' + code.length + ' bytes to ' + minified.length + ' bytes.');
        if (minifyCache.length>100)
          minifyCache = minifyCache.slice(-100);
        minifyCache.push({ level : minificationLevel, code : code, minified : minified });
        callback(minified);
      } else {
        Espruino.Core.Notifications.warning("Errors while minifying - sending unminified code.");
        callback(code);
        // get errors...
        closureCompilerGoogle(code,  minificationLevel, 'errors',function(errors) {
          errors.split("\n").forEach(function (err) {
            if (err.trim()!="")
              Espruino.Core.Notifications.error(err.trim());
          });
        });
      }
    });
  }
  function closureCompilerGoogle(code, minificationLevel, output_info, callback){
    if(minificationLevel !== ""){
      var minifyObj = $.param({
        compilation_level: minificationLevel,
        output_format: "text",
        output_info: output_info,
        js_code: code,
        language : "ECMASCRIPT6", // so no need to mess with binary numbers now. \o/
        language_out : "ECMASCRIPT5" // ES6 output uses some now features now that Espruino doesn't like
      });
      $.post(minifyUrl, minifyObj, function(minifiedCode) {
        code = minifiedCode;
      },"text")
      .error(function() {
        Espruino.Core.Notifications.error("HTTP error while minifying.");
      })
      .complete(function() {
        // ensure we call the callback even if minification failes
        callback(code);
      });
    }
  }

  function minify(code, callback, level, isModule) {
    var minifyCode = code;
    var minifyCallback = callback;
    if (isModule) {
      /* if we're a module, we wrap this in a function so that unused constants
      and functions can be removed */
      var header = "(function(){";
      var footer = "})();";
      minifyCode = header+code+footer;
      minifyCallback = function (minified){
        callback(minified.substr(header.length, minified.length-(header.length+footer.length+1)));
      }
    }

    switch(level){
      case "WHITESPACE_ONLY":
      case "SIMPLE_OPTIMIZATIONS":
      case "ADVANCED_OPTIMIZATIONS": minifyCodeGoogle(code, callback, level); break;
      case "ESPRIMA": minifyCodeEsprima(code, callback); break;
      default: callback(code); break;
    }
  }

  Espruino.Plugins.Minify = {
    init : init,
  };
}());
<commit_msg>still upload even if we can't minify - fix EspruinoWebIDE#122<commit_after>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  Automatically minify code before it is sent to Espruino
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  var minifyUrl = "http://closure-compiler.appspot.com/compile";
  var minifyCache = [];

  function init() {
    Espruino.Core.Config.addSection("Minification", {
      sortOrder:600,
      description: "Minification takes your JavaScript code and makes it smaller by removing comments and whitespace. "+
                   "It can make your code execute faster and will save memory, but it will also make it harder to debug.\n"+
                   "Esprima is a minifier built in to the Web IDE, so it can be used without an internet connection. "+
                   "The Closure Compiler is an online service offered by Google. It produces more efficient code, but you need an internet connection to use it."
    });

    Espruino.Core.Config.add("MINIFICATION_LEVEL", {
      section : "Minification",
      name : "Minification",
      description : "Automatically minify code from the Editor window?",
      type : { "":"No Minification",
               "ESPRIMA":"Esprima (offline)",
               "WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
      defaultValue : ""
    });
    Espruino.Core.Config.add("MODULE_MINIFICATION_LEVEL", {
      section : "Minification",
      name : "Module Minification",
      description : "Automatically minify modules? Only modules with a .js extension will be minified - if a file with a .min.js extension exists then it will be used instead.",
      type : { "":"No Minification",
               "ESPRIMA":"Esprima (offline)",
               "WHITESPACE_ONLY":"Closure (online) - Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Closure (online) - Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Closure (online) - Advanced Optimizations (not recommended)"},
      defaultValue : "ESPRIMA"
    });

    Espruino.Core.Config.add("MINIFICATION_Mangle",{
      section : "Minification",
      name : "Esprima: Mangle",
      description : "Shorten variable name",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Unreachable",{
      section : "Minification",
      name : "Esprima: Unreachable branches",
      description : "Remove unreachable branches",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Unused",{
      section : "Minification",
      name : "Esprima: Unused variables",
      description : "Remove unused variables",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_Literal",{
      section : "Minification",
      name : "Esprima: Fold constants",
      description : "Fold (literal) constants",
      type : "boolean",
      defaultValue : true
    });
    Espruino.Core.Config.add("MINIFICATION_DeadCode",{
      section : "Minification",
      name : "Esprima: Dead Code",
      description : "Eliminate dead code",
      type : "boolean",
      defaultValue : true
    });

    // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformForEspruino", function(code, callback) {
      minify(code, callback, Espruino.Config.MINIFICATION_LEVEL, false);
    });
   // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformModuleForEspruino", function(code, callback) {
      minify(code, callback, Espruino.Config.MODULE_MINIFICATION_LEVEL, true);
    });
  }

  // Use the 'offline' Esprima compile
  function minifyCodeEsprima(code,callback) {
    if ((typeof esprima == "undefined") ||
        (typeof esmangle == "undefined") ||
        (typeof escodegen == "undefined")) {
      console.warn("esprima/esmangle/escodegen not defined - not minifying")
      return callback(code);
    }

    var code, syntax, option, str, before, after;
    var options = {};
    options["mangle"] = Espruino.Config.MINIFICATION_Mangle;
    options["remove-unreachable-branch"] = Espruino.Config.MINIFICATION_Unreachable;
    options["remove-unused-vars"] = Espruino.Config.MINIFICATION_Unused;
    options["fold-constant"] = Espruino.Config.MINIFICATION_Literal;
    options["eliminate-dead-code"] = Espruino.Config.MINIFICATION_DeadCode;
    option = {format: {indent: {style: ''},quotes: 'auto',compact: true}};
    str = '';
    try {
        before = code.length;
        syntax = esprima.parse(code, { raw: true, loc: true });
        syntax = obfuscate(syntax,options);
        code = escodegen.generate(syntax, option);
        after = code.length;
        if (before > after) {
          Espruino.Core.Notifications.info('No error. Minified ' + before + ' bytes to ' + after + ' bytes.');
        } else {
          Espruino.Core.Notifications.info('Can not minify further, code is already optimized.');
        }
        callback(code);
    } catch (e) {
      Espruino.Core.Notifications.error(e.toString());
      console.error(e.stack);
      callback(code);
    } finally { }
  }
  function obfuscate(syntax,options) {
    // hack for random changes between version we have included for Web IDE and node.js version
    if (typeof esmangle.require == "undefined")
      esmangle.require = esmangle.pass.require;
    var result = esmangle.optimize(syntax, createPipeline(options));
    if (options.mangle) { result = esmangle.mangle(result);}
    return result;
  }
  function createPipeline(options) {
    var passes, pipeline, inputs, i, el, optimizer;
    passes = {
      'eliminate-dead-code': 'pass/dead-code-elimination',
      'fold-constant': 'pass/tree-based-constant-folding',
      'remove-unreachable-branch': 'pass/remove-unreachable-branch',
      'remove-unused-vars': 'pass/drop-variable-definition'
    };
    pipeline = [
      'pass/hoist-variable-to-arguments',
      'pass/transform-dynamic-to-static-property-access',
      'pass/transform-dynamic-to-static-property-definition',
      'pass/transform-immediate-function-call',
      'pass/transform-logical-association',
      'pass/reordering-function-declarations',
      'pass/remove-unused-label',
      'pass/remove-empty-statement',
      'pass/remove-wasted-blocks',
      'pass/transform-to-compound-assignment',
      'pass/transform-to-sequence-expression',
      'pass/transform-branch-to-expression',
      'pass/transform-typeof-undefined',
      'pass/reduce-sequence-expression',
      'pass/reduce-branch-jump',
      'pass/reduce-multiple-if-statements',
      'pass/dead-code-elimination',
      'pass/remove-side-effect-free-expressions',
      'pass/remove-context-sensitive-expressions',
      'pass/tree-based-constant-folding',
      'pass/drop-variable-definition',
      'pass/remove-unreachable-branch'
    ];
    for(var i in passes){if(!options[i]){delete(passes[i])};}
    pipeline = pipeline.map(esmangle.require);
    pipeline = [pipeline];
    pipeline.push({
      once: true,
      pass: [
        'post/transform-static-to-dynamic-property-access',
        'post/transform-infinity',
        'post/rewrite-boolean',
        'post/rewrite-conditional-expression'
      ].map(esmangle.require)
    });
    return pipeline;
  }

  // Use the 'online' Closure compiler
  function minifyCodeGoogle(code, callback, minificationLevel){
    for (var i in minifyCache) {
      var item = minifyCache[i];
      if (item.code==code && item.level==minificationLevel) {
        console.log("Found code in minification cache - using that");
        // move to front of cache
        minifyCache.splice(i,1); // remove old
        minifyCache.push(item); // add at front
        // callback
        callback(item.minified);
        return;
      }
    }
    closureCompilerGoogle(code,  minificationLevel, 'compiled_code', function(minified) {
      if (minified.trim()!="") {
        Espruino.Core.Notifications.info('No error. Minifying ' + code.length + ' bytes to ' + minified.length + ' bytes.');
        if (minifyCache.length>100)
          minifyCache = minifyCache.slice(-100);
        minifyCache.push({ level : minificationLevel, code : code, minified : minified });
        callback(minified);
      } else {
        Espruino.Core.Notifications.warning("Errors while minifying - sending unminified code.");
        callback(code);
        // get errors...
        closureCompilerGoogle(code,  minificationLevel, 'errors',function(errors) {
          errors.split("\n").forEach(function (err) {
            if (err.trim()!="")
              Espruino.Core.Notifications.error(err.trim());
          });
        });
      }
    });
  }
  function closureCompilerGoogle(code, minificationLevel, output_info, callback){
    if(minificationLevel !== ""){
      var minifyObj = $.param({
        compilation_level: minificationLevel,
        output_format: "text",
        output_info: output_info,
        js_code: code,
        language : "ECMASCRIPT6", // so no need to mess with binary numbers now. \o/
        language_out : "ECMASCRIPT5" // ES6 output uses some now features now that Espruino doesn't like
      });
      $.post(minifyUrl, minifyObj, function(minifiedCode) {
        code = minifiedCode;
      },"text")
      .error(function() {
        Espruino.Core.Notifications.error("HTTP error while minifying.");
      })
      .complete(function() {
        // ensure we call the callback even if minification failes
        callback(code);
      });
    }
  }

  function minify(code, callback, level, isModule) {
    var minifyCode = code;
    var minifyCallback = callback;
    if (isModule) {
      /* if we're a module, we wrap this in a function so that unused constants
      and functions can be removed */
      var header = "(function(){";
      var footer = "})();";
      minifyCode = header+code+footer;
      minifyCallback = function (minified){
        callback(minified.substr(header.length, minified.length-(header.length+footer.length+1)));
      }
    }

    switch(level){
      case "WHITESPACE_ONLY":
      case "SIMPLE_OPTIMIZATIONS":
      case "ADVANCED_OPTIMIZATIONS": minifyCodeGoogle(code, callback, level); break;
      case "ESPRIMA": minifyCodeEsprima(code, callback); break;
      default: callback(code); break;
    }
  }

  Espruino.Plugins.Minify = {
    init : init,
  };
}());
<|endoftext|>


<commit_before>/**
 * Extends support for global error handling for asynchronous browser
 * functions. Adopted from Closure Library's errorhandler.js
 */
;(function extendToAsynchronousCallbacks(window, Raven) {

var _helper = function _helper(fnName) {
    var originalFn = window[fnName];
    window[fnName] = function ravenAsyncExtension() {
        // Make a copy of the arguments
        var args = _slice.call(arguments);
        var originalCallback = args[0];
        if (typeof (originalCallback) === 'function') {
            args[0] = Raven.wrap(originalCallback);
        }
        // IE < 9 doesn't support .call/.apply on setInterval/etTimeout, but it
        // also only supports 2 argument and doesn't care what this" is, so we
        // can just call the original function directly.
        if (originalFn.apply) {
            return originalFn.apply(this, args);
        } else {
            return originalFn(args[0], args[1]);
        }
    };
};

_helper('setTimeout');
_helper('setInterval');

}(this, Raven));
<commit_msg>plugins/native.js fix on _slice is undefined<commit_after>/**
 * Extends support for global error handling for asynchronous browser
 * functions. Adopted from Closure Library's errorhandler.js
 */
;(function extendToAsynchronousCallbacks(window, Raven) {

var _helper = function _helper(fnName) {
    var originalFn = window[fnName];
    window[fnName] = function ravenAsyncExtension() {
        // Make a copy of the arguments
        var args = [].slice.call(arguments);
        var originalCallback = args[0];
        if (typeof (originalCallback) === 'function') {
            args[0] = Raven.wrap(originalCallback);
        }
        // IE < 9 doesn't support .call/.apply on setInterval/etTimeout, but it
        // also only supports 2 argument and doesn't care what this" is, so we
        // can just call the original function directly.
        if (originalFn.apply) {
            return originalFn.apply(this, args);
        } else {
            return originalFn(args[0], args[1]);
        }
    };
};

_helper('setTimeout');
_helper('setInterval');

}(this, Raven));
<|endoftext|>


<commit_before>var request = require("request");

function OmeglePlugin(bot) {
	var self = this;
	self.name = "omegle";
	self.help = "Omegle plugin";
	self.depend = ["cmd"];

	self.regex = /^(\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)\s*[,:]|>)\s*(.*)$/i

	self.chats = {};

	self.disable = function() {
		for (var to in self.chats) {
			self.chats[to].hardDisconnect();
		}
		self.chats = {};
	};

	self.start = function(to) {
		var server = "http://front1.omegle.com/";
		request.post({url: server + "start", form: {"rcs": 1}}, function(err, res, body) {
			if (!err && res.statusCode == 200) {
				var data = JSON.parse(body);
				var interval = setInterval(function() {
					request.post({url: server + "events", form: {"id": data}}, function(err, res, body) {
						if (!err && res.statusCode == 200) {
							var eventdata = JSON.parse(body);
							if (eventdata != null) {
								for (var i = 0; i < eventdata.length; i++) {
									switch (eventdata[i][0]) {
									case "waiting":
										bot.notice(to, "waiting for stranger");
										break;
									case "connected":
										bot.notice(to, "stranger connected");
										break;
									case "typing":
										bot.notice(to, "typing...");
										break;
									case "stoppedTyping":
										bot.notice(to, "stopped typing");
										break;
									case "gotMessage":
										bot.say(to, "\x02" + eventdata[i][1]);
										break;
									case "strangerDisconnected":
										bot.notice(to, "stranger disconnected");
										self.chats[to].softDisconnect();
										break;
									}
								}
							}
						}
					});
				}, 1000);
				var hardDisconnect = function() {
					request.post({url: server + "disconnect", form: {"id": data}});
					clearInterval(interval);
				};
				var softDisconnect = function() {
					hardDisconnect();
					if (self.chats[to].auto) {
						self.start(to);
					}
					else {
						delete self.chats[to];
					}
				};

				var auto = self.chats[to] === undefined ? false : self.chats[to].auto;
				self.chats[to] = {"server": server, "id": data, "interval": interval, "hardDisconnect": hardDisconnect, "softDisconnect": softDisconnect, "auto": auto};
			}
		});
	};

	self.events = {
		"cmd#omegle": function(nick, to, args) {
			if (!(to in self.chats)) {
				bot.notice(to, "omegle started");
				self.start(to);
			}
			else
				bot.notice(to, "omegle already started");
		},

		"cmd#unomegle": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
				delete self.chats[to];
				bot.notice(to, "omegle stopped");
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#reomegle": function(nick, to, args, message) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
			}
			self.start(to);
		},

		"cmd#autoomegle": function(nick, to, args) {
			if (to in self.chats) {
				if (self.chats[to].auto) {
					self.chats[to].auto = false;
					bot.notice(to, "autoreomegle disabled");
				}
				else {
					self.chats[to].auto = true;
					bot.notice(to, "autoreomegle enabled");
				}
			}
			else
				bot.notice(to, "omegle not started");
		},

		"nocmd": function(nick, to, text) {
			if (to in self.chats)
			{
				var match = text.match(self.regex);
				if (nick == to || (match && (match[1] == ">" || match[2] == bot.nick))) {
					request.post({url: self.chats[to].server + "send", form: {"id": self.chats[to].id, "msg": (nick != to ? match[3] : text)}});
				}
			}
		}
	}
}

module.exports = OmeglePlugin;
<commit_msg>Omegle plugin support for languages and interests<commit_after>var request = require("request");
var qs = require("querystring");

function OmeglePlugin(bot) {
	var self = this;
	self.name = "omegle";
	self.help = "Omegle plugin";
	self.depend = ["cmd"];

	self.regex = /^(\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)\s*[,:]|>)\s*(.*)$/i

	self.chats = {};

	self.disable = function() {
		for (var to in self.chats) {
			self.chats[to].hardDisconnect();
		}
		self.chats = {};
	};

	self.start = function(to, topics, lang) {
		if (self.chats[to] === undefined) {
			self.chats[to] = {
				"auto": false,
				"lang": lang || "en",
				"topics": topics || []
			};
		}

		var server = "http://front1.omegle.com/";
		self.chats[to].server = server;

		var query = {
			"rcs": 1,
			//"firstevents": 1,
			"spid": "",
			"lang": self.chats[to].lang,
			"topics": JSON.stringify(self.chats[to].topics)
		};
		request.post({url: server + "start?" + qs.stringify(query) }, function(err, res, body) {
			if (!err && res.statusCode == 200) {
				var data = JSON.parse(body);
				self.chats[to].id = data;
				var interval = setInterval(function() {
					request.post({url: server + "events", form: {"id": data}}, function(err, res, body) {
						if (!err && res.statusCode == 200) {
							var eventdata = JSON.parse(body);
							if (eventdata != null) {
								for (var i = 0; i < eventdata.length; i++) {
									switch (eventdata[i][0]) {
									case "waiting":
										bot.notice(to, "waiting for stranger [lang: " + self.chats[to].lang + "; interests: " + self.chats[to].topics.join(",") + "]");
										break;
									case "connected":
										bot.notice(to, "stranger connected");
										break;
									case "typing":
										bot.notice(to, "typing...");
										break;
									case "stoppedTyping":
										bot.notice(to, "stopped typing");
										break;
									case "gotMessage":
										bot.say(to, "\x02" + eventdata[i][1]);
										break;
									case "strangerDisconnected":
										bot.notice(to, "stranger disconnected");
										self.chats[to].softDisconnect();
										break;
									}
								}
							}
						}
					});
				}, 1000);
				var hardDisconnect = function() {
					request.post({url: server + "disconnect", form: {"id": data}});
					clearInterval(interval);
				};
				var softDisconnect = function() {
					hardDisconnect();
					if (self.chats[to].auto) {
						self.start(to);
					}
					else {
						delete self.chats[to];
					}
				};

				self.chats[to].interval = interval;
				self.chats[to].hardDisconnect = hardDisconnect;
				self.chats[to].softDisconnect = softDisconnect;
			}
		});
	};

	self.events = {
		"cmd#omegle": function(nick, to, args) {
			if (!(to in self.chats)) {
				bot.notice(to, "omegle started");
				self.start(to, args[1].split(","), args[2]);
			}
			else
				bot.notice(to, "omegle already started");
		},

		"cmd#unomegle": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
				delete self.chats[to];
				bot.notice(to, "omegle stopped");
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#reomegle": function(nick, to, args, message) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
			}
			self.start(to);
		},

		"cmd#autoomegle": function(nick, to, args) {
			if (to in self.chats) {
				if (self.chats[to].auto) {
					self.chats[to].auto = false;
					bot.notice(to, "autoreomegle disabled");
				}
				else {
					self.chats[to].auto = true;
					bot.notice(to, "autoreomegle enabled");
				}
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#lang": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].lang = args[1];
			}
		},

		"cmd#interests": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].topics = args[1].split(",");
			}
		},

		"nocmd": function(nick, to, text) {
			if (to in self.chats)
			{
				var match = text.match(self.regex);
				if (nick == to || (match && (match[1] == ">" || match[2] == bot.nick))) {
					request.post({url: self.chats[to].server + "send", form: {"id": self.chats[to].id, "msg": (nick != to ? match[3] : text)}});
				}
			}
		}
	}
}

module.exports = OmeglePlugin;
<|endoftext|>


<commit_before>var request = require("request");
var qs = require("querystring");

function OmeglePlugin(bot) {
	var self = this;
	self.name = "omegle";
	self.help = "Omegle plugin";
	self.depend = ["cmd"];

	self.regex = /^(\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)\s*[,:]|>)\s*(.*)$/i;

	self.skips = [];

	self.load = function(data) {
		if (data) {
			self.skips = data.skips;
		}
	};

	self.save = function() {
		return {"skips": self.skips};
	};

	self.chats = {};

	self.disable = function() {
		for (var to in self.chats) {
			self.chats[to].hardDisconnect();
		}
		self.chats = {};
	};

	self.start = function(to, topics, lang) {
		if (self.chats[to] === undefined) {
			self.chats[to] = {
				"auto": false,
				"lang": lang || "en",
				"topics": topics || []
			};
		}
		else {
			if (topics !== undefined)
				self.chats[to].topics = topics;
			if (lang !== undefined)
				self.chats[to].lang = lang;
		}

		var server = "http://front1.omegle.com/";
		self.chats[to].server = server;

		var query = {
			"rcs": 1,
			//"firstevents": 1,
			"spid": "",
			"lang": self.chats[to].lang,
			"topics": JSON.stringify(self.chats[to].topics)
		};
		request.post({url: server + "start?" + qs.stringify(query) }, function(err, res, body) {
			if (!err && res.statusCode == 200) {
				var data = JSON.parse(body);
				self.chats[to].id = data;
				var interval = setInterval(function() {
					request.post({url: server + "events", form: {"id": data}}, function(err, res, body) {
						if (!err && res.statusCode == 200) {
							var eventdata = JSON.parse(body);
							if (eventdata != null) {
								for (var i = 0; i < eventdata.length; i++) {
									switch (eventdata[i][0]) {
									case "waiting":
										bot.notice(to, "waiting for stranger [lang: " + self.chats[to].lang + "; interests: " + self.chats[to].topics.join(",") + "]");
										break;
									case "connected":
										bot.out.log("omegle", "stranger connected in " + to);
										bot.notice(to, "stranger connected");
										break;
									case "typing":
										bot.notice(to, "typing...");
										break;
									case "stoppedTyping":
										bot.notice(to, "stopped typing");
										break;
									case "gotMessage":
										var msg = eventdata[i][1];
										bot.out.log("omegle", "stranger in " + to + ": " + msg);
										bot.say(to, "\x02" + msg);
										if (self.skips.some(function(skip) {
											return msg.match(new RegExp(skip));
										})) {
											bot.out.log("omegle", "stranger is bot, skipping");
											bot.notice(to, "bot detected, skipping");
											self.chats[to].softDisconnect();
										}
										break;
									case "strangerDisconnected":
										bot.out.log("omegle", "stranger disconnected");
										bot.notice(to, "stranger disconnected");
										self.chats[to].softDisconnect();
										break;
									case "statusInfo":
										//bot.notice(to, "Omegle users online: " + eventdata[i][1].count);
										break;
									case "commonLikes":
										bot.notice(to, "common likes: " + eventdata[i][1].join(","));
										break;
									}
								}
							}
						}
					});
				}, 1000);
				var hardDisconnect = function() {
					request.post({url: server + "disconnect", form: {"id": data}});
					clearInterval(interval);
				};
				var softDisconnect = function() {
					hardDisconnect();
					if (self.chats[to].auto) {
						self.start(to);
					}
					else {
						delete self.chats[to];
					}
				};

				self.chats[to].interval = interval;
				self.chats[to].hardDisconnect = hardDisconnect;
				self.chats[to].softDisconnect = softDisconnect;
			}
			else {
				bot.notice(to, "omegle failure");
				delete self.chats[to];
			}
		});
	};

	self.events = {
		"cmd#omegle": function(nick, to, args) {
			if (!(to in self.chats)) {
				bot.notice(to, "omegle started");
				self.start(to, args[1] === undefined ? undefined : args[1].split(","), args[2]);
			}
			else
				bot.notice(to, "omegle already started");
		},

		"cmd#unomegle": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
				delete self.chats[to];
				bot.out.log("omegle", nick + " in " + to + " disconnected");
				bot.notice(to, "omegle stopped");
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#reomegle": function(nick, to, args, message) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
			}
			self.start(to, args[1] === undefined ? undefined : args[1].split(","), args[2]);
		},

		"cmd#autoomegle": function(nick, to, args) {
			if (to in self.chats) {
				if (self.chats[to].auto) {
					self.chats[to].auto = false;
					bot.notice(to, "autoreomegle disabled");
				}
				else {
					self.chats[to].auto = true;
					bot.notice(to, "autoreomegle enabled");
				}
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#lang": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].lang = args[1];
			}
		},

		"cmd#interests": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].topics = args[1].split(",");
			}
		},

		"nocmd": function(nick, to, text) {
			if (to in self.chats)
			{
				var match = text.match(self.regex);
				if (nick == to || (match && (match[1] == ">" || match[2] == bot.nick))) {
					var msg = nick != to ? match[3] : text;
					bot.out.log("omegle", nick + " in " + to + ": " + msg);
					request.post({url: self.chats[to].server + "send", form: {"id": self.chats[to].id, "msg": msg}});
				}
			}
		}
	}
}

module.exports = OmeglePlugin;
<commit_msg>Don't match other bots' >>><commit_after>var request = require("request");
var qs = require("querystring");

function OmeglePlugin(bot) {
	var self = this;
	self.name = "omegle";
	self.help = "Omegle plugin";
	self.depend = ["cmd"];

	self.regex = /^(\s*([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*)\s*[,:]|>(?!>))\s*(.*)$/i;

	self.skips = [];

	self.load = function(data) {
		if (data) {
			self.skips = data.skips;
		}
	};

	self.save = function() {
		return {"skips": self.skips};
	};

	self.chats = {};

	self.disable = function() {
		for (var to in self.chats) {
			self.chats[to].hardDisconnect();
		}
		self.chats = {};
	};

	self.start = function(to, topics, lang) {
		if (self.chats[to] === undefined) {
			self.chats[to] = {
				"auto": false,
				"lang": lang || "en",
				"topics": topics || []
			};
		}
		else {
			if (topics !== undefined)
				self.chats[to].topics = topics;
			if (lang !== undefined)
				self.chats[to].lang = lang;
		}

		var server = "http://front1.omegle.com/";
		self.chats[to].server = server;

		var query = {
			"rcs": 1,
			//"firstevents": 1,
			"spid": "",
			"lang": self.chats[to].lang,
			"topics": JSON.stringify(self.chats[to].topics)
		};
		request.post({url: server + "start?" + qs.stringify(query) }, function(err, res, body) {
			if (!err && res.statusCode == 200) {
				var data = JSON.parse(body);
				self.chats[to].id = data;
				var interval = setInterval(function() {
					request.post({url: server + "events", form: {"id": data}}, function(err, res, body) {
						if (!err && res.statusCode == 200) {
							var eventdata = JSON.parse(body);
							if (eventdata != null) {
								for (var i = 0; i < eventdata.length; i++) {
									switch (eventdata[i][0]) {
									case "waiting":
										bot.notice(to, "waiting for stranger [lang: " + self.chats[to].lang + "; interests: " + self.chats[to].topics.join(",") + "]");
										break;
									case "connected":
										bot.out.log("omegle", "stranger connected in " + to);
										bot.notice(to, "stranger connected");
										break;
									case "typing":
										bot.notice(to, "typing...");
										break;
									case "stoppedTyping":
										bot.notice(to, "stopped typing");
										break;
									case "gotMessage":
										var msg = eventdata[i][1];
										bot.out.log("omegle", "stranger in " + to + ": " + msg);
										bot.say(to, "\x02" + msg);
										if (self.skips.some(function(skip) {
											return msg.match(new RegExp(skip));
										})) {
											bot.out.log("omegle", "stranger is bot, skipping");
											bot.notice(to, "bot detected, skipping");
											self.chats[to].softDisconnect();
										}
										break;
									case "strangerDisconnected":
										bot.out.log("omegle", "stranger disconnected");
										bot.notice(to, "stranger disconnected");
										self.chats[to].softDisconnect();
										break;
									case "statusInfo":
										//bot.notice(to, "Omegle users online: " + eventdata[i][1].count);
										break;
									case "commonLikes":
										bot.notice(to, "common likes: " + eventdata[i][1].join(","));
										break;
									}
								}
							}
						}
					});
				}, 1000);
				var hardDisconnect = function() {
					request.post({url: server + "disconnect", form: {"id": data}});
					clearInterval(interval);
				};
				var softDisconnect = function() {
					hardDisconnect();
					if (self.chats[to].auto) {
						self.start(to);
					}
					else {
						delete self.chats[to];
					}
				};

				self.chats[to].interval = interval;
				self.chats[to].hardDisconnect = hardDisconnect;
				self.chats[to].softDisconnect = softDisconnect;
			}
			else {
				bot.notice(to, "omegle failure");
				delete self.chats[to];
			}
		});
	};

	self.events = {
		"cmd#omegle": function(nick, to, args) {
			if (!(to in self.chats)) {
				bot.notice(to, "omegle started");
				self.start(to, args[1] === undefined ? undefined : args[1].split(","), args[2]);
			}
			else
				bot.notice(to, "omegle already started");
		},

		"cmd#unomegle": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
				delete self.chats[to];
				bot.out.log("omegle", nick + " in " + to + " disconnected");
				bot.notice(to, "omegle stopped");
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#reomegle": function(nick, to, args, message) {
			if (to in self.chats) {
				self.chats[to].hardDisconnect();
			}
			self.start(to, args[1] === undefined ? undefined : args[1].split(","), args[2]);
		},

		"cmd#autoomegle": function(nick, to, args) {
			if (to in self.chats) {
				if (self.chats[to].auto) {
					self.chats[to].auto = false;
					bot.notice(to, "autoreomegle disabled");
				}
				else {
					self.chats[to].auto = true;
					bot.notice(to, "autoreomegle enabled");
				}
			}
			else
				bot.notice(to, "omegle not started");
		},

		"cmd#lang": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].lang = args[1];
			}
		},

		"cmd#interests": function(nick, to, args) {
			if (to in self.chats) {
				self.chats[to].topics = args[1].split(",");
			}
		},

		"nocmd": function(nick, to, text) {
			if (to in self.chats)
			{
				var match = text.match(self.regex);
				if (nick == to || (match && (match[1] == ">" || match[2] == bot.nick))) {
					var msg = nick != to ? match[3] : text;
					bot.out.log("omegle", nick + " in " + to + ": " + msg);
					request.post({url: self.chats[to].server + "send", form: {"id": self.chats[to].id, "msg": msg}});
				}
			}
		}
	}
}

module.exports = OmeglePlugin;
<|endoftext|>


<commit_before>const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
const fs = require("fs");

let uploadInProgress = false;
let uploadQueue = [];

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

class SpacesS3 extends LifeforcePlugin {
    constructor(restifyserver, logger, name) {
        super(restifyserver, logger, name);
        this.apiMap = [
            {
                path: "/api/spaces/upload",
                type: "post",
                handler: handleSpacesUpload
            },
            {
                path: "/api/youtube/download/:videoid",
                type: "get",
                handler: handleYoutubeDownload
            },
            {
                path: "/repcast/spaces/getfiles/:authkey",
                type: "get",
                handler: handleGetSpacesFileList

            },
            {
                path: "/repcast/youtube/:videoid",
                type: "get",
                handler: handleYoutubeDownload
            },
        ];

        const AWS = require('aws-sdk');
        this.s3 = require("s3");

        const spacesEndpoint = new AWS.Endpoint(this.config.digitalocean.endpoint);
        this.s3auth = new AWS.S3({
            endpoint: spacesEndpoint,
            accessKeyId: this.config.digitalocean.accessKey,
            secretAccessKey: this.config.digitalocean.secretKey
        });

        this.doclient = this.s3.createClient({
            s3Options: {
                accessKeyId: this.config.digitalocean.accessKey,
                secretAccessKey: this.config.digitalocean.secretKey,
                endpoint: "https://" + this.config.digitalocean.endpoint
            }
        });

        this.youtubedl = require('youtube-dl');
    }

    uploadItem(localPath, remotePath) {
        let that = this;
        return new Promise((resolve, reject) => {
            var params = {
                localFile: localPath,

                s3Params: {
                    Bucket: "repcast",
                    Key: remotePath
                },
            };

            var uploader = that.doclient.uploadFile(params);

            uploader.on('error', function (err) {
                reject(err.message);
            });

            uploader.on('end', function () {
                resolve();
            });
        });
    }

    uploadDirectory() {
        let that = this;
        return new Promise((resolve, reject) => {
            if (!uploadInProgress) {
                uploadInProgress = true;
                var params = {
                    localDir: that.config.syncmount,

                    s3Params: {
                        Bucket: "repcast",
                        Prefix: "repcast/"
                    },
                };

                var uploader = that.doclient.uploadDir(params);

                uploader.on('error', function (err) {
                    uploadInProgress = false;
                    reject(err.message);
                });

                uploader.on('end', function () {
                    uploadInProgress = false;
                    resolve();
                });
            } else {
                that.log.info("Skipping uploadDirectory call as a sync is already in progress");
                resolve();
            }
        });
    }

    listItems(prefix) {
        var that = this;
        return new Promise((resolve, reject) => {
            var list = this.doclient.listObjects({
                s3Params: {
                    Prefix: prefix,
                    Bucket: "repcast"
                }
            });

            list.on('error', function (err) {
                reject(err.message);
            });

            var itemlist = [];
            list.on("data", function (data) {
                data.Contents.map((item) => {
                    itemlist.push(item);
                });
            });

            list.on('end', function () {
                let filelist = [];
                // Remove all the directories from the structure
                itemlist = itemlist.filter((item) => {
                    if (item.Size > 0) {
                        return true;
                    } else {
                        return false;
                    }
                });

                itemlist = itemlist.map((file) => {
                    var hashString = file.ETag;
                    if (hashString.charAt(0) === '"' && hashString.charAt(hashString.length - 1) === '"') {
                        hashString = (hashString.substr(1, hashString.length - 2));
                    }

                    const expireSeconds = 172800;

                    const urlpath = that.s3auth.getSignedUrl('getObject', {
                        Bucket: 'repcast',
                        Key: file.Key,
                        Expires: expireSeconds
                    });

                    // Get the file type
                    let filetype = file.Key.split('.').pop();

                    // Improve the names and paths
                    let nameParts = file.Key.split("/");
                    let namePath = "";

                    if (nameParts.length > 2) {
                        namePath = nameParts[1] + "/";
                    }

                    let name = namePath + nameParts.pop();

                    // Convert the name to something nicer looking
                    let removesstring = ["720p", "x264", "AAC", "ETRG", "BRRip", "WEB-DL", "H264", "AC3", "EVO",
                        "rarbg", "HDTV", "W4F", "hdtv", "w4f", "ETRG", "YIFY", "1080p", "BluRay", "DVDRip"];

                    removesstring.map((rmstr) => {
                        name = name.replaceAll("." + rmstr, "");
                        name = name.replaceAll("-" + rmstr, "");
                        name = name.replaceAll(rmstr.toUpperCase(), "");
                        name = name.replaceAll(rmstr.toLowerCase(), "");
                        name = name.replaceAll(rmstr, "");
                    });

                    let filestruct = {
                        size: file.Size,
                        name: name,
                        original: file.Key,
                        path: urlpath,
                        hash: hashString,
                        type: filetype,
                        thumb: "https://repkam09.com/img/file.png"
                    };

                    // Check for invalid file types
                    var invalid = ["txt", "nfo", "srt", "jpg", "png", "jpeg", "sfv", "ico", "PNG", "sh", "tmp"];
                    if (invalid.indexOf(filestruct.type) < 0) {
                        filelist.push(filestruct);
                    }

                });

                resolve(filelist);
            });
        });
    }
}

function handleSpacesUpload(req, res, next) {
    if (req.files) {
        var data = req.files.filedata;
        var path = data.path;

        this.uploadItem(path, "personal/" + data.name).then(() => {
            // Delete the temp file
            console.log("temp file for s3 upload: " + path);
            // Respond to the client that upload completed
            res.send(200, { upload: true });
        }).catch((error) => {
            res.send(400, { filename: false });
        });
    } else {
        res.send(400, { filename: false });
    }

    next();
}

function handleYoutubeDownload(req, res, next) {
    if (req.params.videoid) {
        var filepath = "./temp/yt_dl_" + req.params.videoid + ".mp4";
        var videoinfo = null;
        var video = this.youtubedl('http://www.youtube.com/watch?v=' + req.params.videoid,
            [],
            { cwd: __dirname });

        // Will be called when the download starts.
        video.on('info', (info) => {
            videoinfo = info;
            res.send(200, { error: false, info });
        });

        video.on('end', (res) => {
            this.log.info("Video download finished, starting upload to Spaces...");
            // Rename the video to something better...
            var newFilePath = "./temp/" + videoinfo.filename;
            move(filepath, newFilePath).then((result) => {
                var spacesName = "repcast/yt_dl_" + videoinfo.filename
                this.log.info("Upload as " + spacesName);
                this.uploadItem(newFilePath, spacesName).then(() => {
                    this.log.info("Video upload to Spaces finished!");
                    fs.unlink(newFilePath, () => {
                        this.log.info("Deleted temp local video file");
                    });
                }).catch((error) => {
                    this.log.info("Video upload to Spaces failed!");
                });
            });
        });

        video.pipe(fs.createWriteStream(filepath));
    } else {
        res.send(400, { error: "bad request" });
    }
    next();
}

function move(oldPath, newPath) {
    function copy() {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', (err) => {
            reject(err);
        });

        writeStream.on('error', (err) => {
            reject(err);
        });

        readStream.on('close', function () {
            fs.unlink(oldPath, callback);
            resolve();
        });

        readStream.pipe(writeStream);
    }

    return new Promise((resolve, reject) => {
        fs.rename(oldPath, newPath, function (err) {
            if (err) {
                if (err.code === 'EXDEV') {
                    copy();
                } else {
                    reject(err);
                }
                return;
            }
            resolve();
        });
    });

}

function handleGetSpacesFileList(req, res, next) {
    if (req.params.authkey === this.config.digitalocean.accessKey) {

        this.listItems("repcast/").then((items) => {
            // Create an object to return
            const response = { error: false, count: items.length, info: items };

            res.send(200, response);
            next();
        }).catch((error) => {
            res.send(500, { error: true, info: [], count: 0 });
        });
    } else {
        res.send(401, "Unauthorized");
    }
}

function handleSyncMediaFiles(req, res, next) {
    this.uploadDirectory().then(() => {
        this.log.info("Finished uploading files!");
    }).catch((error) => {
        this.log.info("Error while uploading files!");
    });

    res.send(200, { error: false, info: "upload started" });
}

module.exports = SpacesS3;
<commit_msg>Remove requirement for authkey<commit_after>const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
const fs = require("fs");

let uploadInProgress = false;
let uploadQueue = [];

String.prototype.replaceAll = function (search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

class SpacesS3 extends LifeforcePlugin {
    constructor(restifyserver, logger, name) {
        super(restifyserver, logger, name);
        this.apiMap = [
            {
                path: "/api/spaces/upload",
                type: "post",
                handler: handleSpacesUpload
            },
            {
                path: "/api/youtube/download/:videoid",
                type: "get",
                handler: handleYoutubeDownload
            },
            {
                path: "/repcast/spaces/getfiles",
                type: "get",
                handler: handleGetSpacesFileList

            },
            {
                path: "/repcast/youtube/:videoid",
                type: "get",
                handler: handleYoutubeDownload
            },
        ];

        const AWS = require('aws-sdk');
        this.s3 = require("s3");

        const spacesEndpoint = new AWS.Endpoint(this.config.digitalocean.endpoint);
        this.s3auth = new AWS.S3({
            endpoint: spacesEndpoint,
            accessKeyId: this.config.digitalocean.accessKey,
            secretAccessKey: this.config.digitalocean.secretKey
        });

        this.doclient = this.s3.createClient({
            s3Options: {
                accessKeyId: this.config.digitalocean.accessKey,
                secretAccessKey: this.config.digitalocean.secretKey,
                endpoint: "https://" + this.config.digitalocean.endpoint
            }
        });

        this.youtubedl = require('youtube-dl');
    }

    uploadItem(localPath, remotePath) {
        let that = this;
        return new Promise((resolve, reject) => {
            var params = {
                localFile: localPath,

                s3Params: {
                    Bucket: "repcast",
                    Key: remotePath
                },
            };

            var uploader = that.doclient.uploadFile(params);

            uploader.on('error', function (err) {
                reject(err.message);
            });

            uploader.on('end', function () {
                resolve();
            });
        });
    }

    uploadDirectory() {
        let that = this;
        return new Promise((resolve, reject) => {
            if (!uploadInProgress) {
                uploadInProgress = true;
                var params = {
                    localDir: that.config.syncmount,

                    s3Params: {
                        Bucket: "repcast",
                        Prefix: "repcast/"
                    },
                };

                var uploader = that.doclient.uploadDir(params);

                uploader.on('error', function (err) {
                    uploadInProgress = false;
                    reject(err.message);
                });

                uploader.on('end', function () {
                    uploadInProgress = false;
                    resolve();
                });
            } else {
                that.log.info("Skipping uploadDirectory call as a sync is already in progress");
                resolve();
            }
        });
    }

    listItems(prefix) {
        var that = this;
        return new Promise((resolve, reject) => {
            var list = this.doclient.listObjects({
                s3Params: {
                    Prefix: prefix,
                    Bucket: "repcast"
                }
            });

            list.on('error', function (err) {
                reject(err.message);
            });

            var itemlist = [];
            list.on("data", function (data) {
                data.Contents.map((item) => {
                    itemlist.push(item);
                });
            });

            list.on('end', function () {
                let filelist = [];
                // Remove all the directories from the structure
                itemlist = itemlist.filter((item) => {
                    if (item.Size > 0) {
                        return true;
                    } else {
                        return false;
                    }
                });

                itemlist = itemlist.map((file) => {
                    var hashString = file.ETag;
                    if (hashString.charAt(0) === '"' && hashString.charAt(hashString.length - 1) === '"') {
                        hashString = (hashString.substr(1, hashString.length - 2));
                    }

                    const expireSeconds = 172800;

                    const urlpath = that.s3auth.getSignedUrl('getObject', {
                        Bucket: 'repcast',
                        Key: file.Key,
                        Expires: expireSeconds
                    });

                    // Get the file type
                    let filetype = file.Key.split('.').pop();

                    // Improve the names and paths
                    let nameParts = file.Key.split("/");
                    let namePath = "";

                    if (nameParts.length > 2) {
                        namePath = nameParts[1] + "/";
                    }

                    let name = namePath + nameParts.pop();

                    // Convert the name to something nicer looking
                    let removesstring = ["720p", "x264", "AAC", "ETRG", "BRRip", "WEB-DL", "H264", "AC3", "EVO",
                        "rarbg", "HDTV", "W4F", "hdtv", "w4f", "ETRG", "YIFY", "1080p", "BluRay", "DVDRip"];

                    removesstring.map((rmstr) => {
                        name = name.replaceAll("." + rmstr, "");
                        name = name.replaceAll("-" + rmstr, "");
                        name = name.replaceAll(rmstr.toUpperCase(), "");
                        name = name.replaceAll(rmstr.toLowerCase(), "");
                        name = name.replaceAll(rmstr, "");
                    });

                    let filestruct = {
                        size: file.Size,
                        name: name,
                        original: file.Key,
                        path: urlpath,
                        hash: hashString,
                        type: filetype,
                        thumb: "https://repkam09.com/img/file.png"
                    };

                    // Check for invalid file types
                    var invalid = ["txt", "nfo", "srt", "jpg", "png", "jpeg", "sfv", "ico", "PNG", "sh", "tmp"];
                    if (invalid.indexOf(filestruct.type) < 0) {
                        filelist.push(filestruct);
                    }

                });

                resolve(filelist);
            });
        });
    }
}

function handleSpacesUpload(req, res, next) {
    if (req.files) {
        var data = req.files.filedata;
        var path = data.path;

        this.uploadItem(path, "personal/" + data.name).then(() => {
            // Delete the temp file
            console.log("temp file for s3 upload: " + path);
            // Respond to the client that upload completed
            res.send(200, { upload: true });
        }).catch((error) => {
            res.send(400, { filename: false });
        });
    } else {
        res.send(400, { filename: false });
    }

    next();
}

function handleYoutubeDownload(req, res, next) {
    if (req.params.videoid) {
        var filepath = "./temp/yt_dl_" + req.params.videoid + ".mp4";
        var videoinfo = null;
        var video = this.youtubedl('http://www.youtube.com/watch?v=' + req.params.videoid,
            [],
            { cwd: __dirname });

        // Will be called when the download starts.
        video.on('info', (info) => {
            videoinfo = info;
            res.send(200, { error: false, info });
        });

        video.on('end', (res) => {
            this.log.info("Video download finished, starting upload to Spaces...");
            // Rename the video to something better...
            var newFilePath = "./temp/" + videoinfo.filename;
            move(filepath, newFilePath).then((result) => {
                var spacesName = "repcast/yt_dl_" + videoinfo.filename
                this.log.info("Upload as " + spacesName);
                this.uploadItem(newFilePath, spacesName).then(() => {
                    this.log.info("Video upload to Spaces finished!");
                    fs.unlink(newFilePath, () => {
                        this.log.info("Deleted temp local video file");
                    });
                }).catch((error) => {
                    this.log.info("Video upload to Spaces failed!");
                });
            });
        });

        video.pipe(fs.createWriteStream(filepath));
    } else {
        res.send(400, { error: "bad request" });
    }
    next();
}

function move(oldPath, newPath) {
    function copy() {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);

        readStream.on('error', (err) => {
            reject(err);
        });

        writeStream.on('error', (err) => {
            reject(err);
        });

        readStream.on('close', function () {
            fs.unlink(oldPath, callback);
            resolve();
        });

        readStream.pipe(writeStream);
    }

    return new Promise((resolve, reject) => {
        fs.rename(oldPath, newPath, function (err) {
            if (err) {
                if (err.code === 'EXDEV') {
                    copy();
                } else {
                    reject(err);
                }
                return;
            }
            resolve();
        });
    });

}

function handleGetSpacesFileList(req, res, next) {
    this.listItems("repcast/").then((items) => {
        // Create an object to return
        const response = { error: false, count: items.length, info: items };

        res.send(200, response);
        next();
    }).catch((error) => {
        res.send(500, { error: true, info: [], count: 0 });
    });
}

function handleSyncMediaFiles(req, res, next) {
    this.uploadDirectory().then(() => {
        this.log.info("Finished uploading files!");
    }).catch((error) => {
        this.log.info("Error while uploading files!");
    });

    res.send(200, { error: false, info: "upload started" });
}

module.exports = SpacesS3;
<|endoftext|>


<commit_before>// Alan Badillo Salas | badillo.soft@hotmail.com | @badillosoft
// JavaScript: cesar.js

/*
	El siguiente código extiende métodos de encriptación a cadenas.
	Se utiliza el Cifrado César el cual toma una cadena y un número k,
	luego desplaza k posiciones el caractér, si el caractér llega a 'z'
	entonces su siguiente es 'a'. Este algoritmo deja inmutables los carácteres
	no alfanuméricos y es sensible a minúsculas, mayúsculas y números.
*/

String.prototype.isNumber = function () {
	return this >= '0' && this <= '9';
};

String.prototype.isLowerCase = function () {
	return this >= 'a' && this <= 'z';
};

String.prototype.isUpperCase = function () {
	return this >= 'A' && this <= 'Z';
};

String.prototype.isSpecialCharacter = function () {
	return !(this.isNumber || this.isLowerCase || this.isUpperCase);
};

String.prototype.encode = function (k) {
	k = k || 0;

	k = k % 26;

	if (k < 0) k = 26 + k;

	var aux = this.split('');

	var enc = '';

	var lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
	var upperAlphabet = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase().split('');
	//var numbers = '01234567890123456789012345'.split('');

	aux.forEach(function (c) {
		enc = enc + (
			c.isLowerCase() ? lowerAlphabet[(lowerAlphabet.indexOf(c) + k) % 26] :
			(c.isUpperCase() ? upperAlphabet[(upperAlphabet.indexOf(c) + k) % 26] : c)
		);
	}, enc);

	return enc;
};

String.prototype.decode = function (k) {
	return this.encode(-k);
};<commit_msg>Arreglos en el código para verse más sencillo y un poco de optimización.<commit_after>// Alan Badillo Salas | badillo.soft@hotmail.com | @badillosoft
// JavaScript: cesar.js

/*
	El siguiente código extiende métodos de encriptación a cadenas.
	Se utiliza el Cifrado César el cual toma una cadena y un número k,
	luego desplaza k posiciones el caractér, si el caractér llega a 'z'
	entonces su siguiente es 'a'. Este algoritmo deja inmutables los carácteres
	no alfanuméricos y es sensible a minúsculas, mayúsculas y números.
*/

String.prototype.isNumber = function () {
	return this >= '0' && this <= '9';
};

String.prototype.isLowerCase = function () {
	return this >= 'a' && this <= 'z';
};

String.prototype.isUpperCase = function () {
	return this >= 'A' && this <= 'Z';
};

String.prototype.isSpecialCharacter = function () {
	return !(this.isNumber || this.isLowerCase || this.isUpperCase);
};

String.prototype.encode = function (k) {
	k = k % 26 || 0;

	if (k < 0) k += 26;

	var aux = this.split('');

	var enc = '';

	var lowerAlphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
	var upperAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');

	aux.forEach(function (c) {
		if (!c.isLowerCase() && !c.isUpperCase()) {
			enc += c;
			return;
		}

		var arr = c.isLowerCase() ? lowerAlphabet : upperAlphabet;

		enc += arr[(arr.indexOf(c) + k) % 26];
	}, enc);

	return enc;
};

String.prototype.decode = function (k) {
	return this.encode(-k);
};<|endoftext|>


<commit_before>
let environment = {
  plugins: [
    require("tailwindcss"),
    require("autoprefixer"),
    require("postcss-import"),
    require("postcss-flexbugs-fixes"),
    require("postcss-preset-env")({
      autoprefixer: {
        flexbox: "no-2009"
      },
      stage: 3
    })
  ]
}

// Only run PurgeCSS in production (you can also add staging here)
console.log("PURGECSS", process.env.NODE_ENV)
if (process.env.NODE_ENV === "production" || process.env.NODE_ENV === "staging") {
  environment.plugins.push(
    require("@fullhuman/postcss-purgecss")({
      content: [
        "./app/**/*.html.erb",
        "./app/**/*.html.slim",
        "./app/helpers/**/*.rb",
        "./app/inputs/**/*.rb",
        "./app/javascript/**/*.js",
        "./app/javascript/**/*.vue",
        "./app/javascript/**/*.jsx",
      ],
      defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || []
    })
  )
}

module.exports = environment
<commit_msg>Purce CSS in a UAT environment<commit_after>
let environment = {
  plugins: [
    require("tailwindcss"),
    require("autoprefixer"),
    require("postcss-import"),
    require("postcss-flexbugs-fixes"),
    require("postcss-preset-env")({
      autoprefixer: {
        flexbox: "no-2009"
      },
      stage: 3
    })
  ]
}

// Only run PurgeCSS in production (you can also add staging here)

if (["production", "staging", "uat"].indexOf(process.env.NODE_ENV) > -1) {
  console.log("PURGECSS", process.env.NODE_ENV)
  environment.plugins.push(
    require("@fullhuman/postcss-purgecss")({
      content: [
        "./app/**/*.html.erb",
        "./app/**/*.html.slim",
        "./app/helpers/**/*.rb",
        "./app/inputs/**/*.rb",
        "./app/javascript/**/*.js",
        "./app/javascript/**/*.vue",
        "./app/javascript/**/*.jsx",
      ],
      defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || []
    })
  )
}

module.exports = environment
<|endoftext|>


<commit_before>var fs = require('fs')
var file = 'contributors.json'

module.exports = function(stats, callback) {

  fs.readFile(file, function (err, data) {
    if (err) console.log(err)

    data = data.toString()

    if (data === "") var array = []
    else var array = JSON.parse(data)

    array.push(stats)
    writeFile(file, JSON.stringify(array, null, " "), callback)
  })
}

function writeFile(file, array, callback) {
  fs.writeFile(file, array, function (err) {
    if (err) console.log(err)
    console.log("Added" + stats.username + " to contributor file")
    callback()
  })
}
<commit_msg>fix write contributors file<commit_after>var fs = require('fs')
var file = 'contributors.json'

module.exports = function(stats, callback) {
  console.log("these are the stats", stats)

  fs.readFile(file, function (err, data) {
    if (err) console.log(err)

    var oldData = data.toString()

    if (oldData === "") var array = []
    else var array = JSON.parse(data)

    array.push(stats)
    writeFile(file, JSON.stringify(array, null, " "), callback)
  })
}

function writeFile(file, array, callback) {
  fs.writeFile(file, array, function (err) {
    if (err) console.log(err)
    console.log("Added" + array[0].username + " to contributor file")
    callback()
  })
}
<|endoftext|>