diff --git a/app.manifest b/app.manifest index 5e5bbdb7..155e762a 100644 --- a/app.manifest +++ b/app.manifest @@ -1,5 +1,5 @@ CACHE MANIFEST -# Time: Wed Nov 25 2015 19:23:23 GMT+0300 (MSK) +# Time: Wed Nov 25 2015 19:47:36 GMT+0300 (MSK) CACHE: diff --git a/js/app.js b/js/app.js index a3c42303..0c5a16e9 100644 --- a/js/app.js +++ b/js/app.js @@ -18,9 +18,9 @@ else if(d.offset5?"[.."+e.result.length+"..]":e.result),console.log(dT(),"Rpc response",f)}r.deferred.resolve(e.result)}r.isAPI&&(this.connectionInited=!0)}delete this.sentMessages[p]}break;default:this.ackMessage(n),g&&g(e)}},{getNetworker:function(e,t,n,i){return new u(e,t,n,i)},setUpdatesProcessor:function(e){g=e},stopAll:m,startAll:p}}]),angular.module("izhukov.mtproto.wrapper",["izhukov.utils","izhukov.mtproto"]).factory("MtpApiManager",["Storage","MtpAuthorizer","MtpNetworkerFactory","MtpSingleInstanceService","AppRuntimeManager","ErrorService","qSync","$rootScope","$q","TelegramMeWebService",function(e,t,n,i,a,o,s,r,l,c){function d(e){_!==e&&(_=e,c.setAuthorized(_))}function u(t,n){var i=angular.extend({dcID:t},n);e.set({dc:t,user_auth:i}),d(!0),r.$broadcast("user_auth",i),w=t}function p(){for(var t=[],n=1;5>=n;n++)t.push("dc"+n+"_auth_key");return e.get.apply(e,t).then(function(n){for(var i=[],a=0;a=i.stopTime)return u(o)}else i.stopTime=f+1e3*(void 0!==i.timeout?i.timeout:10);i.waitTime=i.waitTime?Math.min(60,1.5*i.waitTime):1,setTimeout(function(){_(r)},1e3*i.waitTime)}else{var v=o.type.match(/^FLOOD_WAIT_(\d+)/)[1]||10;if(v>(i.timeout||60))return u(o);setTimeout(function(){_(r)},1e3*v)}})};return(s=i.dcID||w)?m(s,i).then(_,u):e.get("dc").then(function(e){m(s=e||2,i).then(_,u)}),c.promise}function h(){return e.get("user_auth").then(function(e){return d(e&&e.id>0||!1),e.id||0})}function f(){return w||!1}var _,v={},y={},b={},w=!1;return i.start(),e.get("dc").then(function(e){e&&(w=e)}),{getBaseDcID:f,getUserID:h,invokeApi:g,getNetworker:m,setUserAuth:u,logOut:p}}]).factory("MtpApiFileManager",["MtpApiManager","$q","qSync","FileManager","IdbFileStorage","TmpfsFileStorage","MemoryFileStorage","WebpManager",function(e,t,n,i,a,o,s,r){function l(e,n,i){void 0===w[e]&&(w[e]=[],k[e]=0);var a=w[e],o=t.defer();return a.push({cb:n,deferred:o,activeDelta:i}),setZeroTimeout(function(){c(e)}),o.promise}function c(e){var t=w[e],n="upload"==e?11:5;if(k[e]>=n||!t||!t.length)return!1;var i=t.shift(),a=i.activeDelta||1;k[e]+=a;$++;i.cb().then(function(t){k[e]-=a,c(e),i.deferred.resolve(t)},function(t){k[e]-=a,c(e),i.deferred.reject(t)})}function d(e){switch(e._){case"inputVideoFileLocation":return"video"+e.id+".mp4";case"inputDocumentFileLocation":var t=(e.file_name||"").split(".",2),n=t[1]||"";return e.sticker&&!r.isWebpSupported()&&(n+=".png"),t.length?t[0]+"_"+e.id+"."+n:"doc"+e.id;case"inputAudioFileLocation":return"audio"+e.id;default:e.volume_id||console.trace("Empty location",e);var n="jpg";return e.sticker&&(n=r.isWebpSupported()?"webp":"png"),e.volume_id+"_"+e.local_id+"_"+e.secret+"."+n}}function u(e){if(!e)return!1;var t=d(e);return b[t]||!1}function p(){return o.isAvailable()?o:a.isAvailable()?a:s}function m(e,t){var n=d(e);return v[n]||(v[n]=p().saveFile(n,t).then(function(e){return b[n]=e},function(){delete v[n]})),v[n]}function g(a){if(!i.isAvailable())return t.reject({type:"BROWSER_BLOB_NOT_SUPPORTED"});var o=d(a),s=a.sticker?"image/webp":"image/jpeg",c=v[o]||y[o];if(c)return c;var u=p();return y[o]=u.getFile(o).then(function(e){return b[o]=e},function(){var t=l(a.dc_id,function(){var t=a;return t._&&"fileLocation"!=t._||(t=angular.extend({},a,{_:"inputFileLocation"})),e.invokeApi("upload.getFile",{location:t,offset:0,limit:1048576},{dcID:a.dc_id,fileDownload:!0,createNetworker:!0,noErrorBox:!0})}),c=function(e){return!a.sticker||r.isWebpSupported()?n.when(e):r.getPngBlobFromWebp(e)};return u.getFileWriter(o,s).then(function(e){return t.then(function(t){return c(t.bytes).then(function(t){return i.write(e,t).then(function(){return b[o]=e.finalize()})})})})})}function h(e,t){var n=p(),i=d(e);return n.getFile(i,t)}function f(a,o,s,c){if(!i.isAvailable())return t.reject({type:"BROWSER_BLOB_NOT_SUPPORTED"});c=c||{};var u=!1;o.sticker&&!r.isWebpSupported()&&(c.toFileEntry||s>524288?delete o.sticker:(u=!0,c.mime="image/png"));var m=d(o),g=c.toFileEntry||null,h=v[m]||y[m],f=p();if(h)return g?h.then(function(e){return i.copy(e,g)}):h;var _,w=t.defer(),k=!1,$=!1,S=c.mime||"image/jpeg",C=function(e){w.reject(e),C=angular.noop,!_||e&&"DOWNLOAD_CANCELED"==e.type||_.truncate(0)};return f.getFile(m,s).then(function(e){g?i.copy(e,g).then(function(){w.resolve()},C):w.resolve(b[m]=e)},function(){var c=g?i.getFileWriter(g):f.getFileWriter(m,S),d=function(e){return u?r.getPngBlobFromWebp(e):n.when(e)};c.then(function(n){_=n;var r,c,u=524288,p=0,h=t.when();if(n.length){if(p=n.length,p>=s)return void(g?w.resolve():w.resolve(b[m]=n.finalize()));n.seek(p),w.notify({done:p,total:s})}for(r=p;s>r;r+=u)c=t.defer(),function(r,c,p,h){return l(a,function(){return k?t.when():e.invokeApi("upload.getFile",{location:o,offset:c,limit:u},{dcID:a,fileDownload:!0,singleInRequest:void 0!==window.safari,createNetworker:!0})},2).then(function(e){h.then(function(){return k?t.when():d(e.bytes).then(function(e){return i.write(n,e).then(function(){p.resolve()},C).then(function(){r?($=!0,g?w.resolve():w.resolve(b[m]=n.finalize())):w.notify({done:c+u,total:s})})})})})}(r+u>=s,r,c,h),h=c.promise})}),w.promise.cancel=function(){k||$||(k=!0,delete y[m],C({type:"DOWNLOAD_CANCELED"}))},g||(y[m]=w.promise),w.promise}function _(n){var i=n.size,a=i>=10485760,o=!1,s=!1,r=0,c=262144,d=2;i>67108864?(c=524288,d=4):102400>i&&(c=32768,d=1);var u=Math.ceil(i/c);if(u>3e3)return t.reject({type:"FILE_TOO_BIG"});var p,m=[nextRandomInt(4294967295),nextRandomInt(4294967295)],g=t.defer(),h=function(e){g.reject(e),o=!0,h=angular.noop},f=0,_={_:a?"inputFileBig":"inputFile",id:m,parts:u,name:n.name,md5_checksum:""};for(p=0;i>p;p+=c)!function(p,f){l("upload",function(){var l=t.defer(),d=new FileReader,v=n.slice(p,p+c);return d.onloadend=function(t){return o?void l.reject():void(t.target.readyState==FileReader.DONE&&e.invokeApi(a?"upload.saveBigFilePart":"upload.saveFilePart",{file_id:m,file_part:f,file_total_parts:u,bytes:t.target.result},{startMaxLength:c+256,fileUpload:!0,singleInRequest:!0}).then(function(){r++,l.resolve(),r>=u?(g.resolve(_),s=!0):(console.log(dT(),"Progress",r*c/i),g.notify({done:r*c,total:i}))},h))},d.readAsArrayBuffer(v),l.promise},d)}(p,f++);return g.promise.cancel=function(){console.log("cancel upload",o,s),o||s||(o=!0,h({type:"UPLOAD_CANCELED"}))},g.promise}var v={},y={},b={},w={},k={},$=0;return{getCachedFile:u,getDownloadedFile:h,downloadFile:f,downloadSmallFile:g,saveSmallFile:m,uploadFile:_}}]).service("MtpSingleInstanceService",["_","$rootScope","$compile","$timeout","$interval","$modalStack","Storage","AppRuntimeManager","IdleManager","ErrorService","MtpNetworkerFactory",function(e,t,n,i,a,o,s,r,l,c,d){function u(){if(!f&&!Config.Navigator.mobile&&!Config.Modes.packed){f=!0,l.start(),t.$watch("idle.isIDLE",g),a(g,5e3),g();try{$($window).on("beforeunload",p)}catch(e){}}}function p(){s.remove(_?"xt_instance":"xt_idle_instance")}function m(){if(_||y)return!1;console.log(dT(),"deactivate"),v=!1,y=!0,p(),o.dismissAll(),document.title=e("inactive_tab_title_raw");var i=n(""),a=t.$new(!0);a.close=function(){r.close()},a.reload=function(){r.reload()},i(a,function(e){$(".page_wrap").hide(),$(e).appendTo($("body"))}),t.idle.deactivated=!0}function g(){if(y)return!1;var e=tsNow(),n=t.idle&&t.idle.isIDLE,a={id:h,idle:n,time:e};s.get("xt_instance","xt_idle_instance").then(function(t){var o=t[0],r=t[1];!n||!o||o.id==h||o.time=1e3?void o.resolve(s):void this["continue"]()},t.onerror=function(e){console.log("phonebook error",e,e.type,e.message),o.reject(e)},o.promise}return{isAvailable:a,openPhonebookImport:o,getPhonebookContacts:s}}]).service("AppChatsManager",["$q","$rootScope","$modal","_","MtpApiFileManager","MtpApiManager","AppUsersManager","AppPhotosManager","RichTextProcessor",function(e,t,n,i,a,o,s,r,l){function c(e){angular.forEach(e,d)}function d(e){if(angular.isObject(e)){e.rTitle=l.wrapRichText(e.title,{noLinks:!0,noLinebreaks:!0})||i("chat_title_deleted");var n=SearchIndexManager.cleanSearchText(e.title||"").split(" "),a=n.shift(),o=n.pop();if(e.initials=a.charAt(0)+(o?o.charAt(0):a.charAt(1)),e.num=Math.abs(e.id>>1)%8+1,void 0===e.pFlags&&(e.pFlags={}),e.username){var s=SearchIndexManager.cleanUsername(e.username);M[s]=e.id}void 0===C[e.id]?C[e.id]=e:(safeReplaceObject(C[e.id],e),t.$broadcast("chat_update",e.id)),void 0!==E[e.id]&&safeReplaceObject(E[e.id],e&&e.photo&&e.photo.photo_small||{empty:!0})}}function u(e){return C[e]||{id:e,deleted:!0,access_hash:x[e]}}function p(e,t){if(void 0===C[e])return!1;var n=u(e);if("chatForbidden"==n._||"channelForbidden"==n._||n.pFlags.kicked||n.pFlags.left)return!1;if(n.pFlags.creator)return!0;switch(t){case"send":if("channel"==n._&&!n.pFlags.megagroup&&!n.pFlags.editor)return!1;break;case"edit_title":case"edit_photo":case"invite":if("channel"==n._){if(!n.pFlags.megagroup)return!1;if(!n.pFlags.editor)return!1}else if(n.pFlags.admins_enabled&&!n.pFlags.editor)return!1}return!0}function m(e){return M[e]||0}function g(e,t){x[e]=t}function h(e){A[e]=!0}function f(e){var t=C[e];return t&&("channel"==t._||"channelForbidden"==t._)||x[e]?!0:!1}function _(e){if(A[e])return!0;var t=C[e];return t&&"channel"==t._&&t.pFlags.megagroup?!0:!1}function v(e){return e||0}function y(e){return e?{_:"inputChannel",channel_id:e,access_hash:u(e).access_hash||x[e]||0}:{_:"inputChannelEmpty"}}function b(e){return angular.isObject(C[e])}function w(e){var t=u(e);return void 0===E[e]&&(E[e]=t&&t.photo&&t.photo.photo_small||{empty:!0}),{placeholder:"img/placeholders/GroupAvatar"+Math.ceil(t.num/2)+"@2x.png",location:E[e]}}function k(e){var t=u(e);return f(e)?(_(e)?"s":"c")+e+"_"+t.access_hash:"g"+e}function $(e,t){var n=angular.copy(t),i=u(e);if(n.participants&&"chatParticipants"==n.participants._&&o.getUserID().then(function(e){var t=i.pFlags.creator||i.pFlags.admins_enabled&&i.pFlags.admin;angular.forEach(n.participants.participants,function(n){n.canLeave=e==n.user_id,n.canKick=!n.canLeave&&(i.pFlags.creator||"chatParticipant"==n._&&(t||e==n.inviter_id)),n.user=s.getUser(n.user_id)})}),n.participants&&"channelParticipants"==n.participants._){var a=i.pFlags.creator||i.pFlags.editor||i.pFlags.moderator;angular.forEach(n.participants.participants,function(e){e.canLeave=!i.pFlags.creator&&"channelParticipantSelf"==e._,e.canKick=a&&"channelParticipant"==e._,e.user=s.getUser(e.user_id)})}return n.about&&(n.rAbout=l.wrapRichText(n.about,{noLinebreaks:!0})),n.peerString=k(e),n.chat=i,n}function S(e){var i=t.$new();if(i.chatID=e,f(e)){n.open({templateUrl:templateUrl("channel_modal"),controller:"ChannelModalController",scope:i,windowClass:"chat_modal_window channel_modal_window mobile_modal"})}else{n.open({templateUrl:templateUrl("chat_modal"),controller:"ChatModalController",scope:i,windowClass:"chat_modal_window mobile_modal"})}}var C={},M={},x={},A={},E={};return t.$on("apiUpdate",function(e,n){switch(n._){case"updateChannel":var i=n.channel_id;t.$broadcast("channel_settings",{channelID:i})}}),{saveApiChats:c,saveApiChat:d,getChat:u,isChannel:f,isMegagroup:_,hasRights:p,saveChannelAccess:g,saveIsMegagroup:h,getChatInput:v,getChannelInput:y,getChatPhoto:w,getChatString:k,resolveUsername:m,hasChat:b,wrapForFull:$,openChat:S}}]).service("AppPeersManager",["qSync","AppUsersManager","AppChatsManager","MtpApiManager",function(e,t,n,i){function a(e){var t=e.charAt(0),i=e.substr(1).split("_");return"u"==t?{_:"inputPeerUser",user_id:i[0],access_hash:i[1]}:"c"==t||"s"==t?(n.saveChannelAccess(i[0],i[1]),"s"==t&&n.saveIsMegagroup(i[0]),{_:"inputPeerChannel",channel_id:i[0],access_hash:i[1]||0}):{_:"inputPeerChat",chat_id:i[0]}}function o(e){if(!e)return{_:"inputPeerEmpty"};if(0>e){var i=-e;return n.isChannel(i)?{_:"inputPeerChannel",channel_id:i,access_hash:n.getChat(i).access_hash||0}:{_:"inputPeerChat",chat_id:i}}return{_:"inputPeerUser",user_id:e,access_hash:t.getUser(e).access_hash||0}}function s(e){var i;if(e>0)i="%pu "+t.getUserSearchText(e);else if(0>e){var a=n.getChat(-e);i="%pg "+(a.title||"")}return i}function r(e){return e>0?t.getUserString(e):n.getChatString(-e)}function l(e){if(e>0)return{_:"peerUser",user_id:e};var t=-e;return n.isChannel(t)?{_:"peerChannel",channel_id:t}:{_:"peerChat",chat_id:t}}function c(a){var o,s,r,l=SearchIndexManager.cleanUsername(a);return(o=t.resolveUsername(l))&&(r=t.getUser(o).username,SearchIndexManager.cleanUsername(r)==l)?e.when(o):(s=n.resolveUsername(l))&&(r=n.getChat(s).username,SearchIndexManager.cleanUsername(r)==l)?e.when(-s):i.invokeApi("contacts.resolveUsername",{username:a}).then(function(e){return t.saveApiUsers(e.users),n.saveApiChats(e.chats),d(e.peer)})}function d(e){if(angular.isObject(e))return e.user_id?e.user_id:-(e.channel_id||e.chat_id);var t="u"==e.charAt(0),n=e.substr(1).split("_");return t?n[0]:-n[0]||0}function u(e){return e>0?t.getUser(e):n.getChat(-e)}function p(e){return e>0?t.getUserPhoto(e):n.getChatPhoto(-e)}function m(e){return 0>e&&n.isChannel(-e)}function g(e){return 0>e&&n.isMegagroup(-e)}function h(e){return e>0&&t.isBot(e)}return{getInputPeer:a,getInputPeerByID:o,getPeerSearchText:s,getPeerString:r,getOutputPeer:l,getPeerID:d,getPeer:u,getPeerPhoto:p,resolveUsername:c,isChannel:m,isMegagroup:g,isBot:h}}]).service("AppProfileManager",["$q","$rootScope","AppUsersManager","AppChatsManager","AppPeersManager","AppPhotosManager","NotificationsManager","MtpApiManager","ApiUpdatesManager","RichTextProcessor",function(e,t,n,i,a,o,s,r,l,c){function d(e){var t=e&&e.user_id;if(!t)return!1;var n={};return angular.forEach(e.commands,function(e){n[e.command]=e.description}),_[t]={id:t,version:e.version,shareText:e.share_text,description:e.description,rAbout:c.wrapRichText(e.share_text,{noLinebreaks:!0}),commands:n}}function u(e,t){return r.invokeApi("users.getFullUser",{id:n.getUserInput(e)}).then(function(i){return t&&t.phone_number?(i.user.phone=t.phone_number,(t.first_name||t.last_name)&&(i.user.first_name=t.first_name,i.user.last_name=t.last_name),n.saveApiUser(i.user)):n.saveApiUser(i.user,!0),o.savePhoto(i.profile_photo,{user_id:e}),s.savePeerSettings(e,i.notify_settings),i.bot_info=d(i.bot_info),i})}function p(t){var i=[];return t>=0&&!n.isBot(t)||a.isChannel(t)&&!a.isMegagroup(t)?e.when(i):t>=0?u(t).then(function(e){var t=e.bot_info;return t&&"botInfoEmpty"!=t._&&i.push(t),i}):m(-t).then(function(e){return angular.forEach(e.bot_info,function(e){i.push(d(e))}),i})}function m(a){if(i.isChannel(a))return f(a);if(void 0!==v[a]){var l=i.getChat(a);if(l.version==v[a].participants.version||l.pFlags.left)return e.when(v[a])}return void 0!==y[a]?y[a]:y[a]=r.invokeApi("messages.getFullChat",{chat_id:i.getChatInput(a)}).then(function(e){i.saveApiChats(e.chats),n.saveApiUsers(e.users);var r=e.full_chat;return r&&r.chat_photo.id&&o.savePhoto(r.chat_photo),s.savePeerSettings(-a,r.notify_settings),delete y[a],v[a]=r,t.$broadcast("chat_full_update",a),r})}function g(e,t){return m(e).then(function(n){if(!t&&n.exported_invite&&"chatInviteExported"==n.exported_invite._)return n.exported_invite.link;var a;return a=i.isChannel(e)?r.invokeApi("channels.exportInvite",{channel:i.getChannelInput(e)}):r.invokeApi("messages.exportChatInvite",{chat_id:i.getChatInput(e)}),a.then(function(t){return void 0!==v[e]&&(v[e].exported_invite=t),t.link})})}function h(e){return r.invokeApi("channels.getParticipants",{channel:i.getChannelInput(e),filter:{_:"channelParticipantsRecent"},offset:0,limit:i.isMegagroup(e)?50:200}).then(function(t){n.saveApiUsers(t.users);var a=t.participants,o=i.getChat(e);if(!o.pFlags.kicked&&!o.pFlags.left){for(var s,r=n.getSelf().id,l=!1,c=0,d=a.length;d>c;c++)if(a[c].user_id==r){l=c;break}l!==!1?(s=a[c],a.splice(c,1)):s={_:"channelParticipantSelf",user_id:r},a.unshift(s)}return a})}function f(a,c){return void 0===v[a]||c?void 0!==y[a]?y[a]:y[a]=r.invokeApi("channels.getFullChannel",{channel:i.getChannelInput(a)}).then(function(r){i.saveApiChats(r.chats),n.saveApiUsers(r.users);{var l=r.full_chat;i.getChat(a)}l&&l.chat_photo.id&&o.savePhoto(l.chat_photo),s.savePeerSettings(-a,l.notify_settings);var c;return c=8&l.flags?h(a).then(function(e){delete y[a],l.participants={_:"channelParticipants",participants:e}},function(e){e.handled=!0}):e.when(),c.then(function(){return delete y[a],v[a]=l,t.$broadcast("chat_full_update",a),l})},function(e){switch(e.type){case"CHANNEL_PRIVATE":var t=i.getChat(a);t={_:"channelForbidden",access_hash:t.access_hash,title:t.title},l.processUpdateMessage({_:"updates",updates:[{_:"updateChannel",channel_id:a}],chats:[t],users:[]})}}):e.when(v[a])}var _={},v={},y={};return t.$on("apiUpdate",function(e,n){switch(n._){case"updateChatParticipants":var i=n.participants,a=v[i.id];void 0!==a&&(a.participants=n.participants,t.$broadcast("chat_full_update",chatID));break;case"updateChatParticipantAdd":var a=v[n.chat_id];if(void 0!==a){for(var i=a.participants.participants||[],o=0,s=i.length;s>o;o++)if(i[o].user_id==n.user_id)return;i.push({_:"chatParticipant",user_id:n.user_id,inviter_id:n.inviter_id,date:tsNow(!0)}),a.participants.version=n.version,t.$broadcast("chat_full_update",n.chat_id)}break;case"updateChatParticipantDelete":var a=v[n.chat_id];if(void 0!==a)for(var i=a.participants.participants||[],o=0,s=i.length;s>o;o++)if(i[o].user_id==n.user_id)return i.splice(o,1),a.participants.version=n.version,void t.$broadcast("chat_full_update",n.chat_id)}}),t.$on("chat_update",function(e,n){var a=v[n],s=i.getChat(n);if(s.photo&&a){var r="chatPhotoEmpty"==s.photo;if(r!=("photoEmpty"==a.chat_photo._))return delete v[n],void t.$broadcast("chat_full_update",n);if(!r){var l=s.photo.photo_small,c=o.choosePhotoSize(a.chat_photo,0,0);angular.equals(l,c.location)||(delete v[n],t.$broadcast("chat_full_update",n))}}}),{getPeerBots:p,getProfile:u,getChatInviteLink:g,getChatFull:m,getChannelFull:f}}]).service("AppPhotosManager",["$modal","$window","$rootScope","MtpApiManager","MtpApiFileManager","AppUsersManager","FileManager",function(e,t,n,i,a,o,s){function r(e,t){t&&angular.extend(e,t),f[e.id]=e,angular.forEach(e.sizes,function(e){"photoCachedSize"==e._&&(a.saveSmallFile(e.location,e.bytes),e.size=e.bytes.length,delete e.bytes,e._="photoSize")})}function l(e,t,n){Config.Navigator.retina&&(t*=2,n*=2);var i={_:"photoSizeEmpty"},a=16777215;return angular.forEach(e.sizes,function(e){var o=Math.abs(e.w*e.h-t*n);a>o&&(i=e,a=o)}),i}function c(e,t,n){var a=o.getUserInput(e);return i.invokeApi("photos.getUserPhotos",{user_id:a,offset:0,limit:n||20,max_id:t||0}).then(function(t){o.saveApiUsers(t.users);for(var n=[],i={user_id:e},a=0;a800&&(i-=208);var s=l(n,i,o);s&&!s.preloaded&&(s.preloaded=!0,s.size?a.downloadFile(s.location.dc_id,{_:"inputFileLocation",volume_id:s.location.volume_id,local_id:s.location.local_id,secret:s.location.secret},s.size):a.downloadSmallFile(s.location))}}function u(e){return f[e]||{_:"photoEmpty"}}function p(e,t){t=t||{};var n=angular.copy(f[e])||{_:"photoEmpty"},i=t.website?100:Math.min(_-80,Config.Mobile?210:260),a=t.website?100:Math.min(v-100,Config.Mobile?210:260),o=l(n,i,a),s={placeholder:"img/placeholders/PhotoThumbConversation.gif",width:i,height:a}; if(t.website&&Config.Mobile&&(i=50,a=50),o&&"photoSizeEmpty"!=o._){var r=calcImageInBox(o.w,o.h,i,a);s.width=r.w,s.height=r.h,s.location=o.location,s.size=o.size}else s.width=100,s.height=100;return n.thumb=s,n}function m(e){var n=p(e),i=$(window).width()-(Config.Mobile?0:32),a=$(t).height()-(Config.Mobile?0:116);!Config.Mobile&&i>800&&(i-=208);var o=l(n,i,a),s={placeholder:"img/placeholders/PhotoThumbModal.gif"};if(s.width=i,s.height=a,o&&"photoSizeEmpty"!=o._){var r=calcImageInBox(o.w,o.h,i,a,!0);s.width=r.w,s.height=r.h,s.modalWidth=Math.max(s.width,Math.min(400,i)),s.location=o.location,s.size=o.size}return n.full=s,n}function g(t,i){if(!t||"0"===t)return!1;var a=n.$new(!0);a.photoID=t;var o="PhotoModalController";i&&i.p>0?(o="UserpicModalController",a.userID=i.p):i&&i.p<0?(o="ChatpicModalController",a.chatID=-i.p):i&&i.m>0&&(a.messageID=i.m,i.w&&(a.webpageID=i.w));e.open({templateUrl:templateUrl("photo_modal"),windowTemplateUrl:templateUrl("media_modal_layout"),controller:o,scope:a,windowClass:"photo_modal_window"})}function h(e){var n=f[e],i="jpg",o="image/jpeg",r="photo"+e+"."+i,c=Math.max(screen.width||0,$(window).width()-36,800),d=Math.max(screen.height||0,$(t).height()-150,800),u=l(n,c,d),p={_:"inputFileLocation",volume_id:u.location.volume_id,local_id:u.location.local_id,secret:u.location.secret};s.chooseSave(r,i,o).then(function(e){e&&a.downloadFile(u.location.dc_id,p,u.size,{mime:o,toFileEntry:e}).then(function(){},function(e){console.log("photo download failed",e)})},function(){var e=a.getCachedFile(p);return e?s.download(e,o,r):void a.downloadFile(u.location.dc_id,p,u.size,{mime:o}).then(function(e){s.download(e,o,r)},function(e){console.log("photo download failed",e)})})}var f={},_=$(window).width(),v=$(window).height();return n.preloadPhoto=d,n.openPhoto=g,{savePhoto:r,preloadPhoto:d,getUserPhotos:c,getPhoto:u,choosePhotoSize:l,wrapForHistory:p,wrapForFull:m,openPhoto:g,downloadPhoto:h}}]).service("AppWebPagesManager",["$modal","$sce","$window","$rootScope","MtpApiManager","AppPhotosManager","RichTextProcessor",function(e,t,n,i,a,o,s){function r(e,t,n){e.photo&&"photo"===e.photo._?o.savePhoto(e.photo,n):delete e.photo,e.rTitle=s.wrapRichText(e.title||e.author,{noLinks:!0,noLinebreaks:!0});var a="";if("GitHub"==e.site_name){var r=e.url.match(/(https?:\/\/github\.com\/[^\/]+\/[^\/]+)/);r&&(a=r[0]+"/issues/{1}")}if(e.rDescription=s.wrapRichText(e.description,{contextSite:e.site_name||"external",contextHashtag:a}),t&&(void 0===p[e.id]&&(p[e.id]={}),p[e.id][t]=!0,u[e.id]=e),void 0===u[e.id]?u[e.id]=e:safeReplaceObject(u[e.id],e),!t&&void 0!==p[e.id]){var l=[];angular.forEach(p[e.id],function(e,t){l.push(t)}),i.$broadcast("webpage_updated",{id:e.id,msgs:l})}}function l(t,n){var a=i.$new(!0);a.webpageID=t,a.messageID=n,e.open({templateUrl:templateUrl("embed_modal"),windowTemplateUrl:templateUrl("media_modal_layout"),controller:"EmbedModalController",scope:a,windowClass:"photo_modal_window"})}function c(e){var t=angular.copy(u[e])||{_:"webPageEmpty"};return t.photo&&t.photo.id&&(t.photo=o.wrapForHistory(t.photo.id,{website:"photo"!=t.type&&"video"!=t.type})),t}function d(e){var i=c(e);if(!i.embed_url)return i;var a=$(window).width()-(Config.Mobile?0:10),o=$(n).height()-(Config.Mobile?92:150);!Config.Mobile&&a>800&&(a-=208);var s={width:a,height:o};if(i.embed_width&&i.embed_height){var r=calcImageInBox(i.embed_width,i.embed_height,a,o);s.width=r.w,s.height=r.h}else s.height=s.width=Math.min(a,o);var l=Config.Modes.chrome_packed?"webview":"iframe",d="iframe"!=i.embed_type?i.embed_type||"text/html":"text/html",u="<"+l+' src="'+encodeEntities(i.embed_url)+'" type="'+encodeEntities(d)+'" frameborder="0" border="0" webkitallowfullscreen mozallowfullscreen allowfullscreen width="'+s.width+'" height="'+s.height+'" style="width: '+s.width+"px; height: "+s.height+'px;">";return s.html=t.trustAs("html",u),i.full=s,i}var u={},p={};return i.$on("apiUpdate",function(e,t){switch(t._){case"updateWebPage":r(t.webpage)}}),{saveWebPage:r,openEmbed:l,wrapForFull:d,wrapForHistory:c}}]).service("AppVideoManager",["$sce","$rootScope","$modal","$window","MtpApiFileManager","AppUsersManager","FileManager","qSync",function(e,t,n,i,a,o,s,r){function l(e,t){t&&angular.extend(e,t),h[e.id]=e,e.thumb&&"photoCachedSize"==e.thumb._&&(a.saveSmallFile(e.thumb.location,e.thumb.bytes),e.thumb.size=e.thumb.bytes.length,delete e.thumb.bytes,e.thumb._="photoSize")}function c(e){if(void 0!==f[e])return f[e];var t=angular.copy(h[e]),n=Math.min(_-80,Config.Mobile?210:150),i=Math.min(v-100,Config.Mobile?210:150),a=t.thumb,o={placeholder:"img/placeholders/VideoThumbConversation.gif",width:n,height:i};return a&&"photoSizeEmpty"!=a._&&(a.w/a.h>n/i?o.height=parseInt(a.h*n/a.w):(o.width=parseInt(a.w*i/a.h),o.width>n&&(o.height=parseInt(o.height*n/o.width),o.width=n)),o.location=a.location,o.size=a.size),t.thumb=o,f[e]=t}function d(e){var t=c(e),n=Math.min($(window).width()-(Config.Mobile?0:60),542),a=$(i).height()-(Config.Mobile?92:150),o={placeholder:"img/placeholders/VideoThumbModal.gif",width:n,height:a};if(t.w&&t.h){var s=calcImageInBox(t.w,t.h,n,a);o.width=s.w,o.height=s.h}else o.height=o.width=Math.min(n,a);return t.full=o,t.fullThumb=angular.copy(t.thumb),t.fullThumb.width=o.width,t.fullThumb.height=o.height,t}function u(e,i){var a=t.$new(!0);return a.videoID=e,a.messageID=i,n.open({templateUrl:templateUrl("video_modal"),windowTemplateUrl:templateUrl("media_modal_layout"),controller:"VideoModalController",scope:a,windowClass:"video_modal_window"})}function p(e){var t=h[e],n=f[e]||t||{},i={_:"inputVideoFileLocation",id:e,access_hash:t.access_hash};void 0===n.downloaded&&a.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function m(n,i){var o=h[n],l=f[n]||o||{},c=o.mime_type||"video/ogg",d={_:"inputVideoFileLocation",id:n,access_hash:o.access_hash};if(l.downloaded&&!i){var u=a.getCachedFile(d);if(u)return r.when(u)}l.progress={enabled:!l.downloaded,percent:1,total:o.size};var p=a.downloadFile(o.dc_id,d,o.size,{mime:c,toFileEntry:i});return p.then(function(t){s.getFileCorrectUrl(t,c).then(function(t){l.url=e.trustAsResourceUrl(t)}),delete l.progress,l.downloaded=!0,console.log("video save done")},function(e){console.log("video download failed",e),l.progress.enabled=!1},function(e){console.log("dl progress",e),l.progress.enabled=!0,l.progress.done=e.done,l.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update")}),l.progress.cancel=p.cancel,p}function g(e){{var t=h[e],n=t.mime_type||"video/mp4",i=n.split(".")[1]||"mp4",a="t_video"+e+"."+i;f[e]||t||{}}s.chooseSave(a,i,n).then(function(t){t&&m(e,t)},function(){m(e).then(function(e){s.download(e,n,a)})})}var h={},f={},_=$(window).width(),v=$(window).height();return{saveVideo:l,wrapForHistory:c,wrapForFull:d,openVideo:u,updateVideoDownloaded:p,downloadVideo:m,saveVideoFile:g}}]).service("AppDocsManager",["$sce","$rootScope","$modal","$window","$q","RichTextProcessor","MtpApiFileManager","FileManager","qSync",function(e,t,n,i,a,o,s,r,l){function c(e,t){_[e.id]=e,t&&angular.extend(e,t),e.thumb&&"photoCachedSize"==e.thumb._&&(s.saveSmallFile(e.thumb.location,e.thumb.bytes),e.thumb.size=e.thumb.bytes.length,delete e.thumb.bytes,e.thumb._="photoSize"),angular.forEach(e.attributes,function(t){switch(t._){case"documentAttributeFilename":e.file_name=t.file_name;break;case"documentAttributeAudio":e.duration=t.duration,e.audioTitle=t.title,e.audioPerformer=t.performer;break;case"documentAttributeVideo":e.duration=t.duration;break;case"documentAttributeSticker":e.sticker=1,void 0!==t.alt&&(e.sticker=2,e.stickerEmojiRaw=t.alt,e.stickerEmoji=o.wrapRichText(e.stickerEmojiRaw,{noLinks:!0,noLinebreaks:!0})),t.stickerset&&("inputStickerSetEmpty"==t.stickerset._?delete t.stickerset:"inputStickerSetID"==t.stickerset._&&(e.stickerSetInput=t.stickerset));break;case"documentAttributeImageSize":e.w=t.w,e.h=t.h}}),e.file_name=e.file_name||""}function d(e){return _[e]||{_:"documentEmpty"}}function u(e){return void 0!==_[e]}function p(e){if(void 0!==v[e])return v[e];var t,n,i=angular.copy(_[e]),a="image/gif"==i.mime_type,o="image/webp"==i.mime_type&&i.sticker,s=i.thumb;a?(t=Math.min(y-80,260),n=Math.min(b-100,260)):o?(t=Math.min(y-80,Config.Mobile?128:192),n=Math.min(b-100,Config.Mobile?128:192)):t=n=100;var r,l={width:t,height:n};return s&&"photoSizeEmpty"!=s._?(r=a&&i.w&&i.h?{w:i.w,h:i.h}:calcImageInBox(s.w,s.h,t,n),l.width=r.w,l.height=r.h,l.location=s.location,l.size=s.size):o?(r=calcImageInBox(i.w,i.h,t,n),l.width=r.w,l.height=r.h):l=!1,i.thumb=l,i.withPreview=!Config.Mobile&&i.mime_type.match(/^image\/(gif|png|jpeg|jpg|bmp|tiff)/)?1:0,a&&i.thumb?i.isSpecial="gif":o?i.isSpecial="sticker":"audio/"==i.mime_type.substr(0,6)&&(i.isSpecial="audio"),v[e]=i}function m(e){var t=_[e],n=v[e]||t||{},i={_:"inputDocumentFileLocation",id:e,access_hash:t.access_hash,file_name:t.file_name};void 0===n.downloaded&&s.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function g(n,i){var a=_[n],o=v[n]||a||{},c={_:"inputDocumentFileLocation",id:n,access_hash:a.access_hash,file_name:a.file_name};if(o.downloaded&&!i){var d=s.getCachedFile(c);if(d)return l.when(d)}o.progress={enabled:!o.downloaded,percent:1,total:a.size};var u=s.downloadFile(a.dc_id,c,a.size,{mime:a.mime_type||"application/octet-stream",toFileEntry:i});return u.then(function(t){delete o.progress,t&&(r.getFileCorrectUrl(t,a.mime_type).then(function(t){o.url=e.trustAsResourceUrl(t)}),o.downloaded=!0),console.log("file save done")},function(e){console.log("document download failed",e),o.progress.enabled=!1},function(e){console.log("dl progress",e),o.progress.enabled=!0,o.progress.done=e.done,o.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update")}),o.progress.cancel=u.cancel,u}function h(e,i){var a=t.$new(!0);a.docID=e,a.messageID=i;n.open({templateUrl:templateUrl("document_modal"),windowTemplateUrl:templateUrl("media_modal_layout"),controller:"DocumentModalController",scope:a,windowClass:"document_modal_window"})}function f(e){var t=_[e],n=(v[e]||t||{},(t.file_name.split(".",2)||[])[1]||"");r.chooseSave(t.file_name,n,t.mime_type).then(function(t){t&&g(e,t)},function(){g(e).then(function(e){r.download(e,t.mime_type,t.file_name)})})}var _={},v={},y=$(window).width(),b=$(window).height();return{saveDoc:c,getDoc:d,hasDoc:u,wrapForHistory:p,updateDocDownloaded:m,downloadDoc:g,openDoc:h,saveDocFile:f}}]).service("AppAudioManager",["$sce","$rootScope","$modal","$window","MtpApiFileManager","FileManager","qSync",function(e,t,n,i,a,o,s){function r(e){p[e.id]=e}function l(e){if(void 0!==m[e])return m[e];var t=angular.copy(p[e]);return m[e]=t}function c(e){var t=p[e],n=m[e]||t||{},i={_:"inputAudioFileLocation",id:e,access_hash:t.access_hash};void 0===n.downloaded&&a.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function d(n,i){var r=p[n],l=m[n]||r||{},c=r.mime_type||"audio/ogg",d={_:"inputAudioFileLocation",id:n,access_hash:r.access_hash};if(l.downloaded&&!i){var u=a.getCachedFile(d);if(u)return s.when(u)}l.progress={enabled:!l.downloaded,percent:1,total:r.size};var g=a.downloadFile(r.dc_id,d,r.size,{mime:c,toFileEntry:i});return g.then(function(t){o.getFileCorrectUrl(t,c).then(function(t){l.url=e.trustAsResourceUrl(t)}),delete l.progress,l.downloaded=!0,console.log("audio save done")},function(e){console.log("audio download failed",e),l.progress.enabled=!1},function(e){console.log("dl progress",e),l.progress.enabled=!0,l.progress.done=e.done,l.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update")}),l.progress.cancel=g.cancel,g}function u(e){{var t=p[e],n=t.mime_type||"audio/ogg",i=n.split(".")[1]||"ogg",a="t_audio"+e+"."+i;m[e]||t||{}}o.chooseSave(a,i,n).then(function(t){t&&d(e,t)},function(){d(e).then(function(e){o.download(e,n,a)})})}var p={},m={};return{saveAudio:r,wrapForHistory:l,updateAudioDownloaded:c,downloadAudio:d,saveAudioFile:u}}]).service("AppStickersManager",["$q","$rootScope","$modal","_","FileManager","MtpApiManager","MtpApiFileManager","AppDocsManager","Storage",function(e,t,n,i,a,o,s,r,l){function c(){C||(C=!0,setTimeout(m,1e3))}function d(){return l.get("stickers_popular").then(function(e){var t,n,i,a=[];if(e&&e.length)for(t=0,n=e.length;n>t;t++)i=e[t][0],r.hasDoc(i)&&a.push({id:i,rate:e[t][1]});return a})}function u(e){d().then(function(t){for(var n=!1,i=t.length,a=[],o=0;i>o;o++)t[o].id==e&&(n=!0,t[o].rate++),a.push([t[o].id,t[o].rate]);n?a.sort(function(e,t){return t[1]-e[1]}):(a.length>15&&(a=a.slice(0,15)),a.push([e,1])),ConfigStorage.set({stickers_popular:a})})}function p(e){if(S!==e.hash){S=e.hash;var t,n,a,o,s,l,c,u;for(k=[],w=[],a=e.sets.length,t=0;a>t;t++){for(l=e.sets[t],u=e.fullSets[l.id],o=u.documents.length,c=[],n=0;o>n;n++)s=u.documents[n],r.saveDoc(s),w.push(s.id),c.push(s.id);k.push({id:l.id,title:l.title,short_name:l.short_name,installed:(1&l.flags)>0,disabled:(2&l.flags)>0,official:(4&l.flags)>0,docIDs:c}),$[l.id]=!0}}return d().then(function(e){var t=k;if(e.length){t=k.slice();var n,a,o=[];for(n=0,a=e.length;a>n;n++)o.push(e[n].id);t.unshift({id:0,title:i("im_stickers_tab_recent_raw"),short_name:"",installed:!0,disabled:!1,official:!1,docIDs:o})}return t})}function m(e){return l.get("all_stickers").then(function(t){var n=Config.Schema.API.layer;return t.layer!=n&&(t=!1),t&&t.date>tsNow(!0)&&!e?p(t):o.invokeApi("messages.getAllStickers",{hash:t&&t.hash||""}).then(function(e){var i="messages.allStickersNotModified"==e._;return i&&(e=t),e.date=tsNow(!0)+3600,e.layer=n,delete e._,i?(l.set({all_stickers:e}),p(e)):g(e).then(function(){return l.set({all_stickers:e}),p(e)})})})}function g(t){var n=[],i=t.fullSets||{};return t.fullSets={},angular.forEach(t.sets,function(e){var a=i[e.id];if(a&&a.set.hash==e.hash)t.fullSets[e.id]=a;else{var s=o.invokeApi("messages.getStickerSet",{stickerset:{_:"inputStickerSetID",id:e.id,access_hash:e.access_hash}}).then(function(n){t.fullSets[e.id]=n});n.push(s)}}),e.all(n)}function h(e){var t=r.getDoc(e),n=angular.copy(t.thumb.location);return n.sticker=!0,s.downloadSmallFile(n).then(function(e){return{id:t.id,src:a.getUrl(e,"image/webp")}})}function f(){var t=[];return angular.forEach(w,function(e){t.push(h(e))}),e.all(t)}function _(e){return o.invokeApi("messages.getStickerSet",{stickerset:e}).then(function(e){for(var t=0;tn;n++)h(a[n]);return _.seq=t.seq,t.date&&_.date=_.syncPending.seqAwaiting&&(_.syncPending.ptsAwaiting?delete _.syncPending.seqAwaiting:(clearTimeout(_.syncPending.timeout),_.syncPending=!1)),!0}function r(e){var t=e?m(e):_;if(!t.pendingPtsUpdates.length)return!1;t.pendingPtsUpdates.sort(function(e,t){return e.pts-t.pts});for(var n,i=t.pts,a=!1,o=!1,s=0,r=t.pendingPtsUpdates.length;r>s;s++)n=t.pendingPtsUpdates[s],i+=n.pts_count,i>=n.pts&&(a=n.pts,o=s);if(!a)return!1;for(t.pts=a,s=0;o>=s;s++)n=t.pendingPtsUpdates[s],h(n);return t.pendingPtsUpdates.splice(0,o+1),!t.pendingPtsUpdates.length&&t.syncPending&&(t.syncPending.seqAwaiting?delete t.syncPending.ptsAwaiting:(clearTimeout(t.syncPending.timeout),t.syncPending=!1)),!0}function l(){_.syncLoading||d()}function c(e){var t={date:e.date,seq:e.seq,seqStart:e.seq_start};switch(e._){case"updatesTooLong":case"new_session_created":l();break;case"updateShort":g(e.update,t);break;case"updateShortMessage":case"updateShortChatMessage":var o=2&e.flags,s=e.from_id||(o?y:e.user_id),r=e.chat_id?-e.chat_id:o?e.user_id:y;g({_:"updateNewMessage",message:{_:"message",flags:e.flags,pFlags:e.pFlags,id:e.id,from_id:s,to_id:a.getOutputPeer(r),date:e.date,message:e.message,fwd_from_id:e.fwd_from_id,fwd_date:e.fwd_date,reply_to_msg_id:e.reply_to_msg_id,entities:e.entities},pts:e.pts,pts_count:e.pts_count},t);break;case"updatesCombined":case"updates":n.saveApiUsers(e.users),i.saveApiChats(e.chats),angular.forEach(e.updates,function(e){g(e,t)});break;default:console.warn(dT(),"Unknown update message",e)}}function d(){_.syncLoading||(_.syncLoading=!0,_.pendingSeqUpdates={},_.pendingPtsUpdates=[]),_.syncPending&&(clearTimeout(_.syncPending.timeout),_.syncPending=!1),o.invokeApi("updates.getDifference",{pts:_.pts,date:_.date,qts:-1}).then(function(t){if("updates.differenceEmpty"==t._)return console.log(dT(),"apply empty diff",t.seq),_.date=t.date,_.seq=t.seq,_.syncLoading=!1,e.$broadcast("stateSynchronized"),!1;n.saveApiUsers(t.users),i.saveApiChats(t.chats),angular.forEach(t.other_updates,function(e){if("updateChannelTooLong"==e._){var t=e.channel_id,n=v[t];return void(void 0===n||n.syncLoading||u(t))}h(e)}),angular.forEach(t.new_messages,function(e){h({_:"updateNewMessage",message:e,pts:_.pts,pts_count:0})});var a=t.intermediate_state||t.state;_.seq=a.seq,_.pts=a.pts,_.date=a.date,console.log(dT(),"apply diff",_.seq,_.pts),"updates.differenceSlice"==t._?d():(e.$broadcast("stateSynchronized"),_.syncLoading=!1)})}function u(t){var a=m(t);a.syncLoading||(a.syncLoading=!0,a.pendingPtsUpdates=[]),o.invokeApi("updates.getChannelDifference",{channel:i.getChannelInput(t),filter:{_:"channelMessagesFilterEmpty"},pts:a.pts,limit:10}).then(function(o){return a.pts=o.pts,"updates.channelDifferenceEmpty"==o._?(console.log(dT(),"apply channel empty diff",o),a.syncLoading=!1,e.$broadcast("stateSynchronized"),!1):"updates.channelDifferenceTooLong"==o._?(console.log(dT(),"channel diff too long",o),a.syncLoading=!1,delete v[t],h({_:"updateChannelReload",channel_id:t}),!1):(n.saveApiUsers(o.users),i.saveApiChats(o.chats),console.log(dT(),"applying",o.other_updates.length,"channel other updates"),angular.forEach(o.other_updates,function(e){h(e)}),console.log(dT(),"applying",o.new_messages.length,"channel new messages"),angular.forEach(o.new_messages,function(e){h({_:"updateNewChannelMessage",message:e,pts:a.pts,pts_count:0})}),console.log(dT(),"apply channel diff",a.pts),void("updates.channelDifference"!=o._||o.pFlags["final"]?(console.log(dT(),"finished channel get diff"),e.$broadcast("stateSynchronized"),a.syncLoading=!1):u(t)))})}function p(e,t){return void 0===v[e]?(v[e]={pts:t,pendingPtsUpdates:[],syncPending:!1,syncLoading:!1},!0):!1}function m(e,t){if(void 0===v[e]){if(!t)throw new Error("Get channel empty state without pts "+e);p(e,t)}return v[e]}function g(e,t){var o=!1;switch(e._){case"updateNewChannelMessage":o=-a.getPeerID(e.message.to_id);break;case"updateDeleteChannelMessages":o=e.channel_id}if(o&&!i.hasChat(o))return!1;var c=o?m(o,e.pts):_;if(c.syncLoading)return!1;if("updateNewMessage"==e._){var p=e.message,g=p.fwd_from_id?a.getPeerID(p.fwd_from_id):0,f=a.getPeerID(p.to_id);if(p.from_id&&!n.hasUser(p.from_id)||g>0&&!n.hasUser(g)||0>g&&!i.hasChat(-g)||f>0&&!n.hasUser(f)||0>f&&!i.hasChat(-f))return console.warn(dT(),"Short update not enough data",p),l(),!1}var v,y;if(e.pts){var b=c.pts+(e.pts_count||0);if(bc.pts&&(c.pts=e.pts,v=!0)}else if(!o&&t.seq>0){var w=t.seq,k=t.seqStart||w;if(k!=c.seq+1&&k>c.seq)return console.warn(dT(),"Seq hole",c,c.syncPending&&c.syncPending.seqAwaiting),void 0===c.pendingSeqUpdates[k]&&(c.pendingSeqUpdates[k]={seq:w,date:t.date,updates:[]}),c.pendingSeqUpdates[k].updates.push(e),c.syncPending||(c.syncPending={timeout:setTimeout(function(){d()},5e3)}),(!c.syncPending.seqAwaiting||c.syncPending.seqAwaitinga-c||t.offline))return c=e?0:a,i.setUserStatus(u,e),n.invokeApi("account.updateStatus",{offline:e},{noErrorBox:!0})}function s(){l&&e.cancel(l),t.idle.isIDLE?l=e(function(){o(!0)},5e3):(o(!1),l=e(s,6e4))}function r(){return p?tsNow()>p?(p=!1,!1):!0:!1}var l,c=0,d=!1,u=0,p=!1;return n.getUserID().then(function(e){u=e}),t.$on("apiUpdate",function(e,t){"updateUserStatus"==t._&&t.user_id==u&&(p=tsNow()+("userStatusOnline"==t.status._?3e5:0))}),{start:a,isOtherDeviceActive:r}}]).service("NotificationsManager",["$rootScope","$window","$interval","$q","_","MtpApiManager","AppPeersManager","IdleManager","Storage","AppRuntimeManager","FileManager",function(e,t,n,i,a,o,s,r,l,c,d){function u(){l.get("notify_nodesktop","notify_volume","notify_novibrate","notify_nopreview").then(function(e){K.nodesktop=e[0],K.volume=e[1]===!1?.5:e[1],K.novibrate=e[2],K.nopreview=e[3]})}function p(){return K}function m(e){return void 0!==q[e]?q[e]:q[e]=o.invokeApi("account.getNotifySettings",{peer:{_:"inputNotifyPeer",peer:s.getInputPeerByID(e)}})}function g(e){if(e=e||"favicon.ico",P!==e){var t=document.createElement("link");t.rel="shortcut icon",t.type="image/x-icon",t.href=e,H.parentNode.replaceChild(t,H),H=t,P=e}}function h(t,n){q[t]=i.when(n),e.$broadcast("notify_settings",{peerID:t})}function f(e,t){h(e,t);var n=angular.copy(t);return n._="inputPeerNotifySettings",o.invokeApi("account.updateNotifySettings",{peer:{_:"inputNotifyPeer",peer:s.getInputPeerByID(e)},settings:n})}function _(e){return m(e).then(function(e){return"peerNotifySettings"==e._&&1e3*e.mute_until>tsNow()})}function v(){if(u(),e.$on("settings_changed",u),A(),!F)return!1;"Notification"in window&&"granted"!==Notification.permission&&"denied"!==Notification.permission&&$(t).on("click",b);try{"onbeforeunload"in window&&$(t).on("beforeunload",x)}catch(n){}}function y(){x(),n.cancel(D),g(),G=!0}function b(){Notification.requestPermission(),$(t).off("click",b)}function w(e){if(!G){if(Config.Navigator.ffos&&!Config.Navigator.ffos2p)e.image="https://telegram.org/img/t_logo.png";else if(e.image&&!angular.isString(e.image)){if(Config.Navigator.ffos2p)return d.getDataUrl(e.image,"image/jpeg").then(function(t){e.image=t,w(e)}),!1;e.image=d.getUrl(e.image,"image/jpeg")}else e.image||(e.image="img/icons/icon60.png");U++;var t=tsNow();if(K.volume>0&&(!e.tag||!R[e.tag]||t>R[e.tag]+6e4)&&(k(K.volume),R[e.tag]=t),!F||"Notification"in window&&"granted"!==Notification.permission)return!1;if(K.nodesktop){if(L&&!K.novibrate)return void navigator.vibrate([200,100,200])}else{var n,i=++O,a=e.key||"k"+i;if("Notification"in window)n=new Notification(e.title,{icon:e.image||"",body:e.message||"",tag:e.tag||""});else if("mozNotification"in navigator)n=navigator.mozNotification.createNotification(e.title,e.message||"",e.image||"");else{if(!I)return;window.external.msSiteModeClearIconOverlay(),window.external.msSiteModeSetIconOverlay("img/icons/icon16.png",e.title),window.external.msSiteModeActivate(),n={index:i}}n.onclick=function(){n.close(),c.focus(),x(),e.onclick&&e.onclick()},n.onclose=function(){n.hidden||(delete N[a],x())},n.show&&n.show(),N[a]=n,Config.Navigator.mobile||setTimeout(function(){C(a)},8e3)}}}function k(e){var t=tsNow();if(!(B&&B>t&&j==e)){B=t+1e3,j=e;var n="img/sound_a.mp3",i=$("#notify_sound").html('');i.find("audio")[0].volume=e}}function S(e){var t=N[e];if(t){U>0&&U--;try{t.close?t.close():I&&t.index==O&&window.external.msSiteModeClearIconOverlay()}catch(n){}delete U[e]}}function C(e){var t=N[e];if(t){try{t.close&&(t.hidden=!0,t.close())}catch(n){}delete U[e]}}function M(e){delete R[e]}function x(){I?window.external.msSiteModeClearIconOverlay():angular.forEach(N,function(e){try{e.close&&e.close()}catch(t){}}),N={},U=0}function A(){if(Y)return!1;if(navigator.push&&Config.Navigator.ffos&&Config.Modes.packed){var e=navigator.push.register();e.onsuccess=function(){clearTimeout(X),console.log(dT(),"Push registered",e.result),Y=e.result,o.invokeApi("account.registerDevice",{token_type:4,token:Y,device_model:navigator.userAgent||"Unknown UserAgent",system_version:navigator.platform||"Unknown Platform",app_version:Config.App.version,app_sandbox:!1,lang_code:navigator.language||"en"})},e.onerror=function(e){console.error("Push register error",e,e.toString()),X=setTimeout(A,Z),Z=Math.min(3e4,1.5*Z)}}}function E(){return L}navigator.vibrate=navigator.vibrate||navigator.mozVibrate||navigator.webkitVibrate;var I=!1;try{window.external&&window.external.msIsSiteMode()&&(I=!0)}catch(T){}var D,P,F=I||"Notification"in window||"mozNotification"in navigator,N={},O=0,U=0,R={},L=!!navigator.vibrate,B=!1,j=!1,q={},H=$('link[rel="icon"]:first')[0],V=a.pluralize("page_title_pluralize_notifications"),z=document.title,W=!1,G=!1,K={};e.$watch("idle.deactivated",function(e){e&&y()}),e.$watch("idle.isIDLE",function(e){G||(e||x(),Config.Navigator.mobile||(n.cancel(D),e?(z=document.title,D=n(function(){W||!U?(W=!1,document.title=z,g()):(W=!0,document.title=V(U),g("favicon_unread.ico"))},1e3)):(W=!1,document.title=z,g())))}),e.$on("apiUpdate",function(e,t){switch(t._){case"updateNotifySettings":if("notifyPeer"==t.peer._){var n=s.getPeerID(t.peer.peer);h(n,t.notify_settings)}}});var Y=!1;return window.navigator.mozSetMessageHandler&&(window.navigator.mozSetMessageHandler("push",function(t){console.log(dT(),"received push",t),e.$broadcast("push_received")}),window.navigator.mozSetMessageHandler("push-register",function(e){console.log(dT(),"received push",e),Y=!1,A()})),{start:v,notify:w,cancel:S,clear:x,soundReset:M,getPeerSettings:m,getPeerMuted:_,savePeerSettings:h,updatePeerSettings:f,updateNotifySettings:u,getNotifySettings:p,getVibrateSupport:E,testSound:k};var Z,X}]).service("PasswordManager",["$timeout","$q","$rootScope","MtpApiManager","CryptoWorker","MtpSecureRandom",function(e,t,n,i,a,o){function s(e){return i.invokeApi("account.getPassword",{},e).then(function(e){return e})}function r(e,n){var a,s,r={new_settings:{_:"account.passwordInputSettings",flags:0,hint:n.hint||""}};if(a="string"==typeof n.cur_password&&n.cur_password.length>0?u(e.current_salt,n.cur_password):t.when([]),"string"==typeof n.new_password&&n.new_password.length>0){var l=new Array(8),c=bufferConcat(e.new_salt,l);o.nextBytes(l),s=u(c,n.new_password),r.new_settings.new_salt=c,r.new_settings.flags|=1}else"string"==typeof n.new_password&&(r.new_settings.flags|=1,r.new_settings.new_salt=[]),s=t.when([]);return"string"==typeof n.email&&(r.new_settings.flags|=2,r.new_settings.email=n.email||""),t.all([a,s]).then(function(e){return r.current_password_hash=e[0],r.new_settings.new_password_hash=e[1],i.invokeApi("account.updatePasswordSettings",r)})}function l(e,t,n){return u(e.current_salt,t).then(function(e){return i.invokeApi("auth.checkPassword",{password_hash:e},n)})}function c(e,t){return i.invokeApi("auth.requestPasswordRecovery",{},t)}function d(e,t){return i.invokeApi("auth.recoverPassword",{code:e},t)}function u(e,t){for(var n=unescape(encodeURIComponent(t)),i=new ArrayBuffer(n.length),o=new Uint8Array(i),s=0,r=n.length;r>s;s++)o[s]=n.charCodeAt(s);return i=bufferConcat(bufferConcat(e,o),e),a.sha256Hash(i)}return{check:l,getState:s,requestRecovery:c,recover:d,updateSettings:r}}]).service("ErrorService",["$rootScope","$modal","$window",function(e,t,n){function i(n,i){if(s>=1)return console.log("Skip error box, too many open",s,n,i),!1;i=i||{};var a=e.$new();angular.extend(a,n),s++;var o=t.open({templateUrl:templateUrl("error_modal"),scope:a,windowClass:i.windowClass||"error_modal_window"});return o.result["finally"](function(){s--}),o}function a(e,t){return i({title:e,description:t})}function o(n,i){i=i||{};var a=e.$new();angular.extend(a,n);var o=t.open({templateUrl:templateUrl("confirm_modal"),scope:a,windowClass:i.windowClass||"confirm_modal_window"});return o.result}var s=0;return n.safeConfirm=function(e,t){"string"==typeof e&&(e={message:e}),o(e).then(function(e){t(e||!0)},function(){t(!1)})},{show:i,alert:a,confirm:o}}]).service("PeersSelectService",["$rootScope","$modal",function(e,t){function n(n){var i=e.$new();return i.multiSelect=!1,i.noMessages=!0,n&&angular.extend(i,n),t.open({templateUrl:templateUrl("peer_select"),controller:"PeerSelectController",scope:i,windowClass:"peer_select_window mobile_modal",backdrop:"single"}).result}function i(i){if(Config.Mobile)return n(i).then(function(e){return[e]});var a=e.$new();return a.multiSelect=!0,a.noMessages=!0,i&&angular.extend(a,i),t.open({templateUrl:templateUrl("peer_select"),controller:"PeerSelectController",scope:a,windowClass:"peer_select_window mobile_modal",backdrop:"single"}).result}return{selectPeer:n,selectPeers:i}}]).service("ContactsSelectService",["$rootScope","$modal",function(e,t){function n(n,i){i=i||{};var a=e.$new();return a.multiSelect=n,angular.extend(a,i),!a.action&&n&&(a.action="select"),t.open({templateUrl:templateUrl("contacts_modal"),controller:"ContactsModalController",scope:a,windowClass:"contacts_modal_window mobile_modal",backdrop:"single"}).result}return{selectContacts:function(e){return n(!0,e)},selectContact:function(e){return n(!1,e)}}}]).service("ChangelogNotifyService",["Storage","$rootScope","$modal",function(e,t,n){function i(){e.get("last_version").then(function(t){t!=Config.App.version&&(t&&a(t),e.set({last_version:Config.App.version}))})}function a(e){var i=t.$new();i.lastVersion=e,n.open({controller:"ChangelogModalController",templateUrl:templateUrl("changelog_modal"),scope:i,windowClass:"changelog_modal_window mobile_modal"})}return{checkUpdate:i,showChangelog:a}}]).service("HttpsMigrateService",["ErrorService","Storage",function(e,t){function n(){t.get("https_dismiss").then(function(n){(!n||tsNow()>n+432e5)&&e.confirm({type:"MIGRATE_TO_HTTPS"}).then(function(){var e;try{e=window.open("https://web.telegram.org","_blank")}catch(t){}e||(location.href="https://web.telegram.org")},function(){t.set({https_dismiss:tsNow()})})})}function i(){a||"http:"!=location.protocol||Config.Modes.http||-1==Config.App.domains.indexOf(location.hostname)||(a=!0,setTimeout(n,12e4))}var a=!1;return{start:i,check:n}}]).service("LayoutSwitchService",["ErrorService","Storage","AppRuntimeManager","$window",function(e,t,n,i){function a(e){ConfigStorage.noPrefix(),t.set({layout_selected:e?"mobile":"desktop",layout_width:$(window).width()}).then(function(){n.reload()})}function o(n){if(!l){var i=$(window).width(),o=600>i;!i||!n&&(Config.Navigator.mobile?800>=i:o)||o!=Config.Mobile&&(ConfigStorage.noPrefix(),t.get("layout_width").then(function(n){return i==n?!1:(l=!0,void e.confirm({type:o?"SWITCH_MOBILE_VERSION":"SWITCH_DESKTOP_VERSION"}).then(function(){a(o) },function(){ConfigStorage.noPrefix(),t.set({layout_width:i}),l=!1}))}))}}function s(){r||Config.Navigator.mobile||(r=!0,o(),$(i).on("resize",o))}var r=!1,l=!1;return{start:s,switchLayout:a}}]).service("TelegramMeWebService",["Storage",function(e){function t(t){return n?!1:void e.get("tgme_sync").then(function(n){var i=tsNow(!0);if(t&&n&&n.canRedirect==t&&n.ts+86400>i)return!1;e.set({tgme_sync:{canRedirect:t,ts:i}});var a=$("