Registry.require(["promise","helper","xmlhttprequest","cloud","tools"],function(){var m=Registry.log,b=Registry.get("promise"),z=Registry.get("helper"),H=Registry.get("xmlhttprequest").run,A=Registry.get("cloud"),B=Registry.get("tools"),d=0,r={ePASTEBIN:1,eCHROMESYNC:2,eSYNCFS:3,eGDRIVE:4,eDROPBOX:5,eWEBDAV:6},y=[],v=!1,w=null,C=[{method:"HEAD",url:"https://www.google.com",extract:function(a,b){try{for(var e=b?b.split("\n"):[],d=0;d<e.length;d++){var c=e[d].split(":"),f=c.shift()||"",m=c.join(":")||
"";if("date"==f.trim().toLowerCase()&&m)return new Date(m)}}catch(r){}return null}},{method:"GET",url:"https://json-time.appspot.com/time.json",extract:function(a){try{var b=JSON.parse(a);if(!b.error&&b.datetime)return new Date(b.datetime)}catch(d){}return null}}],f=function(){var a=function(a){var c=a.type,e=a.id,h,f=function(p,a){if(a==d){var b=p.name,q=/.user.js$/;m.debug("si: cloud file changed",b,p);(b.match(/.meta.json$/)||b.match(q))&&y.forEach(function(l){l(b)})}},n={},t;return{init:function(a){h=
A[c]({path:"sync",url:a.url,basic_auth:a.basic_auth});return b.Pledge().then(function(){if(!h.credentials&&!a.basic_auth)return h.list()}).then(function(){t||(t=h.changes.listen(),t.progress(function(a){f(a,e)}));return!0})},list:function(a){return h.list(a).then(function(a){n={};var b={},p={},l,u,x=Date.now();a.forEach(function(g){n[g.name]=g;var a=/.meta.json$/,k=/.user.js$/;if(g.modified>x)m.debug("si: ignore future list item",x,g);else if((l=g.name.match(a))||(u=g.name.match(k)))l?(g.uuid=a=g.name.replace(a,
""),g.lastModified=g.modified,g.precision=g.precision,b[a]=g):u&&(a=g.name.replace(k,""),p[a]=g)});return Object.keys(b).map(function(g){var a;if(a=b[g])return a.source=p[g],a.options=a.options||{},a}).filter(function(a){return a})})},setSource:function(a,k){var c=a+".user.js",q=n[c],l;return b.Pledge(!1).then(function(){if(q&&h.compare)return h.compare(q,k)}).then(function(a){if(a)return m.debug("si: remote source data matches, skip upload of",c),b.Pledge();l=new Blob([k],{type:"text/plain"});return h.put(q||
c,l)})},getSource:function(a,k){var c=a+".user.js",q=n[c];if(q)return b.Pledge(!1).then(function(){if(k&&h.compare)return h.compare(q,k)}).then(function(a){return a?(m.debug("si: remote source data matches, skip download of",c),b.Pledge(k)):h.get(q).then(B.readAsText)});m.warn("si: list cache does not contain this UUID",a);return b.Breach()},getMeta:function(a){var k;return(k=n[a+".meta.json"])?h.get(k).then(B.readAsText).then(function(b){var c;var l=null;try{l=JSON.parse(b)}catch(u){}l&&l.uuid?b=
l:(m.debug("si: unable to parse extended info of undefined"),b=null);if((c=b)&&(c.uuid=a))return c.lastModified=k.modified||c.lastModified,c.precision=k.precision,c.options=c.options||{},c}):b.Breach()},setMeta:function(a,b){var c=new Blob([JSON.stringify(a)],{type:"text/plain"}),d=a.uuid+".meta.json";return h.put(n[d]||d,c,b)},remove:function(a){a.options.removed=Date.now()+w;var b=new Blob([JSON.stringify(a)],{type:"text/plain"});return h.put(a.uuid+".meta.json",b).then(function(){var b;if(b=n[a.uuid+
".user.js"])return h.delete(b)})},reset:function(){return h.list(!0).then(function(a){return a=a.filter(function(a){var b=/.user.js$/;return a.name.match(/.meta.json$/)||a.name.match(b)})}).then(function(a){var c=[];a.forEach(function(a){c.push(function(){var c=b();h.delete(a).always(function(){c.resolve()});return c.promise()}())});return b.when(c).always(function(){n={}})})},getRemoteUrl:function(a){if(h.getRemoteUrl)return h.getRemoteUrl(a.uuid+".user.js")},getRemoteDomains:function(){if(h.getRemoteDomains)return h.getRemoteDomains()}}},
f=a({type:"drive",id:r.eGDRIVE}),e=a({type:"dropbox",id:r.eDROPBOX}),a=a({type:"webdav",id:r.eWEBDAV}),t=function(){var a=!1,c,n=function(a,u){d==r.eCHROMESYNC&&"sync"==u&&b.Pledge().then(function(){if(null===w)return D()}).then(function(){var b=new RegExp(c+"$");a&&Object.keys(a).forEach(function(g){var c=a[g];m.debug('si: storage key "%s" in namespace "%s" changed. Old value was "%s", new value is "%s".',g,u,c.oldValue,c.newValue);if(-1!=g.search(b))for(var d=0;d<y.length;d++)if(!k[g]){var e=f(c.newValue,
g);if(e)y[d](g,e)}})})},h=function(a){var c=b(),x=[];a?e().done(function(b){x=z.select(b,function(c){return c.item&&c.item.uuis==a});c.resolve(x)}).fail(function(a){c.reject(a)}):c.resolve(x);return c.promise()},e=function(){return E(function(){var a=b(),u=new RegExp(c+"$");rea.storage.sync.get(null,function(c){var b=[];c&&Object.keys(c).forEach(function(a){-1!=a.search(u)&&b.push({key:a,item:f(c[a],a)})});a.resolve(b)});return a.promise()})},f=function(a,c){var b=null;try{b=JSON.parse(a)}catch(g){}return b&&
(b.url||b.options)?b:(m.debug("si: unable to parse extended info of "+c),null)},t=function(a){return a.then(function(a){var c={};a=z.select(a,function(a,b){if(!c[a.key])return c[a.key]=!0});if(1<a.length){var g=b(),l=[],d=a.pop();a.forEach(function(a){l.push(v(a.key))});b.when(l).done(function(){g.resolve(d)});return g.promise()}return b.Pledge(a[0])})},p=null,k={},v=function(a,c){var d=b();rea.storage.sync.remove(a,function(a){(a=rea.runtime.lastError)?d.reject(a):d.resolve()});return d.promise()},
q=function(a){var c=b();rea.storage.sync.set(k,function(a){(a=rea.runtime.lastError)?c.reject(a):(k={},c.resolve())});return c.promise()};return{init:function(){var d=!0;if(!a)try{rea.storage.onChanged.addListener(n),a=!0}catch(e){m.warn("si: error registering sync callback: "+e.message),d=!1}c="@v2";return b.Pledge(d)},list:function(){return b.Pledge().then(function(){if(null===w)return D()}).then(function(){return e()}).then(function(a){var d=new RegExp(c+"$"),e=[];a.forEach(function(a){var c=a.key,
b=a.item;a=c.replace(d,"");var l=null;if(l=k[c]?f(k[c],c):b)c=l.options||{},b=!!c.removed,e.push({id:a,uuid:b?a:l.uuid,lastModified:b?c.removed:l.lastModified,url:l.url,options:c})});return b.Pledge(e)})},setMeta:function(a,d){var e=b();t(h(a.uuid)).done(function(b){var n;b?(n=b.key,b=b.item):(n=a.uuid+c,b={});b.url=a.url;b.options=a.options||{};b.uuid=a.uuid;d.lastModified&&(b.lastModified=d.lastModified);k[n]=JSON.stringify(b);p&&window.clearTimeout(p);p=window.setTimeout(q,3E3);e.resolve()});return e.promise()},
remove:function(a){var d=b();t(h(a.uuid)).done(function(b){var e;b?(e=b.key,b=b.item):(e=a.uuid+c,b={});b.options=b.options||{};b.options.removed=Date.now()+w;k[e]=JSON.stringify(b);p&&window.clearTimeout(p);p=window.setTimeout(q,3E3);d.resolve()});return d.promise()},reset:function(){return E(function(){var a=b();rea.storage.sync.clear(function(){k={};a.resolve()});return a.promise()})}}}(),c={};rea.storage.sync.supported&&(c[r.eCHROMESYNC]=t);c[r.eGDRIVE]=f;c[r.eDROPBOX]=e;c[r.eWEBDAV]=a;return c}(),
F=function(){var a=b(),d=0,e=function(){if(d<C.length){var b=C[d];H({method:b.method,url:b.url},{ondone:function(c){4==c.readyState&&200==c.status?(c=b.extract(c.responseText,c.responseHeaders),null===c?(d++,window.setTimeout(e,1)):a.resolve(c)):(d++,window.setTimeout(e,1))}})}else a.reject(void 0)};e();return a.promise()},D=function(){var a=b();F().done(function(a){w=a.getTime()-Date.now()}).fail(function(){w=0;m.log("si: time offset detection failed!")}).always(a.resolve);return a.promise()},E=
function(a,d){var e=b();void 0===d&&(d=3);var f=function(){if(v)window.setTimeout(f,500);else{v=!0;try{a().always(function(){v=!1}).done(function(){e.resolve.apply(this,arguments)}).fail(function(){0<--d?(m.log("si: some retries left, wait for",6E4,"ms"),window.setTimeout(f,6E4)):(m.warn("si: no retries left, skipping this sync request!"),e.reject("no retries left"))})}catch(b){m.warn(b),v=!1,e.reject(b)}}};f();return e.promise()},G={init:function(a,n){y=[];d=a;return f[d]?f[d].init(n).done(function(a){}):
b.Breach()},getUtc:F,debug:function(a){},addChangeListener:function(a){y.push(a)},getRemoteUrl:function(a){if(f[d]&&f[d].getRemoteUrl)return f[d].getRemoteUrl(a)},getRemoteDomains:function(){if(f[d]&&f[d].getRemoteDomains)return f[d].getRemoteDomains()},caps:function(){var a={};a.__defineGetter__("specialMeta",function(){return f[d]&&!!f[d].getMeta});a.__defineGetter__("syncsSource",function(){return f[d]&&!!f[d].getSource});return a}(),types:r};"list setMeta getMeta setSource getSource reset remove".split(" ").forEach(function(a){G[a]=
function(){return f[d]&&f[d][a]?f[d][a].apply(this,arguments):b.Pledge()}});Registry.register("syncinfo","5828",function(a){A.init(function(d){var e=b(),f=a.openAndWatch({url:d.url},function(a){a?e&&e.notify(a):e&&(e.reject("auth_failed"),e=null)});return{promise:e.promise(),close:function(){f.cancel()}}});return G})});
