diff --git a/app.manifest b/app.manifest index 570cfc18..9f1ba2a2 100644 --- a/app.manifest +++ b/app.manifest @@ -1,5 +1,5 @@ CACHE MANIFEST -# Time: Thu Jan 01 2015 08:18:07 GMT+0100 (CET) +# Time: Thu Jan 01 2015 08:35:15 GMT+0100 (CET) CACHE: diff --git a/css/desktop.css b/css/desktop.css index cf01f178..72af1b2f 100644 --- a/css/desktop.css +++ b/css/desktop.css @@ -36,7 +36,7 @@ padding: 17px 20px 15px 22px; display: block; font-size: 14px; - line-height: 14px; + line-height: 16px; vertical-align: top; } .tg_head_logo_dropdown .dropdown-toggle:hover, @@ -55,6 +55,10 @@ } .tg_head_logo_dropdown .icon-hamburger-wrap { margin: 0 40px 0 0; + vertical-align: top; +} +.tg_head_logo_dropdown .icon-tg-title { + vertical-align: top; } .icon-hamburger-wrap .icon-bar { background: #fff; diff --git a/js/app.js b/js/app.js index 0e9b72de..068aa2ea 100644 --- a/js/app.js +++ b/js/app.js @@ -15,6 +15,6 @@ return(4294967295^i)>>>0}function i(){}function a(e){var t,n,i,a,o,r,s,l,c,d=e.l l.storeIntBytes(a.authKeyID,64,"auth_key_id"),l.storeIntBytes(t.msgKey,128,"msg_key"),l.storeRawBytes(t.bytes,"encrypted_data");var c,d=b?l.getBuffer():l.getArray();try{n=angular.extend(n||{},{responseType:"arraybuffer",transformRequest:null}),c=r.post(e.chooseServer(a.dcID,a.upload),d,n)}catch(u){c=s.reject(u)}return c.then(function(e){return e.data&&e.data.byteLength?e:s.reject({code:406,type:"NETWORK_BAD_RESPONSE"})},function(e){return 404==e.status&&-1!=(e.data||"").indexOf("nginx/0.3.33")&&i.remove("dc"+a.dcID+"_server_salt","dc"+a.dcID+"_auth_key").then(function(){o.reload()}),e.message||e.type||(e={code:406,type:"NETWORK_BAD_REQUEST"}),s.reject(e)})})},u.prototype.parseResponse=function(e){var t=this,n=new TLDeserialization(e),i=n.fetchIntBytes(64,!1,"auth_key_id");if(!bytesCmp(i,this.authKeyID))throw new Error("Invalid server auth_key_id: "+bytesToHex(i));var o=n.fetchIntBytes(128,!0,"msg_key"),r=n.fetchRawBytes(e.byteLength-n.getOffset(),!0,"encrypted_data");return this.getDecryptedMessage(o,r).then(function(e){var n=new TLDeserialization(e,{mtproto:!0}),i=(n.fetchIntBytes(64,!1,"salt"),n.fetchIntBytes(64,!1,"session_id")),r=n.fetchLong("message_id"),s=n.fetchInt("seq_no"),l=n.fetchRawBytes(!1,!0,"message_data"),c=convertToUint8Array(e).subarray(0,n.getOffset());return a.sha1Hash(c).then(function(e){if(!bytesCmp(o,bytesFromArrayBuffer(e).slice(-16)))throw console.warn(o,bytesFromArrayBuffer(e)),new Error("server msgKey mismatch");var n=bytesToArrayBuffer(l),a={mtproto:!0,override:{mt_message:function(e,t){e.msg_id=this.fetchLong(t+"[msg_id]"),e.seqno=this.fetchInt(t+"[seqno]"),e.bytes=this.fetchInt(t+"[bytes]");var n=this.getOffset();try{e.body=this.fetchObject("Object",t+"[body]")}catch(i){console.error(dT(),"parse error",i.message,i.stack),e.body={_:"parse_error",error:i}}this.offset!=n+e.bytes&&(console.warn(dT(),"set offset",this.offset,n,e.bytes),this.offset=n+e.bytes)},mt_rpc_result:function(e,n){e.req_msg_id=this.fetchLong(n+"[req_msg_id]");var i=t.sentMessages[e.req_msg_id],a=i&&i.resultType||"Object";e.result=this.fetchObject(a,n+"[result]")}}},c=new TLDeserialization(n,a),d=c.fetchObject("","INPUT");return{response:d,messageID:r,sessionID:i,seqNo:s}})})},u.prototype.applyServerSalt=function(e){var t=longToBytes(e),n={};return n["dc"+this.dcID+"_server_salt"]=bytesToHex(t),i.set(n),this.serverSalt=t,!0},u.prototype.sheduleRequest=function(e){this.offline&&this.checkConnection("forced shedule");var t=tsNow()+e;return e&&this.nextReq&&this.nextReq<=t?!1:(l.cancel(this.nextReqPromise),e>0?this.nextReqPromise=l(this.performSheduledRequest.bind(this),e||0):setZeroTimeout(this.performSheduledRequest.bind(this)),void(this.nextReq=t))},u.prototype.ackMessage=function(e){this.pendingAcks.push(e),this.sheduleRequest(3e4)},u.prototype.reqResendMessage=function(e){console.log(dT(),"Req resend",e),this.pendingResends.push(e),this.sheduleRequest(100)},u.prototype.cleanupSent=function(){var e=this,t=!1;return angular.forEach(this.sentMessages,function(n,i){if(n.notContentRelated&&void 0===e.pendingMessages[i])delete e.sentMessages[i];else if(n.container){for(var a=0;ar;r++)this.processMessage(e.messages[r],n,a);break;case"bad_server_salt":console.log(dT(),"Bad server salt",e);var s=this.sentMessages[e.bad_msg_id];if(!s||s.seq_no!=e.bad_msg_seqno)throw console.log(e.bad_msg_id,e.bad_msg_seqno),new Error("Bad server salt for invalid message");this.applyServerSalt(e.new_server_salt),this.pushResend(e.bad_msg_id),this.ackMessage(n);break;case"bad_msg_notification":console.log(dT(),"Bad msg notification",e);var s=this.sentMessages[e.bad_msg_id];if(!s||s.seq_no!=e.bad_msg_seqno)throw console.log(e.bad_msg_id,e.bad_msg_seqno),new Error("Bad msg notification for invalid message");if(16==e.error_code||17==e.error_code){t.applyServerTime(bigStringInt(n).shiftRight(32).toString(10))&&(console.log(dT(),"Update session"),this.updateSession());var l=this.updateSentMessage(e.bad_msg_id);this.pushResend(l.msg_id),this.ackMessage(n)}break;case"message":this.serverMessages.push(e.msg_id),this.processMessage(e.body,e.msg_id,a);break;case"new_session_created":this.ackMessage(n),this.processMessageAck(e.first_msg_id),this.applyServerSalt(e.server_salt);var c=this;i.get("dc").then(function(t){t==c.dcID&&!c.upload&&h&&h(e)});break;case"msgs_ack":for(var r=0;r5?"[.."+e.result.length+"..]":e.result),console.log(dT(),"Rpc response",g)}s.deferred.resolve(e.result)}s.isAPI&&(this.connectionInited=!0)}delete this.sentMessages[p]}break;default:this.ackMessage(n),h&&h(e)}},{getNetworker:function(e,t,n,i){return new u(e,t,n,i)},setUpdatesProcessor:function(e){h=e},stopAll:m,startAll:p}}]),angular.module("izhukov.mtproto.wrapper",["izhukov.utils","izhukov.mtproto"]).factory("MtpApiManager",["Storage","MtpAuthorizer","MtpNetworkerFactory","MtpSingleInstanceService","ErrorService","qSync","$q","TelegramMeWebService",function(e,t,n,i,a,o,r,s){function l(e){f!==e&&(f=e,s.setAuthorized(f))}function c(t,n){e.set({dc:t,user_auth:angular.extend({dcID:t},n)}),l(!0),v=t}function d(){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;a0||!1),e.id||0})}function h(){return v||!1}var f,g={},_={},y={},v=!1;return i.start(),e.get("dc").then(function(e){e&&(v=e)}),{getBaseDcID:h,getUserID:m,invokeApi:p,getNetworker:u,setUserAuth:c,logOut:d}}]).factory("MtpApiFileManager",["MtpApiManager","$q","FileManager","IdbFileStorage","TmpfsFileStorage","MemoryFileStorage",function(e,t,n,i,a,o){function r(e,n,i){void 0===v[e]&&(v[e]=[],b[e]=0);var a=v[e],o=t.defer();return a.push({cb:n,deferred:o,activeDelta:i}),setZeroTimeout(function(){s(e)}),o.promise}function s(e){var t=v[e],n="upload"==e?11:5;if(b[e]>=n||!t||!t.length)return!1;var i=t.shift(),a=i.activeDelta||1;b[e]+=a;w++;i.cb().then(function(t){b[e]-=a,s(e),i.deferred.resolve(t)},function(t){b[e]-=a,s(e),i.deferred.reject(t)})}function l(e){switch(e._){case"inputVideoFileLocation":return"video"+e.id+".mp4";case"inputDocumentFileLocation":return"doc"+e.id;case"inputAudioFileLocation":return"audio"+e.id}return e.volume_id||console.trace("Empty location",e),e.volume_id+"_"+e.local_id+"_"+e.secret+".jpg"}function c(e){if(!e)return!1;var t=l(e);return y[t]||!1}function d(){return a.isAvailable()?a:i.isAvailable()?i:o}function u(e,t){var n=l(e);return g[n]||(g[n]=d().saveFile(n,t).then(function(e){return y[n]=e})),g[n]}function p(i){if(!n.isAvailable())return t.reject({type:"BROWSER_BLOB_NOT_SUPPORTED"});var a=l(i),o="image/jpeg",s=g[a]||_[a];if(s)return s;var c=d();return _[a]=c.getFile(a).then(function(e){return y[a]=e},function(){var t=r(i.dc_id,function(){return e.invokeApi("upload.getFile",{location:angular.extend({},i,{_:"inputFileLocation"}),offset:0,limit:0},{dcID:i.dc_id,fileDownload:!0,createNetworker:!0})});return c.getFileWriter(a,o).then(function(e){return t.then(function(t){return n.write(e,t.bytes).then(function(){return y[a]=e.finalize()})})})})}function m(e,t){var n=d(),i=l(e);return n.getFile(i,t)}function h(i,a,o,s){if(!n.isAvailable())return t.reject({type:"BROWSER_BLOB_NOT_SUPPORTED"});s=s||{};var c=l(a),u=s.toFileEntry||null,p=g[c]||_[c],m=d();if(p)return u?p.then(function(e){return n.copy(e,u)}):p;var h,f=t.defer(),v=!1,b=!1,w=s.mime||"image/jpeg",$=function(e){f.reject(e),$=angular.noop,!h||e&&"DOWNLOAD_CANCELED"==e.type||h.truncate(0)};return m.getFile(c,o).then(function(e){u?n.copy(e,u).then(function(){f.resolve()},$):f.resolve(y[c]=e)},function(){var s=u?n.getFileWriter(u):m.getFileWriter(c,w);s.then(function(s){h=s;var l,d,p=524288,m=0,g=t.when();for(s.length&&(m=s.length,s.seek(m),f.notify({done:m,total:o})),l=m;o>l;l+=p)d=t.defer(),function(l,d,m,h){return r(i,function(){return v?t.when():e.invokeApi("upload.getFile",{location:a,offset:d,limit:p},{dcID:i,fileDownload:!0,createNetworker:!0})},2).then(function(e){h.then(function(){return v?t.when():n.write(s,e.bytes).then(function(){m.resolve()},$).then(function(){l?(b=!0,u?f.resolve():f.resolve(y[c]=s.finalize())):f.notify({done:d+p,total:o})})})})}(l+p>=o,l,d,g),g=d.promise})}),f.promise.cancel=function(){v||b||(v=!0,delete _[c],$({type:"DOWNLOAD_CANCELED"}))},u||(_[c]=f.promise),f.promise}function f(n){var i=n.size,a=i>=10485760,o=!1,s=!1,l=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>1500)return t.reject({type:"FILE_TOO_BIG"});var p,m=[nextRandomInt(4294967295),nextRandomInt(4294967295)],h=t.defer(),f=function(e){h.reject(e),o=!0,f=angular.noop},g=0,_={_:a?"inputFileBig":"inputFile",id:m,parts:u,name:n.name,md5_checksum:""};for(p=0;i>p;p+=c)!function(p,g){r("upload",function(){var r=t.defer(),d=new FileReader,y=n.slice(p,p+c);return d.onloadend=function(t){return o?void r.reject():void(t.target.readyState==FileReader.DONE&&e.invokeApi(a?"upload.saveBigFilePart":"upload.saveFilePart",{file_id:m,file_part:g,file_total_parts:u,bytes:t.target.result},{startMaxLength:c+256,fileUpload:!0,singleInRequest:!0}).then(function(){l++,r.resolve(),l>=u?(h.resolve(_),s=!0):(console.log(dT(),"Progress",l*c/i),h.notify({done:l*c,total:i}))},f))},d.readAsArrayBuffer(y),r.promise},d)}(p,g++);return h.promise.cancel=function(){console.log("cancel upload",o,s),o||s||(o=!0,f({type:"UPLOAD_CANCELED"}))},h.promise}var g={},_={},y={},v={},b={},w=0;return{getCachedFile:c,getDownloadedFile:m,downloadFile:h,downloadSmallFile:p,saveSmallFile:u,uploadFile:f}}]).service("MtpSingleInstanceService",["_","$rootScope","$interval","Storage","AppRuntimeManager","IdleManager","ErrorService","MtpNetworkerFactory",function(e,t,n,i,a,o,r,s){function l(){if(!p&&!Config.Navigator.mobile&&!Config.Modes.packed){p=!0,o.start(),h=tsNow(),t.$watch("idle.isIDLE",d),n(d,5e3),d();try{$($window).on("beforeunload",c)}catch(e){}}}function c(){i.remove(m?"xt_instance":"xt_idle_instance")}function d(){var n=tsNow(),a=t.idle&&t.idle.isIDLE,o={id:u,idle:a,time:n};i.get("xt_instance","xt_idle_instance").then(function(t){var l=t[0],c=t[1];!l||l.timen-1e4&&n>f&&(r.alert(e("error_modal_warning_title_raw"),e("error_modal_multiple_open_tabs_raw")),f+=tsNow()+6e4)),i.set({xt_instance:o}),m||s.startAll(),m=!0):(i.set({xt_idle_instance:o}),m&&s.stopAll(),m=!1)})}var u=nextRandomInt(4294967295),p=!1,m=!1,h=tsNow(),f=0;return{start:l}}]),angular.module("myApp",["ngRoute","ngSanitize","ngTouch","ui.bootstrap","mediaPlayer","izhukov.utils","izhukov.mtproto","izhukov.mtproto.wrapper","myApp.filters","myApp.services","myApp.templates","myApp.directives","myApp.controllers"]).config(["$locationProvider","$routeProvider","$compileProvider","StorageProvider",function(e,t,n,i){var a,o,r,s,l,c,d,u={},p={};for(o=0;o=1e3?void o.resolve(r):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:r}}]).service("AppChatsManager",["$rootScope","$modal","_","MtpApiFileManager","MtpApiManager","AppUsersManager","RichTextProcessor","SearchIndexManager",function(e,t,n,i,a,o,r,s){function l(e){angular.forEach(e,c)}function c(t){if(angular.isObject(t)){t.rTitle=r.wrapRichText(t.title,{noLinks:!0,noLinebreaks:!0})||n("chat_title_deleted");var i=s.cleanSearchText(t.title||"").split(" "),a=i.shift(),o=i.pop();t.initials=a.charAt(0)+(o?o.charAt(0):a.charAt(1)),t.num=Math.abs(t.id>>1)%(Config.Mobile?4:8)+1,void 0===g[t.id]?g[t.id]=t:(safeReplaceObject(g[t.id],t),e.$broadcast("chat_update",t.id)),void 0!==_[t.id]&&safeReplaceObject(_[t.id],t&&t.photo&&t.photo.photo_small||{empty:!0})}}function d(e){return g[e]||{id:e,deleted:!0}}function u(e){return angular.isObject(g[e])}function p(e,t){var n=d(e);return void 0===_[e]&&(_[e]=n&&n.photo&&n.photo.photo_small||{empty:!0}),{placeholder:"img/placeholders/"+t+"Avatar"+n.num+"@2x.png",location:_[e]}}function m(e){d(e);return"g"+e}function h(e,t){var n=angular.copy(t),i=d(e);return n.participants&&"chatParticipants"==n.participants._&&a.getUserID().then(function(e){angular.forEach(n.participants.participants,function(t){t.user=o.getUser(t.user_id),t.canLeave=e==t.user_id,t.canKick=!t.canLeave&&(e==n.participants.admin_id||e==t.inviter_id)})}),n.thumb={placeholder:"img/placeholders/GroupAvatar"+(Math.abs(e)%4+1)+"@2x.png",location:i&&i.photo&&i.photo.photo_small,width:72,height:72,size:0},n.peerString=m(e),n.chat=i,n}function f(n){var i=e.$new();i.chatID=n;t.open({templateUrl:templateUrl("chat_modal"),controller:"ChatModalController",scope:i,windowClass:"chat_modal_window mobile_modal"})}var g={},_={};return{saveApiChats:l,saveApiChat:c,getChat:d,getChatPhoto:p,getChatString:m,hasChat:u,wrapForFull:h,openChat:f}}]).service("AppPeersManager",["AppUsersManager","AppChatsManager","MtpApiManager",function(e,t){return{getInputPeer:function(e){var t="u"==e.charAt(0),n=e.substr(1).split("_");return t?{_:"inputPeerForeign",user_id:n[0],access_hash:n[1]}:{_:"inputPeerChat",chat_id:n[0]}},getInputPeerByID:function(t){return t>0?{_:"inputPeerForeign",user_id:t,access_hash:e.getUser(t).access_hash||0}:0>t?{_:"inputPeerChat",chat_id:-t}:void 0},getPeerSearchText:function(n){var i;if(n>0)i=e.getUserSearchText(n);else if(0>n){var a=t.getChat(-n);i=a.title||""}return i},getPeerString:function(n){return n>0?e.getUserString(n):t.getChatString(-n)},getOutputPeer:function(e){return e>0?{_:"peerUser",user_id:e}:{_:"peerChat",chat_id:-e}},getPeerID:function(e){if(angular.isObject(e))return e.user_id?e.user_id:-e.chat_id;var t="u"==e.charAt(0),n=e.substr(1).split("_");return t?n[0]:-n[0]||0},getPeer:function(n){return n>0?e.getUser(n):t.getChat(-n)},getPeerPhoto:function(n,i,a){return n>0?e.getUserPhoto(n,i):t.getChatPhoto(-n,a)}}}]).service("AppMessagesManager",["$q","$rootScope","$location","$filter","ApiUpdatesManager","AppUsersManager","AppChatsManager","AppPeersManager","AppPhotosManager","AppVideoManager","AppDocsManager","AppAudioManager","MtpApiManager","MtpApiFileManager","RichTextProcessor","NotificationsManager","SearchIndexManager","PeersSelectService","Storage","FileManager","TelegramMeWebService","_",function(e,t,n,i,a,o,r,s,l,c,d,u,p,m,h,f,g,_,y,v,b,w){function $(t,n,i){var a=Y;if(angular.isString(t)&&t.length){if(!i||at.query!==t){at.query=t;var l=g.search(t,it);at.dialogs=[],angular.forEach(Y.dialogs,function(e){l[e.peerID]&&at.dialogs.push(e)}),at.count=at.dialogs.length}a=at}else at.query=!1;var c=0;if(n>0)for(c=0;ca.dialogs[c].top_message);c++);return null!==a.count&&a.dialogs.length==a.count||a.dialogs.length>=c+(i||1)?e.when({count:a.count,dialogs:a.dialogs.slice(c,c+(i||20))}):(i=i||20,p.invokeApi("messages.getDialogs",{offset:c,limit:i,max_id:n||0}).then(function(e){if(b.setAuthorized(!0),o.saveApiUsers(e.users),r.saveApiChats(e.chats),D(e.messages),n>0)for(c=0;ca.dialogs[c].top_message);c++);return a.count=e.count||e.dialogs.length,a.dialogs.splice(c,a.dialogs.length-c),angular.forEach(e.dialogs,function(e){var t=s.getPeerID(e.peer),n=s.getPeerSearchText(t);g.indexObject(t,n,it),a.dialogs.push({peerID:t,top_message:e.top_message,unread_count:e.unread_count}),void 0===X[t]&&(X[t]={count:null,history:[e.top_message],pending:[]}),f.savePeerSettings(t,e.notify_settings)}),{count:a.count,dialogs:a.dialogs.slice(c,c+i)}}))}function k(e,t,n,i){return p.invokeApi("messages.getHistory",{peer:e,offset:i||0,limit:n||0,max_id:t||0},{noErrorBox:!0}).then(function(e){return o.saveApiUsers(e.users),r.saveApiChats(e.chats),D(e.messages),e})}function C(e,t,n,i){return k(e,t,n).then(function(a){i.count=a.count||a.messages.length;var o=0;if(t>0)for(o=0;oi.history[o]);o++);return i.history.splice(o,i.history.length-o),angular.forEach(a.messages,function(e){i.history.push(e.id)}),n-=a.messages.length,n>0&&i.history.length0)for(d=!0,c=0;cl.history[c]){d=!1;break}}else{var h=z(r);if(h&&h[0]&&h[0].unread_count>1){var f=h[0].unread_count;(p=f>50)?(i=10,u=6,c=f-u):(i=Math.max(10,o,f+2),u=f)}else Config.Mobile&&(i=20)}return!d&&(null!==l.count&&l.history.length==l.count||l.history.length>=c+(i||1))?(a?(a=Math.min(c,a),c=Math.max(0,c-a),i+=a):i=i||(c?20:o||5),e.when({count:l.count,history:m.concat(l.history.slice(c,c+i)),unreadOffset:u,unreadSkip:p})):(a||i||(i=o||20),d&&(c=0),a||p||n&&-1==l.history.indexOf(n)?(a&&(c=-a,i+=a),k(t,n,i,c).then(function(e){l.count=e.count||e.messages.length;var t=[];return angular.forEach(e.messages,function(e){t.push(e.id)}),{count:l.count,history:m.concat(t),unreadOffset:u,unreadSkip:p}})):C(t,n,i,l).then(function(){if(c=0,n>0)for(c=0;cl.history[c]);c++);return{count:l.count,history:m.concat(l.history.slice(c,c+i)),unreadOffset:u,unreadSkip:p}}))}function M(t,n,i,a,l){var c=[],d=!n,u=s.getPeerID(t),m={peer:u,filter:i},h=d&&angular.equals(ot,m);if(d&&!h&&(ot=m,rt=[]),!a&&!n){var f=X[u];if(void 0!==f&&f.history.length){var g,_,y={},v=l||20;switch(i._){case"inputMessagesFilterPhotos":y.messageMediaPhoto=!0;break;case"inputMessagesFilterVideo":y.messageMediaVideo=!0;break;case"inputMessagesFilterPhotoVideo":y.messageMediaPhoto=!0,y.messageMediaVideo=!0;break;case"inputMessagesFilterDocument":y.messageMediaDocument=!0;break;case"inputMessagesFilterAudio":y.messageMediaAudio=!0}for(g=0;g=v)));g++);}if(c.length=v));g++);}return c.length||1e3==l?(d&&(rt=listMergeSorted(rt,c)),e.when({count:null,history:c})):p.invokeApi("messages.search",{peer:t,q:n||"",filter:i||{_:"inputMessagesFilterEmpty"},min_date:0,max_date:0,limit:l||20,max_id:a||0}).then(function(e){o.saveApiUsers(e.users),r.saveApiChats(e.chats),D(e.messages);var t=e.count||e.messages.length;return c=[],angular.forEach(e.messages,function(e){c.push(e.id)}),d&&(rt=listMergeSorted(rt,c)),{count:t,history:c}})}function x(e){return G[e]||{deleted:!0}}function A(e){return p.invokeApi("messages.deleteMessages",{id:e}).then(function(e){return a.processUpdateMessage({_:"updateShort",update:{_:"updateDeleteMessages",messages:e}}),e})}function T(t,n,i){return a.processUpdateMessage({_:"updates",seq:n.seq,updates:[]})?n.offset?p.invokeApi(i,{peer:t,offset:n.offset,max_id:0,read_contents:!0}).then(function(e){return T(t,e,i)}):e.when():!1}function E(e){var n=s.getPeerID(e),i=X[n],a=z(n);if(!a[0]||!a[0].unread_count){if(!i||!i.history.length)return!1;var o,r,l=!1;for(c=i.history.length;c>=0;c--)if(o=i.history[c],r=G[o],r&&!r.out&&r.unread){l=!0;break}if(!l)return!1}if(i.readPromise)return i.readPromise;if(i.readPromise=p.invokeApi("messages.readHistory",{peer:e,offset:0,max_id:0,read_contents:!0}).then(function(t){return T(e,t,"messages.readHistory")}).then(function(){a[0]&&(a[0].unread_count=0,t.$broadcast("dialog_unread",{peerID:n,count:0}),t.$broadcast("messages_read"))})["finally"](function(){delete i.readPromise}),i&&i.history.length){var o,r,c,n,a;for(c=0;c=0?(r="photo",l="photo."+i.type.split("/")[1]):"video/"==i.type.substr(0,6)?(r="video",l="video.mp4"):"audio/"==i.type.substr(0,6)?(r="audio",l="audio."+("ogg"==i.type.split("/")[1]?"ogg":"mp3")):(r="document",l="document."+i.type.split("/")[1]):(r="document",l="document."+i.type.split("/")[1]),void 0===h&&(h=X[n]={count:null,history:[],pending:[]}),p.getUserID().then(function(o){var g={_:"messageMediaPending",type:r,file_name:i.name||l,size:i.size,progress:{percent:1,total:i.size}},_={_:"message",id:c,from_id:o,to_id:s.getOutputPeer(n),flags:3,date:tsNow(!0)+st,message:"",media:g,random_id:u,pending:!0},y=function(e){var n=K[c];e?(_.error=!0,n&&(n.error=!0)):(delete _.error,n&&delete n.error),t.$broadcast("messages_pending")};_.send=function(){var o=e.defer();tt.then(function(){var e=!1,s=m.uploadFile(i);s.then(function(t){t.name=l,e=!0;var n;switch(r){case"photo":n={_:"inputMediaUploadedPhoto",file:t};break;case"video":n={_:"inputMediaUploadedVideo",file:t,duration:0,w:0,h:0,mime_type:i.type};break;case"audio":n={_:"inputMediaUploadedAudio",file:t,duration:0,mime_type:i.type};break;case"document":default:n={_:"inputMediaUploadedDocument",file:t,file_name:i.name,mime_type:i.type}}p.invokeApi("messages.sendMedia",{peer:f,media:n,random_id:d}).then(function(e){_.date=e.message.date,_.id=e.message.id,_.media=e.message.media,a.processUpdateMessage({_:"updates",users:e.users,chats:e.chats,seq:e.seq,updates:[{_:"updateMessageID",random_id:u,id:e.message.id},{_:"updateNewMessage",message:_,pts:e.pts}]})},function(){y(!0)})},function(){y(!0)},function(e){g.progress.done=e.done,g.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update",{peerID:n})}),g.progress.cancel=function(){e||(o.resolve(),s.cancel(),U(u))},s["finally"](function(){o.resolve()})}),tt=o.promise},D([_]),h.pending.unshift(c),t.$broadcast("history_append",{peerID:n,messageID:c,my:!0}),_.send()}),J[u]=[n,c]}function L(e,n){var i=nt--,o=[nextRandomInt(4294967295),nextRandomInt(4294967295)],r=bigint(o[0]).shiftLeft(32).add(bigint(o[1])).toString(),c=X[e],d=s.getInputPeerByID(e);void 0===c&&(c=X[e]={count:null,history:[],pending:[]}),p.getUserID().then(function(u){var m;switch(n._){case"inputMediaContact":m=angular.extend({},n,{_:"messageMediaContact"});break;case"inputMediaPhoto":m={photo:l.getPhoto(n.id.id)}}var h={_:"message",id:i,from_id:u,to_id:s.getOutputPeer(e),flags:3,date:tsNow(!0)+st,message:"",media:m,random_id:r,pending:!0},f=function(e){var n=K[i];e?(h.error=!0,n&&(n.error=!0)):(delete h.error,n&&delete n.error),t.$broadcast("messages_pending")};h.send=function(){p.invokeApi("messages.sendMedia",{peer:d,media:n,random_id:o}).then(function(e){h.date=e.message.date,h.id=e.message.id,h.media=e.message.media,a.processUpdateMessage({_:"updates",users:e.users,chats:e.chats,seq:e.seq,updates:[{_:"updateMessageID",random_id:r,id:e.message.id},{_:"updateNewMessage",message:h,pts:e.pts}]})},function(){f(!0)})},D([h]),c.pending.unshift(i),t.$broadcast("history_append",{peerID:e,messageID:i,my:!0}),h.send()}),J[r]=[e,i]}function O(e,t){return t=t.sort(),p.invokeApi("messages.forwardMessages",{peer:s.getInputPeerByID(e),id:t}).then(function(e){var t=[];angular.forEach(e.messages,function(n){t.push({_:"updateNewMessage",message:n,pts:e.pts})}),a.processUpdateMessage({_:"updates",users:e.users,chats:e.chats,seq:e.seq,updates:t})})}function U(e){var t=J[e];if(console.log("pending",e,t),t){var n,i=t[0],o=t[1],r=X[i];for(a.processUpdateMessage({_:"updateShort",update:{_:"updateDeleteMessages",messages:[o]}}),n=0;nt?t:e.out||2&e.flags?t:e.from_id}function q(e,t){var n=-1!=t;if(n&&void 0!==Z[e])return Z[e];var i=angular.copy(G[e])||{id:e};return i.fromUser=o.getUser(i.from_id),(i.chatID=i.to_id.chat_id)?(i.peerID=-i.chatID,i.peerData=r.getChat(i.chatID)):(i.peerID=i.out?i.to_id.user_id:i.from_id,i.peerData=o.getUser(i.peerID)),i.peerString=s.getPeerString(i.peerID),i.peerPhoto=s.getPeerPhoto(i.peerID,"User","Group"),i.unreadCount=t,"messageService"==i._&&i.action.user_id&&(i.action.user=o.getUser(i.action.user_id)),i.message&&i.message.length&&(i.richMessage=h.wrapRichText(i.message.substr(0,64),{noLinks:!0,noLinebreaks:!0})),i.dateText=ut(i.date),n&&(Z[e]=i),i}function H(e){if(void 0!==K[e])return K[e];var t=angular.copy(G[e])||{id:e};if(t.media&&void 0!==t.media.progress&&(t.media.progress=G[e].media.progress),t.media)switch(t.media._){case"messageMediaPhoto":t.media.photo=l.wrapForHistory(t.media.photo.id);break;case"messageMediaVideo":t.media.video=c.wrapForHistory(t.media.video.id);break;case"messageMediaDocument":t.media.document=d.wrapForHistory(t.media.document.id);break;case"messageMediaAudio":t.media.audio=u.wrapForHistory(t.media.audio.id);break;case"messageMediaContact":t.media.rFullName=h.wrapRichText(t.media.first_name+" "+(t.media.last_name||""),{noLinks:!0,noLinebreaks:!0});break;case"messageMediaEmpty":delete t.media}else if(t.action)switch(t.action._){case"messageActionChatEditPhoto":t.action.photo=l.wrapForHistory(t.action.photo.id);break;case"messageActionChatCreate":case"messageActionChatEditTitle":t.action.rTitle=h.wrapRichText(t.action.title,{noLinks:!0,noLinebreaks:!0})||w("chat_title_deleted")}return t.message&&t.message.length&&(t.richMessage=h.wrapRichText(t.message),Config.Navigator.mobile||(t.richUrlEmbed=h.extractExternalEmbed(t.message))),K[e]=t}function j(e,t){if(!e||!e.length)return!1;var n,i,a,o,r,s,l,c=0,d=e.length,u=d,p=!1,m=!Config.Mobile;for(t>0?u=Math.min(t,d):0>t&&(c=Math.max(0,u+t)),n=c;u>n;n++){if(o=e[n],i=Math.floor((o.date+W)/86400),l=r&&r.grouped,s=o.grouped,i===a?o.needDate&&(delete o.needDate,p=!0):(!n||r)&&(o.needDate||(o.needDate=!0,p=!0)),r&&o.from_id==r.from_id&&!r.fwd_from_id==!o.fwd_from_id&&!r.action&&!o.action&&o.date0?(c.title=(s.first_name||"")+(s.first_name&&s.last_name?" ":"")+(s.last_name||""),i=l,n=o.getUserString(a)):(c.title=(s.first_name||s.last_name||w("conversation_unknown_user_raw"))+" @ "+(r.getChat(-a).title||w("conversation_unknown_chat_raw")),i=r.getChatPhoto(-a,"Group"),n=r.getChatString(-a)),c.title=h.wrapPlainText(c.title),c.onclick=function(){t.$broadcast("history_focus",{peerString:n})},c.message=d,c.image=i.placeholder,c.key="msg"+e.id,c.tag=n,i.location&&!i.location.empty?m.downloadSmallFile(i.location,i.size).then(function(t){c.image=v.getUrl(t,"image/jpeg"),e.unread&&f.notify(c)}):f.notify(c)}var W,G={},K={},Z={},X={},Y={count:null,dialogs:[]},J={},Q={},et={},tt=e.when(),nt=-1,it=g.createIndex(),at={query:!1},ot={},rt=[],st=0,lt=tsNow(!0),ct=lt-lt%86400,dt=new Date;y.get("server_time_offset").then(function(e){e&&(st=e)});var ut=i("dateOrTime");return dt.setHours(0),dt.setMinutes(0),dt.setSeconds(0),W=ct-Math.floor(+dt/1e3),f.start(),window.navigator.mozSetMessageHandler&&window.navigator.mozSetMessageHandler("activity",function(e){var n=e.source;console.log(dT(),"Received activity",n.name,n.data),"share"===n.name&&n.data.blobs.length>0&&_.selectPeers({confirm_type:"EXT_SHARE_PEER"}).then(function(e){angular.forEach(e,function(e){var t=s.getPeerID(e);angular.forEach(n.data.blobs,function(e){N(t,e,{isMedia:!0})})}),1==e.length&&t.$broadcast("history_focus",{peerString:e[0]})})}),t.$on("apiUpdate",function(e,n){switch(n._){case"updateMessageID":Q[n.id]=n.random_id;break;case"updateNewMessage":var i=n.message,a=F(i),r=X[a];if(void 0!==r){{X[a].history[0]}if(-1!=X[a].history.indexOf(i.id))return!1;r.history.unshift(i.id),r.history.sort(function(e,t){return t-e})}else r=X[a]={count:null,history:[i.id],pending:[]};D([i]),i.out||o.forceUserOnline(i.from_id),null!==r.count&&r.count++;var l,c=Q[i.id];c&&((l=B(c,i))&&t.$broadcast("history_update",{peerID:a}),delete Q[i.id]),l||t.$broadcast("history_append",{peerID:a,messageID:i.id});var d,u=z(a);u.length?(d=u[0],Y.dialogs.splice(u[1],1)):d={peerID:a,unread_count:0,top_message:!1},!i.out&&i.unread&&d.unread_count++,d.top_message=i.id,g.indexObject(a,s.getPeerSearchText(a),it),Y.dialogs.unshift(d),t.$broadcast("dialogs_update",d),(Config.Mobile&&t.selectedPeerID!=a||t.idle.isIDLE)&&!i.out&&i.unread&&f.getPeerMuted(a).then(function(e){i.unread&&!e&&V(i)});break;case"updateReadMessages":var p,i,m,a,u,d,h={},_=!1;for(m=0;m0&&o.forceUserOnline(a):(u=z(a),u&&(h[a]=--u[0].unread_count),f.cancel("msg"+p)));angular.forEach(h,function(e,n){t.$broadcast("dialog_unread",{peerID:n,count:e})}),_&&t.$broadcast("messages_read");break;case"updateDeleteMessages":var p,i,m,a,u,d,y,h={},v={};for(m=0;mo&&(i=e,a=o)}),i}function d(e,t,n){return a.invokeApi("photos.getUserPhotos",{user_id:e,offset:0,limit:n||20,max_id:t||0}).then(function(e){r.saveApiUsers(e.users);for(var t=[],n=0;n800&&(i-=208);var r=c(n,i,a);r&&!r.preloaded&&(r.preloaded=!0,r.size?o.downloadFile(r.location.dc_id,{_:"inputFileLocation",volume_id:r.location.volume_id,local_id:r.location.local_id,secret:r.location.secret},r.size):o.downloadSmallFile(r.location))}}function p(e){return _[e]||{_:"photoEmpty"}}function m(e){var t=angular.copy(_[e])||{_:"photoEmpty"},n=Math.min(y-80,Config.Mobile?210:260),i=Math.min(v-100,Config.Mobile?210:260),a=c(t,n,i),o={placeholder:"img/placeholders/PhotoThumbConversation.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):(o.width=100,o.height=100),t.thumb=o,t}function h(e){var n=m(e),i=$(window).width()-(Config.Mobile?0:32),a=$(t).height()-(Config.Mobile?0:116);!Config.Mobile&&i>800&&(i-=208);var o=c(n,i,a),r={placeholder:"img/placeholders/PhotoThumbModal.gif"};if(r.width=i,r.height=a,o&&"photoSizeEmpty"!=o._){var s=calcImageInBox(o.w,o.h,i,a,!0);r.width=s.w,r.height=s.h,r.modalWidth=Math.max(r.width,Math.min(400,i)),r.location=o.location,r.size=o.size}return n.full=r,n}function f(t,n){if(!t||"0"===t)return!1;var a=i.$new(!0);a.photoID=t;var o="PhotoModalController";n&&n.p>0?(o="UserpicModalController",a.userID=n.p):n&&n.p<0?(o="ChatpicModalController",a.chatID=-n.p):n&&n.m>0&&(a.messageID=n.m);e.open({templateUrl:templateUrl("photo_modal"),windowTemplateUrl:templateUrl("media_modal_layout"),controller:o,scope:a,windowClass:"photo_modal_window"})}function g(e){var n=_[e],i="jpg",a="image/jpeg",r="photo"+e+"."+i,l=Math.max(screen.width||0,$(window).width()-36,800),d=Math.max(screen.height||0,$(t).height()-150,800),u=c(n,l,d),p={_:"inputFileLocation",volume_id:u.location.volume_id,local_id:u.location.local_id,secret:u.location.secret};s.chooseSave(r,i,a).then(function(e){e&&o.downloadFile(u.location.dc_id,p,u.size,{mime:a,toFileEntry:e}).then(function(){},function(e){console.log("photo download failed",e)})},function(){o.downloadFile(u.location.dc_id,p,u.size,{mime:a}).then(function(e){s.download(e,a,r)},function(e){console.log("photo download failed",e)})})}var _={},y=$(window).width(),v=$(window).height();return i.preloadPhoto=u,i.openPhoto=f,{savePhoto:l,preloadPhoto:u,getUserPhotos:d,getPhoto:p,choosePhotoSize:c,wrapForHistory:m,wrapForFull:h,openPhoto:f,downloadPhoto:g}}]).service("AppVideoManager",["$sce","$rootScope","$modal","$window","$timeout","MtpApiFileManager","AppUsersManager","FileManager",function(e,t,n,i,a,o,r,s){function l(e){f[e.id]=e,e.thumb&&"photoCachedSize"==e.thumb._&&(o.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!==g[e])return g[e];var t=angular.copy(f[e]),n=Math.min(_-80,Config.Mobile?210:150),i=Math.min(y-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,g[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 r=calcImageInBox(t.w,t.h,n,a);o.width=r.w,o.height=r.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=f[e],n=g[e]||t||{},i={_:"inputVideoFileLocation",id:e,access_hash:t.access_hash};void 0===n.downloaded&&o.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function m(n,i){var a=f[n],r=g[n]||a||{},l=a.mime_type||"video/ogg",c={_:"inputVideoFileLocation",id:n,access_hash:a.access_hash};r.progress={enabled:!r.downloaded,percent:1,total:a.size};var d=o.downloadFile(a.dc_id,c,a.size,{mime:l,toFileEntry:i});return d.then(function(t){s.getFileCorrectUrl(t,l).then(function(t){r.url=e.trustAsResourceUrl(t)}),delete r.progress,r.downloaded=!0,console.log("video save done")},function(e){console.log("video download failed",e),r.progress.enabled=!1},function(e){console.log("dl progress",e),r.progress.enabled=!0,r.progress.done=e.done,r.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update")}),r.progress.cancel=d.cancel,d}function h(e){{var t=f[e],n=t.mime_type||"video/mp4",i=n.split(".")[1]||"mp4",a="t_video"+e+"."+i;g[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 f={},g={},_=$(window).width(),y=$(window).height();return{saveVideo:l,wrapForHistory:c,wrapForFull:d,openVideo:u,updateVideoDownloaded:p,downloadVideo:m,saveVideoFile:h}}]).service("AppDocsManager",["$sce","$rootScope","$modal","$window","$timeout","$q","MtpApiFileManager","FileManager",function(e,t,n,i,a,o,r,s){function l(e){h[e.id]=e,e.thumb&&"photoCachedSize"==e.thumb._&&(r.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="image/gif"==t.mime_type,i="audio/"==t.mime_type.substr(0,6),a=n?Math.min(g-80,260):100,o=n?Math.min(_-100,260):100,r=t.thumb,s={width:a,height:o};return r&&"photoSizeEmpty"!=r._?(r.w/r.h>a/o?s.height=parseInt(r.h*a/r.w):(s.width=parseInt(r.w*o/r.h),s.width>a&&(s.height=parseInt(s.height*a/s.width),s.width=a)),s.location=r.location,s.size=r.size):s=!1,t.thumb=s,t.withPreview=!Config.Mobile&&t.mime_type.match(/^(image\/)/)?1:0,n&&t.thumb?t.isSpecial="gif":i&&(t.isSpecial="audio"),f[e]=t}function d(e){var t=h[e],n=f[e]||t||{},i={_:"inputDocumentFileLocation",id:e,access_hash:t.access_hash};void 0===n.downloaded&&r.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function u(n,i){var a=h[n],o=f[n]||a||{},l={_:"inputDocumentFileLocation",id:n,access_hash:a.access_hash};o.progress={enabled:!o.downloaded,percent:1,total:a.size};var c=r.downloadFile(a.dc_id,l,a.size,{mime:a.mime_type,toFileEntry:i});return c.then(function(t){s.getFileCorrectUrl(t,a.mime_type).then(function(t){o.url=e.trustAsResourceUrl(t)}),delete o.progress,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=c.cancel,c}function p(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 m(e){var t=h[e],n=(f[e]||t||{},(t.file_name.split(".",2)||[])[1]||"");s.chooseSave(t.file_name,n,t.mime_type).then(function(t){t&&u(e,t)},function(){u(e).then(function(e){s.download(e,t.mime_type,t.file_name)})})}var h={},f={},g=$(window).width(),_=$(window).height();return{saveDoc:l,wrapForHistory:c,updateDocDownloaded:d,downloadDoc:u,openDoc:p,saveDocFile:m}}]).service("AppAudioManager",["$sce","$rootScope","$modal","$window","$timeout","MtpApiFileManager","FileManager",function(e,t,n,i,a,o,r){function s(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&&o.getDownloadedFile(i,t.size).then(function(){n.downloaded=!0},function(){n.downloaded=!1})}function d(n,i){var a=p[n],s=m[n]||a||{},l=a.mime_type||"audio/ogg",c={_:"inputAudioFileLocation",id:n,access_hash:a.access_hash};s.progress={enabled:!s.downloaded,percent:1,total:a.size};var d=o.downloadFile(a.dc_id,c,a.size,{mime:l,toFileEntry:i});return d.then(function(t){r.getFileCorrectUrl(t,l).then(function(t){s.url=e.trustAsResourceUrl(t)}),delete s.progress,s.downloaded=!0,console.log("audio save done")},function(e){console.log("audio download failed",e),s.progress.enabled=!1},function(e){console.log("dl progress",e),s.progress.enabled=!0,s.progress.done=e.done,s.progress.percent=Math.max(1,Math.floor(100*e.done/e.total)),t.$broadcast("history_update")}),s.progress.cancel=d.cancel,d}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||{}}r.chooseSave(a,i,n).then(function(t){t&&d(e,t)},function(){d(e).then(function(e){r.download(e,n,a)})})}var p={},m={};return{saveAudio:s,wrapForHistory:l,updateAudioDownloaded:c,downloadAudio:d,saveAudioFile:u}}]).service("ApiUpdatesManager",["$rootScope","MtpNetworkerFactory","AppUsersManager","AppChatsManager","AppPeersManager","MtpApiManager",function(e,t,n,i,a,o){function r(){var e=f.seq+1,t=g[e];t&&(console.log(dT(),"pop pending update",e,t),l(t)&&delete g[e])}function s(){m||c()}function l(e){if(e.seq){if(!u(e.seq,e.seq_start))return g[e.seq_start||e.seq]=e,!1;e.date&&(f.date=e.date)}switch(e._){case"updatesTooLong":case"new_session_created":s();break;case"updateShort":d(e.update);break;case"updateShortMessage":if(!n.hasUser(e.from_id)){console.log("User not found",e.from_id,"getDiff"),s();break}d({_:"updateNewMessage",message:{_:"message",id:e.id,from_id:e.from_id,to_id:a.getOutputPeer(o.getUserID()),flags:1,date:e.date,message:e.message,media:{_:"messageMediaEmpty"}},pts:e.pts});break;case"updateShortChatMessage":if(!n.hasUser(e.from_id)||!i.hasChat(e.chat_id)){console.log("User or chat not found",e.from_id,e.chat_id,"getDiff"),s();break}d({_:"updateNewMessage",message:{_:"message",id:e.id,from_id:e.from_id,to_id:a.getOutputPeer(-e.chat_id),flags:1,date:e.date,message:e.message,media:{_:"messageMediaEmpty"}},pts:e.pts});break;case"updatesCombined":case"updates":n.saveApiUsers(e.users),i.saveApiChats(e.chats);for(var t,l,c,t=0;t=h.seqAwaiting&&(console.log(dT(),"cancel pending getDiff",h.seqAwaiting),clearTimeout(h.timeout),h=!1),!0}function c(){m=!0,h&&(clearTimeout(h.timeout),h=!1),o.invokeApi("updates.getDifference",{pts:f.pts,date:f.date,qts:0}).then(function(e){if("updates.differenceEmpty"==e._)return console.log(dT(),"apply empty diff",e.seq),f.date=e.date,f.seq=e.seq,m=!1,r(),!1;n.saveApiUsers(e.users),i.saveApiChats(e.chats),angular.forEach(e.other_updates,function(e){d(e)}),angular.forEach(e.new_messages,function(e){d({_:"updateNewMessage",message:e,pts:f.pts})});var t=e.intermediate_state||e.state;f.seq=t.seq,f.pts=t.pts,f.date=t.date,console.log(dT(),"apply diff",f.seq,f.pts),"updates.differenceSlice"==e._?c(!0):m=!1})}function d(t){t.pts&&(f.pts=t.pts),e.$broadcast("apiUpdate",t)}function u(e,t){return(t=t||e)?m?(console.log(dT(),"Seq decline",t),!1):t!=f.seq+1?(t>f.seq&&(console.warn(dT(),"Seq hole",t,h&&h.seqAwaiting),h||(h={seqAwaiting:t,timeout:setTimeout(function(){c()},5e3)})),!1):(f.seq=e,!0):!0}function p(){t.setUpdatesProcessor(l),o.invokeApi("updates.getState",{},{noErrorBox:!0}).then(function(e){f.seq=e.seq,f.pts=e.pts,f.date=e.date,setTimeout(function(){m=!1},1e3)})}var m=!0,h=!1,f={},g={};return{processUpdateMessage:l,attach:p}}]).service("RichTextProcessor",["$sce","$sanitize",function(e,t){function n(e){for(var t,n,i,a,o=0;o-1)return n=Math.floor(t/a),i=t%a,{category:o,row:n,column:i};return console.error("emoji not found in spritesheet",e),null}function i(i,a){if(!i||!i.length)return"";a=a||{},i=i.replace(/\ufe0f/g,"",i);for(var o,s,u,p=i,m=[],f=!1;o=p.match(h);)m.push(encodeEntities(p.substr(0,o.index))),o[3]?a.noLinks?m.push(o[1],encodeEntities(o[2]+o[3])):m.push(o[1],'',encodeEntities(o[2]+o[3]),""):o[4]?a.noLinks?m.push(encodeEntities(o[0])):o[6]?m.push('',encodeEntities(o[6]+o[7]),""):m.push('',encodeEntities(o[5]+"://"+o[7]),""):o[8]?m.push(a.noLinebreaks?" ":"
"):o[9]?(r=l[o[9]])&&(u=n(r))?(s=encodeEntities(c[r][1][0]),f=!0,m.push('',":",s,":")):m.push(encodeEntities(o[9])):o[11]&&(a.noLinks?m.push(o[10],encodeEntities(o[11])):m.push(o[10],'',encodeEntities(o[11]),"")),p=p.substr(o.index+o[0].length);return m.push(encodeEntities(p)),i=t(m.join("")),f&&(i=i.replace(//g,'')),e.trustAs("html",i)}function a(e){var t;if(t=e.match(f))return["youtube",t[1]];if(t=e.match(g))return["vimeo",t[1]];if(t=e.match(_))return["instagram",t[1]];if(t=e.match(y))return["vine",t[1]];if(t=e.match(w)){var n="explore,upload,pages,terms-of-use,mobile,jobs,imprint".split(",");if(-1==n.indexOf(t[1]))return["soundcloud",t[0]]}if(!Config.Modes.chrome_packed){if(t=e.match(v))return["twitter",t[0]];if(t=e.match(b))return["facebook",t[0]]}return!1}function o(e,t){if(u)return e;if(!e||!e.length)return"";t=t||{},e=e.replace(/\ufe0f/g,"",e);for(var n,i,a=e,e=[];n=a.match(h);)e.push(a.substr(0,n.index)),e.push(n[9]?(r=l[n[9]])&&(i=c[r][1][0])?":"+i+":":n[0]:n[0]),a=a.substr(n.index+n[0].length);return e.push(a),e.join("")}var r,s=[],l={},c=Config.Emoji,d=18,u=-1!=navigator.userAgent.search(/OS X|iPhone|iPad|iOS|Android/i);for(r in c)s.push(c[r][0]),l[c[r][0]]=r;var p="a-z\\u00c0-\\u00d6\\u00d8-\\u00f6\\u00f8-\\u00ff\\u0100-\\u024f\\u0253\\u0254\\u0256\\u0257\\u0259\\u025b\\u0263\\u0268\\u026f\\u0272\\u0289\\u028b\\u02bb\\u0300-\\u036f\\u1e00-\\u1eff\\u0400-\\u04ff\\u0500-\\u0527\\u2de0-\\u2dff\\ua640-\\ua69f\\u0591-\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7\\u05d0-\\u05ea\\u05f0-\\u05f4\\ufb1d-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufb4f\\u0610-\\u061a\\u0620-\\u065f\\u066e-\\u06d3\\u06d5-\\u06dc\\u06de-\\u06e8\\u06ea-\\u06ef\\u06fa-\\u06fc\\u06ff\\u0750-\\u077f\\u08a0\\u08a2-\\u08ac\\u08e4-\\u08fe\\ufb50-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\u200c\\u0e01-\\u0e3a\\u0e40-\\u0e4e\\u1100-\\u11ff\\u3130-\\u3185\\uA960-\\uA97F\\uAC00-\\uD7AF\\uD7B0-\\uD7FF\\u3003\\u3005\\u303b\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uff9f\\uffa1-\\uffdc",m="0-9._"+p,h=new RegExp("(^|\\s)((?:https?://)?telegram\\.me/|@)([a-zA-Z\\d_]{5,32})|((?:(ftp|https?)://|(?:mailto:)?([A-Za-z0-9._%+-]+@))(\\S*\\.\\S*[^\\s.;,(){}<>\"']))|(\\n)|("+s.join("|")+")|(^|\\s)(#["+m+"]{2,20})","i"),f=/(?:https?:\/\/)?(?:www\.)?youtu(?:|\.be|be\.com|\.b)(?:\/v\/|\/watch\\?v=|e\/|(?:\/\??#)?\/watch(?:.+)v=)(.{11})(?:\&[^\s]*)?/,g=/(?:https?:\/\/)?(?:www\.)?vimeo\.com\/(\d+)/,_=/https?:\/\/(?:instagr\.am\/p\/|instagram\.com\/p\/)([a-zA-Z0-9\-\_]+)/i,y=/https?:\/\/vine\.co\/v\/([a-zA-Z0-9\-\_]+)/i,v=/https?:\/\/twitter\.com\/.+?\/status\/\d+/i,b=/https?:\/\/(?:www\.)?facebook\.com\/.+?\/posts\/\d+/i,w=/https?:\/\/(?:soundcloud\.com|snd\.sc)\/([a-zA-Z0-9%\-\_]+)\/([a-zA-Z0-9%\-\_]+)/i;return{wrapRichText:i,wrapPlainText:o,extractExternalEmbed:a}}]).service("StatusManager",["$timeout","$rootScope","MtpApiManager","IdleManager",function(e,t,n){function i(){l||(l=!0,t.$watch("idle.isIDLE",o),t.$watch("offline",o))}function a(e){var i=tsNow();if(!(e&&!s||!e&&5e4>i-s||t.offline))return s=e?0:i,n.invokeApi("account.updateStatus",{offline:e},{noErrorBox:!0})}function o(){r&&e.cancel(r),t.idle.isIDLE?r=e(function(){a(!0)},5e3):(a(!1),r=e(o,6e4))}var r,s=0,l=!1;return{start:i}}]).service("NotificationsManager",["$rootScope","$window","$timeout","$interval","$q","_","MtpApiManager","AppPeersManager","IdleManager","Storage","AppRuntimeManager",function(e,t,n,i,a,o,r,s,l,c,d){function u(e){return void 0!==D[e]?D[e]:D[e]=r.invokeApi("account.getNotifySettings",{peer:{_:"inputNotifyPeer",peer:s.getInputPeerByID(e)}})}function p(e,t){D[e]=a.when(t)}function m(e,t){p(e,t);var n=angular.copy(t);return n._="inputPeerNotifySettings",r.invokeApi("account.updateNotifySettings",{peer:{_:"inputNotifyPeer",peer:s.getInputPeerByID(e)},settings:n})}function h(e){return u(e).then(function(e){return"peerNotifySettings"==e._&&1e3*e.mute_until>tsNow()})}function f(){if(w(),!x)return!1;"Notification"in window&&"granted"!==Notification.permission&&"denied"!==Notification.permission&&$(t).on("click",g);try{"onbeforeunload"in window&&$(t).on("beforeunload",b)}catch(e){}}function g(){Notification.requestPermission(),$(t).off("click",g)}function _(e){return Config.Navigator.ffos?e.image="https://raw.githubusercontent.com/zhukov/webogram/master/app/img/icons/icon60.png":e.image||(e.image="img/icons/icon60.png"),E++,c.get("notify_nosound","notify_volume").then(function(e){(!e[0]&&e[1]===!1||e[1]>0)&&y(e[1]||.5) }),!x||"Notification"in window&&"granted"!==Notification.permission?!1:void c.get("notify_nodesktop","notify_novibrate").then(function(t){if(t[0]){if(I&&!t[1])return void navigator.vibrate([200,100,200])}else{var n,i=++T,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(!C)return;window.external.msSiteModeClearIconOverlay(),window.external.msSiteModeSetIconOverlay("img/icons/icon16.png",e.title),window.external.msSiteModeActivate(),n={index:i}}n.onclick=function(){n.close(),d.focus(),b(),e.onclick&&e.onclick()},n.onclose=function(){delete A[a],b()},n.show&&n.show(),A[a]=n}})}function y(e){var t="img/sound_a.wav",n=$("#notify_sound").html('');n.find("audio")[0].volume=e}function v(e){var t=A[e];if(t){E>0&&E--;try{t.close?t.close():C&&t.index==T&&window.external.msSiteModeClearIconOverlay()}catch(n){}delete E[e]}}function b(){C?window.external.msSiteModeClearIconOverlay():angular.forEach(A,function(e){try{e.close&&e.close()}catch(t){}}),A={},E=0}function w(){if(U)return!1;if(navigator.push&&Config.Navigator.ffos&&Config.Modes.packed){var e=navigator.push.register();e.onsuccess=function(){clearTimeout(R),console.log(dT(),"Push registered",e.result),U=e.result,r.invokeApi("account.registerDevice",{token_type:4,token:U,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()),R=setTimeout(w,B),B=Math.min(3e4,1.5*B)}}}function k(){return I}navigator.vibrate=navigator.vibrate||navigator.mozVibrate||navigator.webkitVibrate;var C=!1;try{window.external&&window.external.msIsSiteMode()&&(C=!0)}catch(S){}var M,x=C||"Notification"in window||"mozNotification"in navigator,A={},T=0,E=0,I=!!navigator.vibrate,D={},P=$('link[rel="icon"]:first'),N=$(''),L=o.pluralize("page_title_pluralize_notifications"),O=document.title;e.$watch("idle.isIDLE",function(e){e||b(),Config.Navigator.mobile||(i.cancel(M),e?(O=document.title,M=i(function(){var e=tsNow();if(!E||e%2e3>1e3){document.title=O;var t=$('link[rel="icon"]:first');-1!=t.attr("href").indexOf("favicon_unread")&&t.replaceWith(P)}else document.title=L(E),$('link[rel="icon"]:first').replaceWith(N)},1e3)):(document.title=O,$('link[rel="icon"]:first').replaceWith(P)))}),e.$on("apiUpdate",function(e,t){switch(t._){case"updateNotifySettings":if("notifyPeer"==t.peer._){var n=s.getPeerID(t.peer.peer);p(n,t.notify_settings)}}});var U=!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),U=!1,w()})),{start:f,notify:_,cancel:v,clear:b,getPeerSettings:u,getPeerMuted:h,savePeerSettings:p,updatePeerSettings:m,getVibrateSupport:k,testSound:y};var B,R}]).service("ErrorService",["$rootScope","$modal","$window",function(e,t,n){function i(n,i){if(r>=1)return console.log("Skip error box, too many open",r,n,i),!1;i=i||{};var a=e.$new();angular.extend(a,n),r++;var o=t.open({templateUrl:templateUrl("error_modal"),scope:a,windowClass:i.windowClass||"error_modal_window"});return o.result["finally"](function(){r--}),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 r=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,n&&angular.extend(i,n),t.open({templateUrl:templateUrl("peer_select"),controller:"PeerSelectController",scope:i,windowClass:"peer_select_window mobile_modal"}).result}function i(i){if(Config.Mobile)return n(i).then(function(e){return[e]});var a=e.$new();return a.multiSelect=!0,i&&angular.extend(a,i),t.open({templateUrl:templateUrl("peer_select"),controller:"PeerSelectController",scope:a,windowClass:"peer_select_window mobile_modal"}).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"}).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="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){t.set({current_layout:e?"mobile":"desktop",layout_confirmed:{width:$(window).width(),mobile:e}}).then(function(){n.reload()})}function o(n){if(!l){var i=$(window).width();if(!(!n&&Config.Mobile&&800>=i)){var o=600>i;o!=Config.Mobile&&t.get("layout_confirmed").then(function(n){return n&&(n.mobile?i==n.width:i==n.width)?!1:(l=!0,void e.confirm({type:o?"SWITCH_MOBILE_VERSION":"SWITCH_DESKTOP_VERSION"}).then(function(){t.remove("layout_confirmed"),a(o)},function(){t.set({layout_confirmed:{width:i,mobile:Config.Mobile}}),l=!1}))})}}}function r(){s||Config.Navigator.mobile||(s=!0,o(),$(i).on("resize",o))}var s=!1,l=!1;return{start:r,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=$("