diff --git a/README.md b/README.md index 5647511c..fad6c340 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) [![Stories in Ready](https://badge.waffle.io/zhukov/webogram.png?label=ready&title=Ready)](https://waffle.io/zhukov/webogram) + ## [Webogram](https://web.telegram.org) — Telegram Web App Telegram offers great [apps for mobile communication](https://www.telegram.org). It is based on the [MTProto protocol](https://core.telegram.org/mtproto) and has an [Open API](https://core.telegram.org/api). I personally like Telegram for its speed and cloud-support (that makes a web app possible, unlike in the case of WA and others). diff --git a/app/js/app.js b/app/js/app.js index 9b17cf55..b0a19ec7 100644 --- a/app/js/app.js +++ b/app/js/app.js @@ -5,14 +5,13 @@ * https://github.com/zhukov/webogram/blob/master/LICENSE */ -'use strict'; +'use strict' -var extraModules = []; +var extraModules = [] if (Config.Modes.animations) { - extraModules.push('ngAnimate'); + extraModules.push('ngAnimate') } - // Declare app level module which depends on filters, and services angular.module('myApp', [ 'ngRoute', @@ -31,23 +30,20 @@ angular.module('myApp', [ PRODUCTION_ONLY_END*/ 'myApp.directives', 'myApp.controllers' -].concat(extraModules)). -config(['$locationProvider', '$routeProvider', '$compileProvider', 'StorageProvider', function($locationProvider, $routeProvider, $compileProvider, StorageProvider) { - - $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob|filesystem|chrome-extension|app):|data:image\//); - $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|file|tg|mailto|blob|filesystem|chrome-extension|app):|data:/); +].concat(extraModules)).config(['$locationProvider', '$routeProvider', '$compileProvider', 'StorageProvider', function ($locationProvider, $routeProvider, $compileProvider, StorageProvider) { + $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob|filesystem|chrome-extension|app):|data:image\//) + $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|file|tg|mailto|blob|filesystem|chrome-extension|app):|data:/) /*PRODUCTION_ONLY_BEGIN - $compileProvider.debugInfoEnabled(false); + $compileProvider.debugInfoEnabled(false) PRODUCTION_ONLY_END*/ if (Config.Modes.test) { - StorageProvider.setPrefix('t_'); + StorageProvider.setPrefix('t_') } - $routeProvider.when('/', {templateUrl: templateUrl('welcome'), controller: 'AppWelcomeController'}); - $routeProvider.when('/login', {templateUrl: templateUrl('login'), controller: 'AppLoginController'}); - $routeProvider.when('/im', {templateUrl: templateUrl('im'), controller: 'AppIMController', reloadOnSearch: false}); - $routeProvider.otherwise({redirectTo: '/'}); - -}]); + $routeProvider.when('/', {templateUrl: templateUrl('welcome'), controller: 'AppWelcomeController'}) + $routeProvider.when('/login', {templateUrl: templateUrl('login'), controller: 'AppLoginController'}) + $routeProvider.when('/im', {templateUrl: templateUrl('im'), controller: 'AppIMController', reloadOnSearch: false}) + $routeProvider.otherwise({redirectTo: '/'}) +}]) diff --git a/app/js/background.js b/app/js/background.js index 8889dd88..1cce2a98 100644 --- a/app/js/background.js +++ b/app/js/background.js @@ -5,9 +5,9 @@ * https://github.com/zhukov/webogram/blob/master/LICENSE */ -chrome.app.runtime.onLaunched.addListener(function(launchData) { +chrome.app.runtime.onLaunched.addListener(function (launchData) { chrome.app.window.create('../index.html', { - id: 'webogram-chat', + id: 'webogram-chat', innerBounds: { width: 1000, height: 700 @@ -15,5 +15,5 @@ chrome.app.runtime.onLaunched.addListener(function(launchData) { minWidth: 320, minHeight: 400, frame: 'chrome' - }); -}); + }) +}) diff --git a/app/js/controllers.js b/app/js/controllers.js index 04e1a9fc..a054bb8c 100644 --- a/app/js/controllers.js +++ b/app/js/controllers.js @@ -5,58 +5,57 @@ * https://github.com/zhukov/webogram/blob/master/LICENSE */ -'use strict'; +'use strict' /* Controllers */ angular.module('myApp.controllers', ['myApp.i18n']) - .controller('AppWelcomeController', function($scope, $location, MtpApiManager, ErrorService, ChangelogNotifyService, LayoutSwitchService) { + .controller('AppWelcomeController', function ($scope, $location, MtpApiManager, ErrorService, ChangelogNotifyService, LayoutSwitchService) { MtpApiManager.getUserID().then(function (id) { if (id) { - $location.url('/im'); - return; + $location.url('/im') + return } if (location.protocol == 'http:' && - !Config.Modes.http && - Config.App.domains.indexOf(location.hostname) != -1) { - location.href = location.href.replace(/^http:/, 'https:'); - return; + !Config.Modes.http && + Config.App.domains.indexOf(location.hostname) != -1) { + location.href = location.href.replace(/^http:/, 'https:') + return } - $location.url('/login'); - }); + $location.url('/login') + }) - ChangelogNotifyService.checkUpdate(); - LayoutSwitchService.start(); + ChangelogNotifyService.checkUpdate() + LayoutSwitchService.start() }) .controller('AppLoginController', function ($scope, $rootScope, $location, $timeout, $modal, $modalStack, MtpApiManager, ErrorService, NotificationsManager, PasswordManager, ChangelogNotifyService, IdleManager, LayoutSwitchService, TelegramMeWebService, _) { - - $modalStack.dismissAll(); - IdleManager.start(); + $modalStack.dismissAll() + IdleManager.start() MtpApiManager.getUserID().then(function (id) { if (id) { - $location.url('/im'); - return; + $location.url('/im') + return } if (location.protocol == 'http:' && - !Config.Modes.http && - Config.App.domains.indexOf(location.hostname) != -1) { - location.href = location.href.replace(/^http:/, 'https:'); - return; + !Config.Modes.http && + Config.App.domains.indexOf(location.hostname) != -1) { + location.href = location.href.replace(/^http:/, 'https:') + return } - TelegramMeWebService.setAuthorized(false); - }); + TelegramMeWebService.setAuthorized(false) + }) - var options = {dcID: 2, createNetworker: true}, - countryChanged = false, - selectedCountry = false; + var options = {dcID: 2, createNetworker: true} + var countryChanged = false + var selectedCountry = false - $scope.credentials = {phone_country: '', phone_country_name: '', phone_number: '', phone_full: ''}; - $scope.progress = {}; - $scope.nextPending = {}; - $scope.about = {}; + $scope.credentials = {phone_country: '', phone_country_name: '', phone_number: '', phone_full: ''} + $scope.progress = {} + $scope.nextPending = {} + $scope.about = {} $scope.chooseCountry = function () { var modal = $modal.open({ @@ -64,127 +63,126 @@ angular.module('myApp.controllers', ['myApp.i18n']) controller: 'CountrySelectModalController', windowClass: 'countries_modal_window mobile_modal', backdrop: 'single' - }); + }) - modal.result.then(selectCountry); - }; + modal.result.then(selectCountry) + } function initPhoneCountry () { - var langCode = (navigator.language || '').toLowerCase(), - countryIso2 = Config.LangCountries[langCode], - shouldPregenerate = !Config.Navigator.mobile; + var langCode = (navigator.language || '').toLowerCase() + var countryIso2 = Config.LangCountries[langCode] + var shouldPregenerate = !Config.Navigator.mobile if (['en', 'en-us', 'en-uk'].indexOf(langCode) == -1) { if (countryIso2 !== undefined) { - selectPhoneCountryByIso2(countryIso2); + selectPhoneCountryByIso2(countryIso2) } else if (langCode.indexOf('-') > 0) { - selectPhoneCountryByIso2(langCode.split('-')[1].toUpperCase()); + selectPhoneCountryByIso2(langCode.split('-')[1].toUpperCase()) } else { - selectPhoneCountryByIso2('US'); + selectPhoneCountryByIso2('US') } } else { - selectPhoneCountryByIso2('US'); + selectPhoneCountryByIso2('US') } if (!shouldPregenerate) { - return; + return } - var wasCountry = $scope.credentials.phone_country; + var wasCountry = $scope.credentials.phone_country MtpApiManager.invokeApi('help.getNearestDc', {}, {dcID: 2, createNetworker: true}).then(function (nearestDcResult) { if (wasCountry == $scope.credentials.phone_country) { - selectPhoneCountryByIso2(nearestDcResult.country); + selectPhoneCountryByIso2(nearestDcResult.country) } if (nearestDcResult.nearest_dc != nearestDcResult.this_dc) { - MtpApiManager.getNetworker(nearestDcResult.nearest_dc, {createNetworker: true}); + MtpApiManager.getNetworker(nearestDcResult.nearest_dc, {createNetworker: true}) } - }); + }) } function selectPhoneCountryByIso2 (countryIso2) { if (countryIso2) { - var i, country; + var i, country for (i = 0; i < Config.CountryCodes.length; i++) { - country = Config.CountryCodes[i]; + country = Config.CountryCodes[i] if (country[0] == countryIso2) { - return selectCountry({name: _(country[1] + '_raw'), code: country[2]}); + return selectCountry({name: _(country[1] + '_raw'), code: country[2]}) } } } - return selectCountry({name: _('country_select_modal_country_us_raw'), code: '+1'}); + return selectCountry({name: _('country_select_modal_country_us_raw'), code: '+1'}) } function selectCountry (country) { - selectedCountry = country; + selectedCountry = country if ($scope.credentials.phone_country != country.code) { - $scope.credentials.phone_country = country.code; + $scope.credentials.phone_country = country.code } else { - updateCountry(); + updateCountry() } - $scope.$broadcast('country_selected'); - $scope.$broadcast('value_updated'); + $scope.$broadcast('country_selected') + $scope.$broadcast('value_updated') } function updateCountry () { var phoneNumber = ( - ($scope.credentials.phone_country || '') + - ($scope.credentials.phone_number || '') + ($scope.credentials.phone_country || '') + + ($scope.credentials.phone_number || '') ).replace(/\D+/g, ''), - i, j, code, - maxLength = 0, - maxName = false; + i, j, code + var maxLength = 0 + var maxName = false if (phoneNumber.length) { if (selectedCountry && !phoneNumber.indexOf(selectedCountry.code.replace(/\D+/g, ''))) { - maxName = selectedCountry.name; + maxName = selectedCountry.name } else { for (i = 0; i < Config.CountryCodes.length; i++) { for (j = 2; j < Config.CountryCodes[i].length; j++) { - code = Config.CountryCodes[i][j].replace(/\D+/g, ''); + code = Config.CountryCodes[i][j].replace(/\D+/g, '') if (code.length > maxLength && !phoneNumber.indexOf(code)) { - maxLength = code.length; - maxName = _(Config.CountryCodes[i][1] + '_raw'); + maxLength = code.length + maxName = _(Config.CountryCodes[i][1] + '_raw') } } } } } - $scope.credentials.phone_full = phoneNumber; - $scope.credentials.phone_country_name = maxName || _('login_controller_unknown_country_raw'); - }; - - $scope.$watch('credentials.phone_country', updateCountry); - $scope.$watch('credentials.phone_number', updateCountry); - initPhoneCountry(); + $scope.credentials.phone_full = phoneNumber + $scope.credentials.phone_country_name = maxName || _('login_controller_unknown_country_raw') + } + $scope.$watch('credentials.phone_country', updateCountry) + $scope.$watch('credentials.phone_number', updateCountry) + initPhoneCountry() - var nextTimeout; - var updatePasswordTimeout = false; + var nextTimeout + var updatePasswordTimeout = false function saveAuth (result) { MtpApiManager.setUserAuth(options.dcID, { id: result.user.id - }); - $timeout.cancel(nextTimeout); + }) + $timeout.cancel(nextTimeout) - $location.url('/im'); - }; + $location.url('/im') + } $scope.sendCode = function () { - $timeout.cancel(nextTimeout); + $timeout.cancel(nextTimeout) ErrorService.confirm({ type: 'LOGIN_PHONE_CORRECT', country_code: $scope.credentials.phone_country, phone_number: $scope.credentials.phone_number }).then(function () { - $scope.progress.enabled = true; + $scope.progress.enabled = true onContentLoaded(function () { - $scope.$broadcast('ui_height'); - }); + $scope.$broadcast('ui_height') + }) - var authKeyStarted = tsNow(); + var authKeyStarted = tsNow() MtpApiManager.invokeApi('auth.sendCode', { flags: 0, phone_number: $scope.credentials.phone_full, @@ -192,21 +190,20 @@ angular.module('myApp.controllers', ['myApp.i18n']) api_hash: Config.App.hash, lang_code: navigator.language || 'en' }, options).then(function (sentCode) { - $scope.progress.enabled = false; - - $scope.error = {}; - $scope.about = {}; - $scope.credentials.phone_code_hash = sentCode.phone_code_hash; - applySentCode(sentCode); + $scope.progress.enabled = false + $scope.error = {} + $scope.about = {} + $scope.credentials.phone_code_hash = sentCode.phone_code_hash + applySentCode(sentCode) }, function (error) { - $scope.progress.enabled = false; - console.log('sendCode error', error); + $scope.progress.enabled = false + console.log('sendCode error', error) switch (error.type) { case 'PHONE_NUMBER_INVALID': - $scope.error = {field: 'phone'}; - error.handled = true; - break; + $scope.error = {field: 'phone'} + error.handled = true + break } })['finally'](function () { if ($rootScope.idle.isIDLE || tsNow() - authKeyStarted > 60000) { @@ -214,272 +211,267 @@ angular.module('myApp.controllers', ['myApp.i18n']) title: 'Telegram', message: 'Your authorization key was successfully generated! Open the app to log in.', tag: 'auth_key' - }); + }) } - }); - }); + }) + }) } - function applySentCode(sentCode) { - $scope.credentials.type = sentCode.type; - $scope.nextPending.type = sentCode.next_type || false; - $scope.nextPending.remaining = sentCode.timeout || false; + function applySentCode (sentCode) { + $scope.credentials.type = sentCode.type + $scope.nextPending.type = sentCode.next_type || false + $scope.nextPending.remaining = sentCode.timeout || false - nextTimeoutCheck(); + nextTimeoutCheck() onContentLoaded(function () { - $scope.$broadcast('ui_height'); - }); + $scope.$broadcast('ui_height') + }) } $scope.sendNext = function () { if (!$scope.nextPending.type || - $scope.nextPending.remaining > 0) { - return; + $scope.nextPending.remaining > 0) { + return } MtpApiManager.invokeApi('auth.resendCode', { phone_number: $scope.credentials.phone_full, phone_code_hash: $scope.credentials.phone_code_hash - }, options).then(applySentCode); + }, options).then(applySentCode) } function nextTimeoutCheck () { - $timeout.cancel(nextTimeout); + $timeout.cancel(nextTimeout) if (!$scope.nextPending.type || - $scope.nextPending.remaining === false) { - return; + $scope.nextPending.remaining === false) { + return } if (!(--$scope.nextPending.remaining)) { - $scope.nextPending.success = false; - $scope.sendNext(); + $scope.nextPending.success = false + $scope.sendNext() } else { - nextTimeout = $timeout(nextTimeoutCheck, 1000); + nextTimeout = $timeout(nextTimeoutCheck, 1000) } } $scope.editPhone = function () { - $timeout.cancel(nextTimeout); + $timeout.cancel(nextTimeout) if ($scope.credentials.phone_full && - $scope.credentials.phone_code_hash) { + $scope.credentials.phone_code_hash) { MtpApiManager.invokeApi('auth.cancelCode', { phone_number: $scope.credentials.phone_full, phone_code_hash: $scope.credentials.phone_code_hash - }, options); + }, options) } - delete $scope.credentials.phone_code_hash; - delete $scope.credentials.phone_unoccupied; - delete $scope.credentials.phone_code_valid; - delete $scope.nextPending.remaining; - delete $scope.nextPending.success; + delete $scope.credentials.phone_code_hash + delete $scope.credentials.phone_unoccupied + delete $scope.credentials.phone_code_valid + delete $scope.nextPending.remaining + delete $scope.nextPending.success } $scope.$watch('credentials.phone_code', function (newVal) { if (newVal && - newVal.match(/^\d+$/) && - $scope.credentials.type && - $scope.credentials.type.length && - newVal.length == $scope.credentials.type.length) { - $scope.logIn(); + newVal.match(/^\d+$/) && + $scope.credentials.type && + $scope.credentials.type.length && + newVal.length == $scope.credentials.type.length) { + $scope.logIn() } - }); + }) $scope.logIn = function (forceSignUp) { - var method = 'auth.signIn', params = { + var method = 'auth.signIn' + var params = { phone_number: $scope.credentials.phone_full, phone_code_hash: $scope.credentials.phone_code_hash, phone_code: $scope.credentials.phone_code - }; + } if (forceSignUp) { - method = 'auth.signUp'; + method = 'auth.signUp' angular.extend(params, { first_name: $scope.credentials.first_name || '', last_name: $scope.credentials.last_name || '' - }); + }) } - $scope.progress.enabled = true; + $scope.progress.enabled = true MtpApiManager.invokeApi(method, params, options).then(saveAuth, function (error) { - $scope.progress.enabled = false; + $scope.progress.enabled = false if (error.code == 400 && error.type == 'PHONE_NUMBER_UNOCCUPIED') { - error.handled = true; - $scope.credentials.phone_code_valid = true; - $scope.credentials.phone_unoccupied = true; - $scope.about = {}; - return; + error.handled = true + $scope.credentials.phone_code_valid = true + $scope.credentials.phone_unoccupied = true + $scope.about = {} + return } else if (error.code == 400 && error.type == 'PHONE_NUMBER_OCCUPIED') { - error.handled = true; - return $scope.logIn(false); + error.handled = true + return $scope.logIn(false) } else if (error.code == 401 && error.type == 'SESSION_PASSWORD_NEEDED') { - $scope.progress.enabled = true; + $scope.progress.enabled = true updatePasswordState().then(function () { - $scope.progress.enabled = false; - $scope.credentials.phone_code_valid = true; - $scope.credentials.password_needed = true; - $scope.about = {}; - }); - error.handled = true; - return; + $scope.progress.enabled = false + $scope.credentials.phone_code_valid = true + $scope.credentials.password_needed = true + $scope.about = {} + }) + error.handled = true + return } - switch (error.type) { case 'FIRSTNAME_INVALID': - $scope.error = {field: 'first_name'}; - error.handled = true; - break; + $scope.error = {field: 'first_name'} + error.handled = true + break case 'LASTNAME_INVALID': - $scope.error = {field: 'last_name'}; - error.handled = true; - break; + $scope.error = {field: 'last_name'} + error.handled = true + break case 'PHONE_CODE_INVALID': - $scope.error = {field: 'phone_code'}; - delete $scope.credentials.phone_code_valid; - error.handled = true; - break; + $scope.error = {field: 'phone_code'} + delete $scope.credentials.phone_code_valid + error.handled = true + break case 'PHONE_CODE_EXPIRED': - $scope.editPhone(); - error.handled = true; - break; + $scope.editPhone() + error.handled = true + break } - }); - - }; + }) + } $scope.checkPassword = function () { return PasswordManager.check($scope.password, $scope.credentials.password, options).then(saveAuth, function (error) { switch (error.type) { case 'PASSWORD_HASH_INVALID': - $scope.error = {field: 'password'}; - error.handled = true; - break; + $scope.error = {field: 'password'} + error.handled = true + break } - }); - }; + }) + } $scope.forgotPassword = function (event) { PasswordManager.requestRecovery($scope.password, options).then(function (emailRecovery) { - - var scope = $rootScope.$new(); - scope.recovery = emailRecovery; - scope.options = options; + var scope = $rootScope.$new() + scope.recovery = emailRecovery + scope.options = options var modal = $modal.open({ scope: scope, templateUrl: templateUrl('password_recovery_modal'), controller: 'PasswordRecoveryModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); + }) modal.result.then(function (result) { if (result && result.user) { - saveAuth(result); + saveAuth(result) } else { - $scope.canReset = true; + $scope.canReset = true } - }); - + }) }, function (error) { switch (error.type) { case 'PASSWORD_EMPTY': - $scope.logIn(); - error.handled = true; - break; + $scope.logIn() + error.handled = true + break case 'PASSWORD_RECOVERY_NA': $timeout(function () { - $scope.canReset = true; - }, 1000); - error.handled = true; - break; + $scope.canReset = true + }, 1000) + error.handled = true + break } }) - return cancelEvent(event); - }; + return cancelEvent(event) + } $scope.resetAccount = function () { ErrorService.confirm({ type: 'RESET_ACCOUNT' }).then(function () { - $scope.progress.enabled = true; + $scope.progress.enabled = true MtpApiManager.invokeApi('account.deleteAccount', { reason: 'Forgot password' }, options).then(function () { - delete $scope.progress.enabled; - delete $scope.credentials.password_needed; - $scope.credentials.phone_unoccupied = true; + delete $scope.progress.enabled + delete $scope.credentials.password_needed + $scope.credentials.phone_unoccupied = true }, function () { - delete $scope.progress.enabled; + delete $scope.progress.enabled }) - }); - }; + }) + } function updatePasswordState () { - // $timeout.cancel(updatePasswordTimeout); - // updatePasswordTimeout = false; + // $timeout.cancel(updatePasswordTimeout) + // updatePasswordTimeout = false return PasswordManager.getState(options).then(function (result) { - return $scope.password = result; - // if (result._ == 'account.noPassword' && result.email_unconfirmed_pattern) { - // updatePasswordTimeout = $timeout(updatePasswordState, 5000); - // } - }); + return $scope.password = result + // if (result._ == 'account.noPassword' && result.email_unconfirmed_pattern) { + // updatePasswordTimeout = $timeout(updatePasswordState, 5000) + // } + }) } - ChangelogNotifyService.checkUpdate(); - LayoutSwitchService.start(); + ChangelogNotifyService.checkUpdate() + LayoutSwitchService.start() }) .controller('AppIMController', function ($q, qSync, $scope, $location, $routeParams, $modal, $rootScope, $modalStack, MtpApiManager, AppUsersManager, AppChatsManager, AppMessagesManager, AppPeersManager, ContactsSelectService, ChangelogNotifyService, ErrorService, AppRuntimeManager, HttpsMigrateService, LayoutSwitchService, LocationParamsService, AppStickersManager) { + $scope.$on('$routeUpdate', updateCurDialog) - $scope.$on('$routeUpdate', updateCurDialog); - - var pendingParams = false; - var pendingAttachment = false; + var pendingParams = false + var pendingAttachment = false $scope.$on('history_focus', function (e, peerData) { - $modalStack.dismissAll(); + $modalStack.dismissAll() if (peerData.peerString == $scope.curDialog.peer && - peerData.messageID == $scope.curDialog.messageID && - !peerData.startParam) { + peerData.messageID == $scope.curDialog.messageID && + !peerData.startParam) { if (peerData.messageID) { - $scope.$broadcast('ui_history_change_scroll', true); + $scope.$broadcast('ui_history_change_scroll', true) } else { - $scope.$broadcast('ui_history_focus'); + $scope.$broadcast('ui_history_focus') } } else { - var peerID = AppPeersManager.getPeerID(peerData.peerString); - var username = AppPeersManager.getPeer(peerID).username; - var peer = username ? '@' + username : peerData.peerString; + var peerID = AppPeersManager.getPeerID(peerData.peerString) + var username = AppPeersManager.getPeer(peerID).username + var peer = username ? '@' + username : peerData.peerString if (peerData.messageID || peerData.startParam) { pendingParams = { messageID: peerData.messageID, startParam: peerData.startParam - }; + } } else { - pendingParams = false; + pendingParams = false } if (peerData.attachment) { - pendingAttachment = peerData.attachment; + pendingAttachment = peerData.attachment } if ($routeParams.p != peer) { - $location.url('/im?p=' + peer); + $location.url('/im?p=' + peer) } else { - updateCurDialog(); + updateCurDialog() } } - }); + }) $scope.$on('esc_no_more', function () { $rootScope.$apply(function () { - $location.url('/im'); + $location.url('/im') }) - }); - + }) - $scope.isLoggedIn = true; - $scope.isEmpty = {}; - $scope.search = {}; - $scope.historyFilter = {mediaType: false}; - $scope.historyPeer = {}; + $scope.isLoggedIn = true + $scope.isEmpty = {} + $scope.search = {} + $scope.historyFilter = {mediaType: false} + $scope.historyPeer = {} $scope.historyState = { selectActions: false, botActions: false, @@ -487,12 +479,12 @@ angular.module('myApp.controllers', ['myApp.i18n']) canReply: false, canDelete: false, actions: function () { - return $scope.historyState.selectActions ? 'selected' : ($scope.historyState.botActions ? 'bot' : ($scope.historyState.channelActions ? 'channel' : false)); + return $scope.historyState.selectActions ? 'selected' : ($scope.historyState.botActions ? 'bot' : ($scope.historyState.channelActions ? 'channel' : false)) }, typing: [], missedCount: 0, skipped: false - }; + } $scope.openSettings = function () { $modal.open({ @@ -500,37 +492,46 @@ angular.module('myApp.controllers', ['myApp.i18n']) controller: 'SettingsModalController', windowClass: 'settings_modal_window mobile_modal', backdrop: 'single' - }); - }; + }) + } - // setTimeout($scope.openSettings, 1000); + // setTimeout($scope.openSettings, 1000) $scope.openFaq = function () { - var url = 'https://telegram.org/faq'; + var url = 'https://telegram.org/faq' switch (Config.I18n.locale) { - case 'es-es': url += '/es'; break; - case 'it-it': url += '/it'; break; - case 'de-de': url += '/de'; break; - case 'ko-ko': url += '/ko'; break; - case 'pt-br': url += '/br'; break; - }; - window.open(url, '_blank'); - }; + case 'es-es': + url += '/es' + break + case 'it-it': + url += '/it' + break + case 'de-de': + url += '/de' + break + case 'ko-ko': + url += '/ko' + break + case 'pt-br': + url += '/br' + break + } + window.open(url, '_blank') + } $scope.openContacts = function () { ContactsSelectService.selectContact().then(function (userID) { - $scope.dialogSelect(AppUsersManager.getUserString(userID)); - }); - }; + $scope.dialogSelect(AppUsersManager.getUserString(userID)) + }) + } $scope.openGroup = function () { ContactsSelectService.selectContacts({action: 'new_group'}).then(function (userIDs) { - if (userIDs.length == 1) { - $scope.dialogSelect(AppUsersManager.getUserString(userIDs[0])); + $scope.dialogSelect(AppUsersManager.getUserString(userIDs[0])) } else if (userIDs.length > 1) { - var scope = $rootScope.$new(); - scope.userIDs = userIDs; + var scope = $rootScope.$new() + scope.userIDs = userIDs $modal.open({ templateUrl: templateUrl('chat_create_modal'), @@ -538,54 +539,53 @@ angular.module('myApp.controllers', ['myApp.i18n']) scope: scope, windowClass: 'md_simple_modal_window mobile_modal', backdrop: 'single' - }); + }) } - - }); - }; + }) + } $scope.importContact = function () { AppUsersManager.openImportContact().then(function (foundContact) { if (foundContact) { $rootScope.$broadcast('history_focus', { peerString: AppUsersManager.getUserString(foundContact) - }); + }) } - }); - }; + }) + } $scope.searchClear = function () { - $scope.search.query = ''; - $scope.$broadcast('search_clear'); + $scope.search.query = '' + $scope.$broadcast('search_clear') } $scope.dialogSelect = function (peerString, messageID) { - var params = {peerString: peerString}; + var params = {peerString: peerString} if (messageID) { - params.messageID = messageID; + params.messageID = messageID } else if ($scope.search.query) { - $scope.searchClear(); + $scope.searchClear() } - var peerID = AppPeersManager.getPeerID(peerString); - var converted = AppMessagesManager.convertMigratedPeer(peerID); + var peerID = AppPeersManager.getPeerID(peerString) + var converted = AppMessagesManager.convertMigratedPeer(peerID) if (converted) { - params.peerString = AppPeersManager.getPeerString(converted); + params.peerString = AppPeersManager.getPeerString(converted) } - $rootScope.$broadcast('history_focus', params); - }; + $rootScope.$broadcast('history_focus', params) + } $scope.logOut = function () { ErrorService.confirm({type: 'LOGOUT'}).then(function () { MtpApiManager.logOut().then(function () { - location.hash = '/login'; - AppRuntimeManager.reload(); - }); + location.hash = '/login' + AppRuntimeManager.reload() + }) }) - }; + } $scope.openChangelog = function () { - ChangelogNotifyService.showChangelog(false); + ChangelogNotifyService.showChangelog(false) } $scope.showPeerInfo = function () { @@ -594,208 +594,206 @@ angular.module('myApp.controllers', ['myApp.i18n']) } else if ($scope.curDialog.peerID < 0) { AppChatsManager.openChat(-$scope.curDialog.peerID) } - }; + } $scope.toggleEdit = function () { - $scope.$broadcast('history_edit_toggle'); - }; + $scope.$broadcast('history_edit_toggle') + } $scope.selectedFlush = function () { - $scope.$broadcast('history_edit_flush'); - }; + $scope.$broadcast('history_edit_flush') + } $scope.toggleMedia = function (mediaType) { - $scope.$broadcast('history_media_toggle', mediaType); - }; + $scope.$broadcast('history_media_toggle', mediaType) + } $scope.returnToRecent = function () { - $scope.$broadcast('history_return_recent'); - }; + $scope.$broadcast('history_return_recent') + } $scope.toggleSearch = function () { - $scope.$broadcast('dialogs_search_toggle'); - }; + $scope.$broadcast('dialogs_search_toggle') + } - updateCurDialog(); + updateCurDialog() - function updateCurDialog() { - var addParams = pendingParams || {}; - pendingParams = false; - addParams.messageID = parseInt(addParams.messageID) || false; - addParams.startParam = addParams.startParam; + function updateCurDialog () { + var addParams = pendingParams || {} + pendingParams = false + addParams.messageID = parseInt(addParams.messageID) || false + addParams.startParam = addParams.startParam - var peerStringPromise; + var peerStringPromise if ($routeParams.p && $routeParams.p.charAt(0) == '@') { if ($scope.curDialog === undefined) { $scope.curDialog = { peer: '', peerID: 0 - }; + } } peerStringPromise = AppPeersManager.resolveUsername($routeParams.p.substr(1)).then(function (peerID) { - return qSync.when(AppPeersManager.getPeerString(peerID)); - }); + return qSync.when(AppPeersManager.getPeerString(peerID)) + }) } else { - peerStringPromise = qSync.when($routeParams.p); + peerStringPromise = qSync.when($routeParams.p) } peerStringPromise.then(function (peerString) { $scope.curDialog = angular.extend({ peer: peerString, peerID: AppPeersManager.getPeerID(peerString || '') - }, addParams); + }, addParams) if (pendingAttachment) { - $scope.$broadcast('peer_draft_attachment', pendingAttachment); - pendingAttachment = false; + $scope.$broadcast('peer_draft_attachment', pendingAttachment) + pendingAttachment = false } - }); + }) } - ChangelogNotifyService.checkUpdate(); - HttpsMigrateService.start(); - LayoutSwitchService.start(); - LocationParamsService.start(); - AppStickersManager.start(); + ChangelogNotifyService.checkUpdate() + HttpsMigrateService.start() + LayoutSwitchService.start() + LocationParamsService.start() + AppStickersManager.start() }) .controller('AppImDialogsController', function ($scope, $location, $q, $timeout, $routeParams, MtpApiManager, AppUsersManager, AppChatsManager, AppMessagesManager, AppProfileManager, AppPeersManager, PhonebookContactsService, ErrorService, AppRuntimeManager) { - - $scope.dialogs = []; - $scope.contacts = []; - $scope.foundPeers = []; - $scope.foundMessages = []; + $scope.dialogs = [] + $scope.contacts = [] + $scope.foundPeers = [] + $scope.foundMessages = [] if ($scope.search === undefined) { - $scope.search = {}; + $scope.search = {} } if ($scope.isEmpty === undefined) { - $scope.isEmpty = {}; + $scope.isEmpty = {} } - $scope.phonebookAvailable = PhonebookContactsService.isAvailable(); - - var searchMessages = false; - var offsetIndex = 0; - var maxID = 0; - var hasMore = false; - var jump = 0; - var contactsJump = 0; - var peersInDialogs = {}; - var typingTimeouts = {}; - var contactsShown; + $scope.phonebookAvailable = PhonebookContactsService.isAvailable() + + var searchMessages = false + var offsetIndex = 0 + var maxID = 0 + var hasMore = false + var jump = 0 + var contactsJump = 0 + var peersInDialogs = {} + var typingTimeouts = {} + var contactsShown $scope.$on('dialogs_need_more', function () { - // console.log('on need more'); - showMoreDialogs(); - }); + // console.log('on need more') + showMoreDialogs() + }) $scope.$on('dialog_unread', function (e, dialog) { - angular.forEach($scope.dialogs, function(curDialog) { + angular.forEach($scope.dialogs, function (curDialog) { if (curDialog.peerID == dialog.peerID) { - curDialog.unreadCount = dialog.count; + curDialog.unreadCount = dialog.count } - }); - }); + }) + }) $scope.$on('dialogs_multiupdate', function (e, dialogsUpdated) { if ($scope.search.query !== undefined && $scope.search.query.length) { - return false; + return false } - var indexes = []; - var indexesToDialogs = {}; + var indexes = [] + var indexesToDialogs = {} angular.forEach(dialogsUpdated, function (dialog, peerID) { if ($scope.noUsers && peerID > 0) { - return; + return } - indexesToDialogs[dialog.index] = dialog; - indexes.push(dialog.index); - }); - indexes.sort(); + indexesToDialogs[dialog.index] = dialog + indexes.push(dialog.index) + }) + indexes.sort() - var i, dialog; - var len = $scope.dialogs.length; + var i, dialog + var len = $scope.dialogs.length for (i = 0; i < len; i++) { - dialog = $scope.dialogs[i]; + dialog = $scope.dialogs[i] if (dialogsUpdated[dialog.peerID]) { - $scope.dialogs.splice(i, 1); - i--; - len--; - AppMessagesManager.clearDialogCache(dialog.mid); + $scope.dialogs.splice(i, 1) + i-- + len-- + AppMessagesManager.clearDialogCache(dialog.mid) } } - len = indexes.length; + len = indexes.length for (i = 0; i < len; i++) { - dialog = indexesToDialogs[indexes[i]]; + dialog = indexesToDialogs[indexes[i]] $scope.dialogs.unshift( AppMessagesManager.wrapForDialog(dialog.top_message, dialog) - ); + ) } - delete $scope.isEmpty.dialogs; + delete $scope.isEmpty.dialogs if (!peersInDialogs[dialog.peerID]) { - peersInDialogs[dialog.peerID] = true; + peersInDialogs[dialog.peerID] = true if (contactsShown) { - showMoreConversations(); + showMoreConversations() } } - - }); + }) function deleteDialog (peerID) { for (var i = 0; i < $scope.dialogs.length; i++) { if ($scope.dialogs[i].peerID == peerID) { - $scope.dialogs.splice(i, 1); - break; + $scope.dialogs.splice(i, 1) + break } } } $scope.$on('dialog_top', function (e, dialog) { - var curDialog, i; + var curDialog, i for (i = 0; i < $scope.dialogs.length; i++) { - curDialog = $scope.dialogs[i]; + curDialog = $scope.dialogs[i] if (curDialog.peerID == dialog.peerID) { - var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, dialog); - $scope.dialogs.splice(i, 1, wrappedDialog); - break; + var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, dialog) + $scope.dialogs.splice(i, 1, wrappedDialog) + break } } - }); + }) $scope.$on('dialog_flush', function (e, update) { - var curDialog, i; + var curDialog, i for (i = 0; i < $scope.dialogs.length; i++) { - curDialog = $scope.dialogs[i]; + curDialog = $scope.dialogs[i] if (curDialog.peerID == update.peerID) { - curDialog.deleted = true; - break; + curDialog.deleted = true + break } } - }); + }) $scope.$on('dialog_drop', function (e, dialog) { - deleteDialog(dialog.peerID); - }); + deleteDialog(dialog.peerID) + }) $scope.$on('draft_updated', function (e, draftUpdate) { - var curDialog, i; + var curDialog, i for (i = 0; i < $scope.dialogs.length; i++) { - curDialog = $scope.dialogs[i]; + curDialog = $scope.dialogs[i] if (curDialog.peerID == draftUpdate.peerID) { - curDialog.draft = draftUpdate.draft; + curDialog.draft = draftUpdate.draft if (i > 0 && draftUpdate.draft) { - $scope.dialogs.splice(i, 1); - $scope.dialogs.unshift(curDialog); + $scope.dialogs.splice(i, 1) + $scope.dialogs.unshift(curDialog) } - break; + break } } - }); + }) $scope.$on('history_delete', function (e, historyUpdate) { for (var i = 0; i < $scope.dialogs.length; i++) { if ($scope.dialogs[i].peerID == historyUpdate.peerID) { if (historyUpdate.msgs[$scope.dialogs[i].mid]) { - $scope.dialogs[i].deleted = true; + $scope.dialogs[i].deleted = true } - break; + break } } - }); + }) $scope.$on('apiUpdate', function (e, update) { switch (update._) { @@ -803,815 +801,803 @@ angular.module('myApp.controllers', ['myApp.i18n']) case 'updateChatUserTyping': if (!AppUsersManager.hasUser(update.user_id)) { if (update.chat_id && - AppChatsManager.hasChat(update.chat_id) && - !AppChatsManager.isChannel(update.chat_id)) { - AppProfileManager.getChatFull(update.chat_id); + AppChatsManager.hasChat(update.chat_id) && + !AppChatsManager.isChannel(update.chat_id)) { + AppProfileManager.getChatFull(update.chat_id) } - return; + return } - var peerID = update._ == 'updateUserTyping'? update.user_id : -update.chat_id; - AppUsersManager.forceUserOnline(update.user_id); + var peerID = update._ == 'updateUserTyping' ? update.user_id : -update.chat_id + AppUsersManager.forceUserOnline(update.user_id) for (var i = 0; i < $scope.dialogs.length; i++) { if ($scope.dialogs[i].peerID == peerID) { - $scope.dialogs[i].typing = update.user_id; - $timeout.cancel(typingTimeouts[peerID]); + $scope.dialogs[i].typing = update.user_id + $timeout.cancel(typingTimeouts[peerID]) typingTimeouts[peerID] = $timeout(function () { for (var i = 0; i < $scope.dialogs.length; i++) { if ($scope.dialogs[i].peerID == peerID) { if ($scope.dialogs[i].typing == update.user_id) { - delete $scope.dialogs[i].typing; + delete $scope.dialogs[i].typing } } } - }, 6000); - break; + }, 6000) + break } } - break; + break } - }); + }) $scope.$watchCollection('search', function () { - $scope.dialogs = []; - $scope.foundMessages = []; - searchMessages = false; - contactsJump++; - loadDialogs(); - }); + $scope.dialogs = [] + $scope.foundMessages = [] + searchMessages = false + contactsJump++ + loadDialogs() + }) if (Config.Mobile) { $scope.$watch('curDialog.peer', function () { $scope.$broadcast('ui_dialogs_update') - }); + }) } $scope.importPhonebook = function () { - PhonebookContactsService.openPhonebookImport(); - }; + PhonebookContactsService.openPhonebookImport() + } $scope.$on('contacts_update', function () { if (contactsShown) { - showMoreConversations(); + showMoreConversations() } - }); + }) - $scope.$on('ui_dialogs_search_clear', $scope.searchClear); + $scope.$on('ui_dialogs_search_clear', $scope.searchClear) if (!$scope.noMessages) { $scope.$on('dialogs_search', function (e, data) { - $scope.search.query = data.query || ''; - $scope.toggleSearch(); - }); + $scope.search.query = data.query || '' + $scope.toggleSearch() + }) } - var searchTimeoutPromise; - function getDialogs(force) { - var curJump = ++jump; + var searchTimeoutPromise + function getDialogs (force) { + var curJump = ++jump - $timeout.cancel(searchTimeoutPromise); + $timeout.cancel(searchTimeoutPromise) if (searchMessages) { - searchTimeoutPromise = (force || maxID) ? $q.when() : $timeout(angular.noop, 500); + searchTimeoutPromise = (force || maxID) ? $q.when() : $timeout(angular.noop, 500) return searchTimeoutPromise.then(function () { return AppMessagesManager.getSearch(false, $scope.search.query, {_: 'inputMessagesFilterEmpty'}, maxID).then(function (result) { if (curJump != jump) { - return $q.reject(); + return $q.reject() } - var dialogs = []; + var dialogs = [] angular.forEach(result.history, function (messageID) { - var message = AppMessagesManager.getMessage(messageID), - peerID = AppMessagesManager.getMessagePeer(message); + var message = AppMessagesManager.getMessage(messageID) + var peerID = AppMessagesManager.getMessagePeer(message) dialogs.push({ peerID: peerID, top_message: messageID, unread_count: -1 - }); - }); + }) + }) return { dialogs: dialogs - }; + } }) - }); + }) } - var query = $scope.search.query || ''; + var query = $scope.search.query || '' if ($scope.noUsers) { - query = '%pg ' + query; + query = '%pg ' + query } return AppMessagesManager.getConversations(query, offsetIndex).then(function (result) { if (curJump != jump) { - return $q.reject(); + return $q.reject() } - return result; - }); - }; + return result + }) + } function loadDialogs (force) { - offsetIndex = 0; - maxID = 0; - hasMore = false; + offsetIndex = 0 + maxID = 0 + hasMore = false if (!searchMessages) { - peersInDialogs = {}; - contactsShown = false; + peersInDialogs = {} + contactsShown = false } getDialogs(force).then(function (dialogsResult) { if (!searchMessages) { - $scope.dialogs = []; - $scope.contacts = []; - $scope.foundPeers = []; + $scope.dialogs = [] + $scope.contacts = [] + $scope.foundPeers = [] } - $scope.foundMessages = []; + $scope.foundMessages = [] - var dialogsList = searchMessages ? $scope.foundMessages : $scope.dialogs; + var dialogsList = searchMessages ? $scope.foundMessages : $scope.dialogs if (dialogsResult.dialogs.length) { angular.forEach(dialogsResult.dialogs, function (dialog) { if ($scope.canSend && - AppPeersManager.isChannel(dialog.peerID) && - !AppChatsManager.hasRights(-dialog.peerID, 'send')) { - return; + AppPeersManager.isChannel(dialog.peerID) && + !AppChatsManager.hasRights(-dialog.peerID, 'send')) { + return } - var wrapDialog = searchMessages ? undefined : dialog; - var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, wrapDialog); + var wrapDialog = searchMessages ? undefined : dialog + var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, wrapDialog) if (searchMessages) { - wrappedDialog.unreadCount = -1; + wrappedDialog.unreadCount = -1 } else { - peersInDialogs[dialog.peerID] = true; + peersInDialogs[dialog.peerID] = true } - dialogsList.push(wrappedDialog); - }); + dialogsList.push(wrappedDialog) + }) if (searchMessages) { - maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message; + maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message } else { - offsetIndex = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].index; - delete $scope.isEmpty.dialogs; + offsetIndex = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].index + delete $scope.isEmpty.dialogs } - hasMore = true; + hasMore = true } else { - hasMore = false; + hasMore = false } - $scope.$broadcast('ui_dialogs_change'); + $scope.$broadcast('ui_dialogs_change') if (!$scope.search.query) { - AppMessagesManager.getConversations('', offsetIndex, 100); + AppMessagesManager.getConversations('', offsetIndex, 100) if (!dialogsResult.dialogs.length) { - $scope.isEmpty.dialogs = true; - showMoreDialogs(); + $scope.isEmpty.dialogs = true + showMoreDialogs() } } else { - showMoreDialogs(); + showMoreDialogs() } - - }); + }) } function showMoreDialogs () { if (contactsShown && (!hasMore || !offsetIndex && !maxID)) { - return; + return } if (!hasMore && - !searchMessages && - !$scope.noUsers && - ($scope.search.query || !$scope.dialogs.length)) { - showMoreConversations(); - return; + !searchMessages && + !$scope.noUsers && + ($scope.search.query || !$scope.dialogs.length)) { + showMoreConversations() + return } getDialogs().then(function (dialogsResult) { if (dialogsResult.dialogs.length) { - var dialogsList = searchMessages ? $scope.foundMessages : $scope.dialogs; + var dialogsList = searchMessages ? $scope.foundMessages : $scope.dialogs angular.forEach(dialogsResult.dialogs, function (dialog) { if ($scope.canSend && - AppPeersManager.isChannel(dialog.peerID) && - !AppChatsManager.hasRights(-dialog.peerID, 'send')) { - return; + AppPeersManager.isChannel(dialog.peerID) && + !AppChatsManager.hasRights(-dialog.peerID, 'send')) { + return } - var wrapDialog = searchMessages ? undefined : dialog; - var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, wrapDialog); + var wrapDialog = searchMessages ? undefined : dialog + var wrappedDialog = AppMessagesManager.wrapForDialog(dialog.top_message, wrapDialog) if (searchMessages) { - wrappedDialog.unreadCount = -1; + wrappedDialog.unreadCount = -1 } else { - peersInDialogs[dialog.peerID] = true; + peersInDialogs[dialog.peerID] = true } - dialogsList.push(wrappedDialog); - }); + dialogsList.push(wrappedDialog) + }) if (searchMessages) { - maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message; + maxID = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].top_message } else { - offsetIndex = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].index; + offsetIndex = dialogsResult.dialogs[dialogsResult.dialogs.length - 1].index } - $scope.$broadcast('ui_dialogs_append'); + $scope.$broadcast('ui_dialogs_append') - hasMore = true; + hasMore = true + }else { + hasMore = false } - else { - hasMore = false; - } - }); - }; + }) + } function showMoreConversations () { - contactsShown = true; + contactsShown = true - var curJump = ++contactsJump; + var curJump = ++contactsJump AppUsersManager.getContacts($scope.search.query).then(function (contactsList) { - if (curJump != contactsJump) return; - $scope.contacts = []; - angular.forEach(contactsList, function(userID) { + if (curJump != contactsJump) return + $scope.contacts = [] + angular.forEach(contactsList, function (userID) { if (peersInDialogs[userID] === undefined) { $scope.contacts.push({ userID: userID, user: AppUsersManager.getUser(userID), peerString: AppUsersManager.getUserString(userID) - }); + }) } - }); + }) if (contactsList.length) { - delete $scope.isEmpty.contacts; + delete $scope.isEmpty.contacts } else if (!$scope.search.query) { - $scope.isEmpty.contacts = true; + $scope.isEmpty.contacts = true } - $scope.$broadcast('ui_dialogs_append'); - }); + $scope.$broadcast('ui_dialogs_append') + }) if ($scope.search.query && $scope.search.query.length >= 5) { - $timeout(function() { - if (curJump != contactsJump) return; + $timeout(function () { + if (curJump != contactsJump) return MtpApiManager.invokeApi('contacts.search', {q: $scope.search.query, limit: 10}).then(function (result) { - AppUsersManager.saveApiUsers(result.users); - AppChatsManager.saveApiChats(result.chats); - if (curJump != contactsJump) return; - $scope.foundPeers = []; - angular.forEach(result.results, function(contactFound) { - var peerID = AppPeersManager.getPeerID(contactFound); + AppUsersManager.saveApiUsers(result.users) + AppChatsManager.saveApiChats(result.chats) + if (curJump != contactsJump) return + $scope.foundPeers = [] + angular.forEach(result.results, function (contactFound) { + var peerID = AppPeersManager.getPeerID(contactFound) if (peersInDialogs[peerID] === undefined) { if ($scope.canSend && - AppPeersManager.isChannel(peerID) && - !AppChatsManager.hasRights(-peerID, 'send')) { - return; + AppPeersManager.isChannel(peerID) && + !AppChatsManager.hasRights(-peerID, 'send')) { + return } $scope.foundPeers.push({ id: peerID, username: AppPeersManager.getPeer(peerID).username, peerString: AppUsersManager.getUserString(peerID) - }); + }) } - }); + }) }, function (error) { if (error.code == 400) { - error.handled = true; + error.handled = true } - }); - }, 500); + }) + }, 500) } if ($scope.search.query && !$scope.noMessages) { - searchMessages = true; - loadDialogs(); + searchMessages = true + loadDialogs() } } - }) .controller('AppImHistoryController', function ($scope, $location, $timeout, $modal, $rootScope, toaster, _, MtpApiManager, AppUsersManager, AppChatsManager, AppMessagesManager, AppPeersManager, ApiUpdatesManager, PeersSelectService, IdleManager, StatusManager, NotificationsManager, ErrorService, GeoLocationManager) { - - $scope.$watchCollection('curDialog', applyDialogSelect); - - ApiUpdatesManager.attach(); - IdleManager.start(); - StatusManager.start(); - - $scope.peerHistories = []; - $scope.selectedMsgs = {}; - $scope.selectedCount = 0; - $scope.historyState.selectActions = false; - $scope.historyState.botActions = false; - $scope.historyState.channelActions = false; - $scope.historyState.canDelete = false; - $scope.historyState.canReply = false; - $scope.historyState.missedCount = 0; - $scope.historyState.skipped = false; - $scope.state = {}; - - $scope.toggleMessage = toggleMessage; - $scope.selectedDelete = selectedDelete; - $scope.selectedForward = selectedForward; - $scope.selectedReply = selectedReply; - $scope.selectedCancel = selectedCancel; - $scope.selectedFlush = selectedFlush; - $scope.selectInlineBot = selectInlineBot; - - $scope.startBot = startBot; - $scope.cancelBot = cancelBot; - $scope.joinChannel = joinChannel; - $scope.togglePeerMuted = togglePeerMuted; - - - $scope.toggleEdit = toggleEdit; - $scope.toggleMedia = toggleMedia; - $scope.returnToRecent = returnToRecent; - - $scope.$on('history_edit_toggle', toggleEdit); - $scope.$on('history_edit_flush', selectedFlush); + $scope.$watchCollection('curDialog', applyDialogSelect) + + ApiUpdatesManager.attach() + IdleManager.start() + StatusManager.start() + + $scope.peerHistories = [] + $scope.selectedMsgs = {} + $scope.selectedCount = 0 + $scope.historyState.selectActions = false + $scope.historyState.botActions = false + $scope.historyState.channelActions = false + $scope.historyState.canDelete = false + $scope.historyState.canReply = false + $scope.historyState.missedCount = 0 + $scope.historyState.skipped = false + $scope.state = {} + + $scope.toggleMessage = toggleMessage + $scope.selectedDelete = selectedDelete + $scope.selectedForward = selectedForward + $scope.selectedReply = selectedReply + $scope.selectedCancel = selectedCancel + $scope.selectedFlush = selectedFlush + $scope.selectInlineBot = selectInlineBot + + $scope.startBot = startBot + $scope.cancelBot = cancelBot + $scope.joinChannel = joinChannel + $scope.togglePeerMuted = togglePeerMuted + + $scope.toggleEdit = toggleEdit + $scope.toggleMedia = toggleMedia + $scope.returnToRecent = returnToRecent + + $scope.$on('history_edit_toggle', toggleEdit) + $scope.$on('history_edit_flush', selectedFlush) $scope.$on('history_media_toggle', function (e, mediaType) { - toggleMedia(mediaType); - }); - - - $scope.$on('history_return_recent', returnToRecent); - - var peerID, - peerHistory = false, - unreadAfterIdle = false, - hasMore = false, - hasLess = false, - maxID = 0, - minID = 0, - lastSelectID = false, - inputMediaFilters = { - photos: 'inputMessagesFilterPhotos', - video: 'inputMessagesFilterVideo', - documents: 'inputMessagesFilterDocument', - audio: 'inputMessagesFilterVoice' - }, - jump = 0, - moreJump = 0, - moreActive = false, - morePending = false, - lessJump = 0, - lessActive = false, - lessPending = false; + toggleMedia(mediaType) + }) + + $scope.$on('history_return_recent', returnToRecent) + + var peerID + var peerHistory = false + var unreadAfterIdle = false + var hasMore = false + var hasLess = false + var maxID = 0 + var minID = 0 + var lastSelectID = false + var inputMediaFilters = { + photos: 'inputMessagesFilterPhotos', + video: 'inputMessagesFilterVideo', + documents: 'inputMessagesFilterDocument', + audio: 'inputMessagesFilterVoice' + } + var jump = 0 + var moreJump = 0 + var moreActive = false + var morePending = false + var lessJump = 0, + lessActive = false, + lessPending = false function applyDialogSelect (newDialog, oldDialog) { - peerID = $rootScope.selectedPeerID = newDialog.peerID; - $scope.historyFilter.mediaType = false; + peerID = $rootScope.selectedPeerID = newDialog.peerID + $scope.historyFilter.mediaType = false - AppPeersManager.getInputPeer(newDialog.peer || $scope.curDialog.peer || ''); + AppPeersManager.getInputPeer(newDialog.peer || $scope.curDialog.peer || '') - updateBotActions(); - selectedCancel(true); + updateBotActions() + selectedCancel(true) if (oldDialog.peer && - oldDialog.peer == newDialog.peer && - newDialog.messageID) { - messageFocusHistory(); + oldDialog.peer == newDialog.peer && + newDialog.messageID) { + messageFocusHistory() } else if (peerID) { - updateHistoryPeer(true); - loadHistory(); - } - else { - showEmptyHistory(); + updateHistoryPeer(true) + loadHistory() + }else { + showEmptyHistory() } } function historiesQueuePush (peerID) { - var pos = -1, - maxLen = 10, - i, - history, - diff; + var pos = -1 + var maxLen = 10, + i, + history, + diff for (i = 0; i < $scope.peerHistories.length; i++) { if ($scope.peerHistories[i].peerID == peerID) { - pos = i; - break; + pos = i + break } } if (pos > -1) { - history = $scope.peerHistories[pos]; - return history; + history = $scope.peerHistories[pos] + return history } - history = {peerID: peerID, messages: [], ids: []}; - $scope.peerHistories.unshift(history); - diff = $scope.peerHistories.length - maxLen; + history = {peerID: peerID, messages: [], ids: []} + $scope.peerHistories.unshift(history) + diff = $scope.peerHistories.length - maxLen if (diff > 0) { - $scope.peerHistories.splice(maxLen - 1, diff); + $scope.peerHistories.splice(maxLen - 1, diff) } - return history; + return history } function historiesQueueFind (peerID) { - var i; + var i for (i = 0; i < $scope.peerHistories.length; i++) { if ($scope.peerHistories[i].peerID == peerID) { - return $scope.peerHistories[i]; + return $scope.peerHistories[i] } } - return false; + return false } function historiesQueuePop (peerID) { - var i; + var i for (i = 0; i < $scope.peerHistories.length; i++) { if ($scope.peerHistories[i].peerID == peerID) { - $scope.peerHistories.splice(i, 1); - return true; + $scope.peerHistories.splice(i, 1) + return true } } - return false; + return false } - function updateHistoryPeer(preload) { - var peerData = AppPeersManager.getPeer(peerID); - // console.log('update', preload, peerData); + function updateHistoryPeer (preload) { + var peerData = AppPeersManager.getPeer(peerID) + // console.log('update', preload, peerData) if (!peerData || peerData.deleted) { - safeReplaceObject($scope.state, {loaded: false}); - return false; + safeReplaceObject($scope.state, {loaded: false}) + return false } - peerHistory = historiesQueuePush(peerID); + peerHistory = historiesQueuePush(peerID) safeReplaceObject($scope.historyPeer, { id: peerID, data: peerData - }); + }) MtpApiManager.getUserID().then(function (myID) { - $scope.ownID = myID; - }); + $scope.ownID = myID + }) if (preload) { - $scope.historyState.typing.splice(0, $scope.historyState.typing.length); - $scope.$broadcast('ui_peer_change'); - $scope.$broadcast('ui_history_change'); - safeReplaceObject($scope.state, {loaded: true, empty: !peerHistory.messages.length, mayBeHasMore: true}); + $scope.historyState.typing.splice(0, $scope.historyState.typing.length) + $scope.$broadcast('ui_peer_change') + $scope.$broadcast('ui_history_change') + safeReplaceObject($scope.state, {loaded: true, empty: !peerHistory.messages.length, mayBeHasMore: true}) - updateBotActions(); - updateChannelActions(); + updateBotActions() + updateChannelActions() } } function updateBotActions () { - var wasBotActions = $scope.historyState.botActions; + var wasBotActions = $scope.historyState.botActions if (!peerID || - peerID < 0 || - !AppUsersManager.isBot(peerID) || - $scope.historyFilter.mediaType || - $scope.curDialog.messageID) { - $scope.historyState.botActions = false; + peerID < 0 || + !AppUsersManager.isBot(peerID) || + $scope.historyFilter.mediaType || + $scope.curDialog.messageID) { + $scope.historyState.botActions = false } else if ( $scope.state.empty || ( - peerHistory && - peerHistory.messages.length == 1 && - peerHistory.messages[0].action && - peerHistory.messages[0].action._ == 'messageActionBotIntro' + peerHistory && + peerHistory.messages.length == 1 && + peerHistory.messages[0].action && + peerHistory.messages[0].action._ == 'messageActionBotIntro' ) ) { - $scope.historyState.botActions = 'start'; + $scope.historyState.botActions = 'start' } else if ($scope.curDialog.startParam) { - $scope.historyState.botActions = 'param'; - } - else { - $scope.historyState.botActions = false; + $scope.historyState.botActions = 'param' + }else { + $scope.historyState.botActions = false } if (wasBotActions != $scope.historyState.botActions) { - $scope.$broadcast('ui_panel_update'); + $scope.$broadcast('ui_panel_update') } } function updateChannelActions () { - var wasChannelActions = $scope.historyState.channelActions; - var channel; + var wasChannelActions = $scope.historyState.channelActions + var channel if (peerID && - AppPeersManager.isChannel(peerID) && - (channel = AppChatsManager.getChat(-peerID))) { - - var canSend = AppChatsManager.hasRights(-peerID, 'send'); + AppPeersManager.isChannel(peerID) && + (channel = AppChatsManager.getChat(-peerID))) { + var canSend = AppChatsManager.hasRights(-peerID, 'send') if (!canSend) { if (channel.pFlags.left) { - $scope.historyState.channelActions = 'join'; + $scope.historyState.channelActions = 'join' } else { if (!$scope.historyState.channelActions) { - $scope.historyState.channelActions = 'mute'; + $scope.historyState.channelActions = 'mute' } NotificationsManager.getPeerMuted(peerID).then(function (muted) { - $scope.historyState.channelActions = muted ? 'unmute' : 'mute'; - }); + $scope.historyState.channelActions = muted ? 'unmute' : 'mute' + }) } } else { - $scope.historyState.channelActions = false; + $scope.historyState.channelActions = false } - $scope.historyState.canReply = canSend; - $scope.historyState.canDelete = canSend || channel.pFlags.moderator; - } - else { - $scope.historyState.channelActions = false; - $scope.historyState.canReply = true; - $scope.historyState.canDelete = true; + $scope.historyState.canReply = canSend + $scope.historyState.canDelete = canSend || channel.pFlags.moderator + }else { + $scope.historyState.channelActions = false + $scope.historyState.canReply = true + $scope.historyState.canDelete = true } if (wasChannelActions != $scope.historyState.channelActions) { - $scope.$broadcast('ui_panel_update'); + $scope.$broadcast('ui_panel_update') } } function messageFocusHistory () { - var history = historiesQueueFind(peerID); + var history = historiesQueueFind(peerID) if (history && - history.ids.indexOf($scope.curDialog.messageID) != -1) { - $scope.historyUnread = {}; - var focusedMsgID = $scope.curDialog.messageID || 0; - $scope.$broadcast('messages_focus', focusedMsgID); - $scope.$broadcast('ui_history_change_scroll', true); + history.ids.indexOf($scope.curDialog.messageID) != -1) { + $scope.historyUnread = {} + var focusedMsgID = $scope.curDialog.messageID || 0 + $scope.$broadcast('messages_focus', focusedMsgID) + $scope.$broadcast('ui_history_change_scroll', true) } else { - loadHistory(); + loadHistory() } } function showLessHistory () { if (!hasLess) { - return; + return } if (moreActive) { - lessPending = true; - return; + lessPending = true + return } - lessPending = false; - $scope.state.lessActive = lessActive = true; + lessPending = false + $scope.state.lessActive = lessActive = true - var curJump = jump, - curLessJump = ++lessJump, - limit = 0, - backLimit = 20; + var curJump = jump + var curLessJump = ++lessJump + var limit = 0 + var backLimit = 20 AppMessagesManager.getHistory($scope.curDialog.peerID, minID, limit, backLimit).then(function (historyResult) { - $scope.state.lessActive = lessActive = false; - if (curJump != jump || curLessJump != lessJump) return; + $scope.state.lessActive = lessActive = false + if (curJump != jump || curLessJump != lessJump) return - var i, id; + var i, id for (i = historyResult.history.length - 1; i >= 0; i--) { - id = historyResult.history[i]; + id = historyResult.history[i] if (id > minID) { - peerHistory.messages.push(AppMessagesManager.wrapForHistory(id)); - peerHistory.ids.push(id); + peerHistory.messages.push(AppMessagesManager.wrapForHistory(id)) + peerHistory.ids.push(id) } } if (historyResult.history.length) { minID = historyResult.history.length >= backLimit - ? historyResult.history[0] - : 0; + ? historyResult.history[0] + : 0 if (AppMessagesManager.regroupWrappedHistory(peerHistory.messages, -backLimit)) { - $scope.$broadcast('messages_regroup'); + $scope.$broadcast('messages_regroup') } - delete $scope.state.empty; - $scope.$broadcast('ui_history_append'); + delete $scope.state.empty + $scope.$broadcast('ui_history_append') } else { - minID = 0; + minID = 0 } - $scope.historyState.skipped = hasLess = minID > 0; + $scope.historyState.skipped = hasLess = minID > 0 if (morePending) { - showMoreHistory(); + showMoreHistory() } - }); + }) } function showMoreHistory () { if (!hasMore) { - return; + return } if (lessActive) { - morePending = true; - return; + morePending = true + return } - morePending = false; - $scope.state.moreActive = moreActive = true; + morePending = false + $scope.state.moreActive = moreActive = true - var curJump = jump, - curMoreJump = ++moreJump, - inputMediaFilter = $scope.historyFilter.mediaType && {_: inputMediaFilters[$scope.historyFilter.mediaType]}, - limit = Config.Mobile ? 20 : 0, - getMessagesPromise = inputMediaFilter + var curJump = jump + var curMoreJump = ++moreJump + var inputMediaFilter = $scope.historyFilter.mediaType && {_: inputMediaFilters[$scope.historyFilter.mediaType]} + var limit = Config.Mobile ? 20 : 0 + var getMessagesPromise = inputMediaFilter ? AppMessagesManager.getSearch($scope.curDialog.peerID, '', inputMediaFilter, maxID, limit) - : AppMessagesManager.getHistory($scope.curDialog.peerID, maxID, limit); + : AppMessagesManager.getHistory($scope.curDialog.peerID, maxID, limit) getMessagesPromise.then(function (historyResult) { - $scope.state.moreActive = moreActive = false; - if (curJump != jump || curMoreJump != moreJump) return; + $scope.state.moreActive = moreActive = false + if (curJump != jump || curMoreJump != moreJump) return angular.forEach(historyResult.history, function (id) { - peerHistory.messages.unshift(AppMessagesManager.wrapForHistory(id)); - peerHistory.ids.unshift(id); - }); + peerHistory.messages.unshift(AppMessagesManager.wrapForHistory(id)) + peerHistory.ids.unshift(id) + }) hasMore = historyResult.count === null || - historyResult.history.length && peerHistory.messages.length < historyResult.count; + historyResult.history.length && peerHistory.messages.length < historyResult.count if (historyResult.history.length) { - delete $scope.state.empty; - maxID = historyResult.history[historyResult.history.length - 1]; - $scope.$broadcast('ui_history_prepend'); + delete $scope.state.empty + maxID = historyResult.history[historyResult.history.length - 1] + $scope.$broadcast('ui_history_prepend') if (AppMessagesManager.regroupWrappedHistory(peerHistory.messages, historyResult.history.length + 1)) { - $scope.$broadcast('messages_regroup'); + $scope.$broadcast('messages_regroup') } } if (lessPending) { - showLessHistory(); + showLessHistory() } - }); - }; + }) + } function loadHistory (forceRecent) { - $scope.historyState.missedCount = 0; + $scope.historyState.missedCount = 0 - hasMore = false; - $scope.historyState.skipped = hasLess = false; - maxID = 0; - minID = 0; - peerHistory = historiesQueuePush(peerID); + hasMore = false + $scope.historyState.skipped = hasLess = false + maxID = 0 + minID = 0 + peerHistory = historiesQueuePush(peerID) - - var limit = 0, backLimit = 0; + var limit = 0 + var backLimit = 0 if ($scope.curDialog.messageID) { - maxID = parseInt($scope.curDialog.messageID); - limit = 20; - backLimit = 20; + maxID = parseInt($scope.curDialog.messageID) + limit = 20 + backLimit = 20 } else if (forceRecent) { - limit = 10; + limit = 10 } - $scope.state.moreActive = moreActive = false; - morePending = false; - $scope.state.lessActive = lessActive = false; - lessPending = false; + $scope.state.moreActive = moreActive = false + morePending = false + $scope.state.lessActive = lessActive = false + lessPending = false - var prerenderedLen = peerHistory.messages.length; + var prerenderedLen = peerHistory.messages.length if (prerenderedLen && (maxID || backLimit)) { - prerenderedLen = 0; - peerHistory.messages = []; - peerHistory.ids = []; - $scope.state.empty = true; + prerenderedLen = 0 + peerHistory.messages = [] + peerHistory.ids = [] + $scope.state.empty = true } - var curJump = ++jump, - inputMediaFilter = $scope.historyFilter.mediaType && {_: inputMediaFilters[$scope.historyFilter.mediaType]}, - getMessagesPromise = inputMediaFilter + var curJump = ++jump + var inputMediaFilter = $scope.historyFilter.mediaType && {_: inputMediaFilters[$scope.historyFilter.mediaType]} + var getMessagesPromise = inputMediaFilter ? AppMessagesManager.getSearch($scope.curDialog.peerID, '', inputMediaFilter, maxID) - : AppMessagesManager.getHistory($scope.curDialog.peerID, maxID, limit, backLimit, prerenderedLen); - + : AppMessagesManager.getHistory($scope.curDialog.peerID, maxID, limit, backLimit, prerenderedLen) - $scope.state.mayBeHasMore = true; - console.log(dT(), 'start load history', $scope.curDialog); + $scope.state.mayBeHasMore = true + // console.log(dT(), 'start load history', $scope.curDialog) getMessagesPromise.then(function (historyResult) { - if (curJump != jump) return; - console.log(dT(), 'history loaded', angular.copy(historyResult)); + if (curJump != jump) return + // console.log(dT(), 'history loaded', angular.copy(historyResult)) - var fetchedLength = historyResult.history.length; + var fetchedLength = historyResult.history.length minID = (historyResult.unreadSkip || maxID && historyResult.history.indexOf(maxID) >= backLimit - 1) - ? historyResult.history[0] - : 0; - maxID = historyResult.history[historyResult.history.length - 1]; + ? historyResult.history[0] + : 0 + maxID = historyResult.history[historyResult.history.length - 1] - $scope.historyState.skipped = hasLess = minID > 0; + $scope.historyState.skipped = hasLess = minID > 0 hasMore = historyResult.count === null || - fetchedLength && fetchedLength < historyResult.count; + fetchedLength && fetchedLength < historyResult.count - updateHistoryPeer(); - safeReplaceObject($scope.state, {loaded: true, empty: !fetchedLength}); + updateHistoryPeer() + safeReplaceObject($scope.state, {loaded: true, empty: !fetchedLength}) - peerHistory.messages = []; - peerHistory.ids = []; + peerHistory.messages = [] + peerHistory.ids = [] angular.forEach(historyResult.history, function (id) { - var message = AppMessagesManager.wrapForHistory(id); + var message = AppMessagesManager.wrapForHistory(id) if ($scope.historyState.skipped) { - delete message.pFlags.unread; + delete message.pFlags.unread } if (historyResult.unreadOffset) { - message.unreadAfter = true; + message.unreadAfter = true } - peerHistory.messages.push(message); - peerHistory.ids.push(id); - }); - peerHistory.messages.reverse(); - peerHistory.ids.reverse(); + peerHistory.messages.push(message) + peerHistory.ids.push(id) + }) + peerHistory.messages.reverse() + peerHistory.ids.reverse() if (AppMessagesManager.regroupWrappedHistory(peerHistory.messages)) { - $scope.$broadcast('messages_regroup'); + $scope.$broadcast('messages_regroup') } if (historyResult.unreadOffset) { - $scope.historyUnreadAfter = historyResult.history[historyResult.unreadOffset - 1]; + $scope.historyUnreadAfter = historyResult.history[historyResult.unreadOffset - 1] } else if ($scope.historyUnreadAfter) { - delete $scope.historyUnreadAfter; + delete $scope.historyUnreadAfter } - $scope.$broadcast('messages_unread_after'); - var focusedMsgID = $scope.curDialog.messageID || 0; + $scope.$broadcast('messages_unread_after') + var focusedMsgID = $scope.curDialog.messageID || 0 onContentLoaded(function () { - $scope.$broadcast('messages_focus', focusedMsgID); - }); - $scope.$broadcast('ui_history_change'); + $scope.$broadcast('messages_focus', focusedMsgID) + }) + $scope.$broadcast('ui_history_change') if (!$rootScope.idle.isIDLE) { - AppMessagesManager.readHistory($scope.curDialog.peerID); + AppMessagesManager.readHistory($scope.curDialog.peerID) } - updateBotActions(); - updateChannelActions(); - + updateBotActions() + updateChannelActions() }, function () { - safeReplaceObject($scope.state, {error: true, loaded: true}); - }); + safeReplaceObject($scope.state, {error: true, loaded: true}) + }) } function showEmptyHistory () { - jump++; - safeReplaceObject($scope.historyPeer, {}); - safeReplaceObject($scope.state, {notSelected: true}); - peerHistory = false; - hasMore = false; + jump++ + safeReplaceObject($scope.historyPeer, {}) + safeReplaceObject($scope.state, {notSelected: true}) + peerHistory = false + hasMore = false - $scope.$broadcast('ui_history_change'); + $scope.$broadcast('ui_history_change') } function startBot () { - AppMessagesManager.startBot(peerID, 0, $scope.curDialog.startParam); - $scope.curDialog.startParam = false; + AppMessagesManager.startBot(peerID, 0, $scope.curDialog.startParam) + $scope.curDialog.startParam = false } function cancelBot () { - delete $scope.curDialog.startParam; + delete $scope.curDialog.startParam } function joinChannel () { MtpApiManager.invokeApi('channels.joinChannel', { channel: AppChatsManager.getChannelInput(-peerID) }).then(function (result) { - ApiUpdatesManager.processUpdateMessage(result); - }); + ApiUpdatesManager.processUpdateMessage(result) + }) } function togglePeerMuted (muted) { NotificationsManager.getPeerSettings(peerID).then(function (settings) { - settings.mute_until = !muted ? 0 : 2000000000; - NotificationsManager.updatePeerSettings(peerID, settings); - }); + settings.mute_until = !muted ? 0 : 2000000000 + NotificationsManager.updatePeerSettings(peerID, settings) + }) } function toggleMessage (messageID, $event) { if ($scope.historyState.botActions || - $rootScope.idle.afterFocus) { - return false; + $rootScope.idle.afterFocus) { + return false } - var message = AppMessagesManager.getMessage(messageID); + var message = AppMessagesManager.getMessage(messageID) if (message._ == 'messageService') { - return false; + return false } if (!$scope.historyState.selectActions) { if (getSelectedText()) { - return false; + return false } - var target = $event.target; + var target = $event.target while (target) { if (target instanceof SVGElement) { - target = target.parentNode; - continue; + target = target.parentNode + continue } if (target.className && target.className.indexOf('im_message_outer_wrap') != -1) { if (Config.Mobile) { - return false; + return false } - break; + break } if (target.className && - target.className.indexOf('im_message_date') != -1) { + target.className.indexOf('im_message_date') != -1) { if ($scope.historyState.canReply) { - selectedReply(messageID); + selectedReply(messageID) } else { - quickForward(messageID); + quickForward(messageID) } - return false; + return false } if (Config.Mobile && - target.className && - target.className.indexOf('im_message_body') != -1) { - break; + target.className && + target.className.indexOf('im_message_body') != -1) { + break } if (target.tagName == 'A' || hasOnlick(target)) { - return false; + return false } - target = target.parentNode; + target = target.parentNode } if (Config.Mobile) { @@ -1622,132 +1608,131 @@ angular.module('myApp.controllers', ['myApp.i18n']) }).result.then(function (action) { switch (action) { case 'reply': - selectedReply(messageID); - break; + selectedReply(messageID) + break case 'delete': - selectedDelete(messageID); - break; + selectedDelete(messageID) + break case 'forward': - selectedForward(messageID); - break; + selectedForward(messageID) + break case 'select': - $scope.historyState.selectActions = 'selected'; - $scope.$broadcast('ui_panel_update'); - toggleMessage(messageID); - break; + $scope.historyState.selectActions = 'selected' + $scope.$broadcast('ui_panel_update') + toggleMessage(messageID) + break } - }); - return false; + }) + return false } } - var shiftClick = $event && $event.shiftKey; + var shiftClick = $event && $event.shiftKey if (shiftClick) { - $scope.$broadcast('ui_selection_clear'); + $scope.$broadcast('ui_selection_clear') } if ($scope.selectedMsgs[messageID]) { - lastSelectID = false; - delete $scope.selectedMsgs[messageID]; - $scope.selectedCount--; + lastSelectID = false + delete $scope.selectedMsgs[messageID] + $scope.selectedCount-- if (!$scope.selectedCount) { - $scope.historyState.selectActions = false; - $scope.$broadcast('ui_panel_update'); + $scope.historyState.selectActions = false + $scope.$broadcast('ui_panel_update') } } else { - if (!shiftClick) { - lastSelectID = messageID; + lastSelectID = messageID } else if (lastSelectID != messageID) { var dir = lastSelectID > messageID, - i, startPos, curMessageID; + i, startPos, curMessageID for (i = 0; i < peerHistory.messages.length; i++) { if (peerHistory.messages[i].mid == lastSelectID) { - startPos = i; - break; + startPos = i + break } } - i = startPos; + i = startPos while (peerHistory.messages[i] && - (curMessageID = peerHistory.messages[i].mid) != messageID) { + (curMessageID = peerHistory.messages[i].mid) != messageID) { if (!$scope.selectedMsgs[curMessageID]) { - $scope.selectedMsgs[curMessageID] = true; - $scope.selectedCount++; + $scope.selectedMsgs[curMessageID] = true + $scope.selectedCount++ } - i += dir ? -1 : +1; + i += dir ? -1 : +1 } } - $scope.selectedMsgs[messageID] = true; - $scope.selectedCount++; + $scope.selectedMsgs[messageID] = true + $scope.selectedCount++ if (!$scope.historyState.selectActions) { - $scope.historyState.selectActions = 'selected'; - $scope.$broadcast('ui_panel_update'); + $scope.historyState.selectActions = 'selected' + $scope.$broadcast('ui_panel_update') } } - $scope.$broadcast('messages_select'); + $scope.$broadcast('messages_select') } function selectInlineBot (botID, $event) { if ($scope.historyState.canReply) { - $scope.$broadcast('inline_bot_select', botID); + $scope.$broadcast('inline_bot_select', botID) } - return cancelEvent($event); + return cancelEvent($event) } function selectedCancel (noBroadcast) { - $scope.selectedMsgs = {}; - $scope.selectedCount = 0; - $scope.historyState.selectActions = false; - lastSelectID = false; + $scope.selectedMsgs = {} + $scope.selectedCount = 0 + $scope.historyState.selectActions = false + lastSelectID = false if (!noBroadcast) { - $scope.$broadcast('ui_panel_update'); + $scope.$broadcast('ui_panel_update') } - $scope.$broadcast('messages_select'); + $scope.$broadcast('messages_select') } function selectedFlush () { ErrorService.confirm({type: 'HISTORY_FLUSH'}).then(function () { AppMessagesManager.flushHistory($scope.curDialog.peerID, true).then(function () { - selectedCancel(); - }); + selectedCancel() + }) }) - }; + } function selectedDelete (selectedMessageID) { - var selectedMessageIDs = []; + var selectedMessageIDs = [] if (selectedMessageID) { - selectedMessageIDs.push(selectedMessageID); + selectedMessageIDs.push(selectedMessageID) } else if ($scope.selectedCount > 0) { angular.forEach($scope.selectedMsgs, function (t, messageID) { - selectedMessageIDs.push(messageID); - }); + selectedMessageIDs.push(messageID) + }) } if (selectedMessageIDs.length) { ErrorService.confirm({type: 'MESSAGES_DELETE', count: selectedMessageIDs.length}).then(function () { AppMessagesManager.deleteMessages(selectedMessageIDs).then(function () { - selectedCancel(); - }); - }); + selectedCancel() + }) + }) } } - function quickForward(msgID) { + function quickForward (msgID) { PeersSelectService.selectPeers({ canSend: true, confirm_type: 'FORWARD_PEER', shareLinkPromise: AppMessagesManager.getMessageShareLink(msgID) }).then(function (peerStrings) { angular.forEach(peerStrings, function (peerString) { - var peerID = AppPeersManager.getPeerID(peerString); - AppMessagesManager.forwardMessages(peerID, [msgID]); - }); + var peerID = AppPeersManager.getPeerID(peerString) + AppMessagesManager.forwardMessages(peerID, [msgID]) + }) var toastData = toaster.pop({ type: 'info', body: _('confirm_modal_forward_to_peer_success'), @@ -1755,114 +1740,113 @@ angular.module('myApp.controllers', ['myApp.i18n']) clickHandler: function () { $rootScope.$broadcast('history_focus', { peerString: peerStrings[0] - }); - toaster.clear(toastData); + }) + toaster.clear(toastData) }, showCloseButton: false - }); - - }); + }) + }) } function selectedForward (selectedMessageID) { - var selectedMessageIDs = []; + var selectedMessageIDs = [] if (selectedMessageID) { - selectedMessageIDs.push(selectedMessageID); + selectedMessageIDs.push(selectedMessageID) } else if ($scope.selectedCount > 0) { angular.forEach($scope.selectedMsgs, function (t, messageID) { - selectedMessageIDs.push(messageID); - }); + selectedMessageIDs.push(messageID) + }) } if (selectedMessageIDs.length) { PeersSelectService.selectPeer({canSend: true}).then(function (peerString) { - selectedCancel(); + selectedCancel() $rootScope.$broadcast('history_focus', { peerString: peerString, attachment: { _: 'fwd_messages', id: selectedMessageIDs } - }); - }); + }) + }) } } function selectedReply (selectedMessageID) { if (!selectedMessageID && $scope.selectedCount == 1) { angular.forEach($scope.selectedMsgs, function (t, messageID) { - selectedMessageID = messageID; - }); + selectedMessageID = messageID + }) } if (selectedMessageID) { - selectedCancel(); - $scope.$broadcast('reply_selected', selectedMessageID); + selectedCancel() + $scope.$broadcast('reply_selected', selectedMessageID) } } function toggleEdit () { if ($scope.historyState.selectActions) { - selectedCancel(); + selectedCancel() } else { - $scope.historyState.selectActions = 'selected'; - $scope.$broadcast('ui_panel_update'); + $scope.historyState.selectActions = 'selected' + $scope.$broadcast('ui_panel_update') } } function toggleMedia (mediaType) { - $scope.historyFilter.mediaType = mediaType || false; - $scope.curDialog.messageID = false; - peerHistory.messages = []; - peerHistory.ids = []; - $scope.state.empty = true; - loadHistory(); + $scope.historyFilter.mediaType = mediaType || false + $scope.curDialog.messageID = false + peerHistory.messages = [] + peerHistory.ids = [] + $scope.state.empty = true + loadHistory() } function returnToRecent () { if ($scope.historyFilter.mediaType) { - toggleMedia(); + toggleMedia() } else { if ($scope.curDialog.messageID) { - $rootScope.$broadcast('history_focus', {peerString: $scope.curDialog.peer}); + $rootScope.$broadcast('history_focus', {peerString: $scope.curDialog.peer}) } else { - loadHistory(true); + loadHistory(true) } } } - $scope.$on('history_update', angular.noop); + $scope.$on('history_update', angular.noop) - var loadAfterSync = false; + var loadAfterSync = false $scope.$on('stateSynchronized', function () { if (!loadAfterSync) { - return; + return } if (loadAfterSync == $scope.curDialog.peerID) { - loadHistory(); + loadHistory() } - loadAfterSync = false; - }); + loadAfterSync = false + }) $scope.$on('reply_button_press', function (e, button) { - var replyKeyboard = $scope.historyState.replyKeyboard; + var replyKeyboard = $scope.historyState.replyKeyboard if (!replyKeyboard) { - return; + return } var sendOptions = { replyToMsgID: peerID < 0 && replyKeyboard.mid - }; + } switch (button._) { case 'keyboardButtonRequestPhone': ErrorService.confirm({type: 'BOT_ACCESS_PHONE'}).then(function () { - var user = AppUsersManager.getSelf(); + var user = AppUsersManager.getSelf() AppMessagesManager.sendOther(peerID, { _: 'inputMediaContact', phone_number: user.phone, first_name: user.first_name, last_name: user.last_name - }, sendOptions); - }); - break; + }, sendOptions) + }) + break case 'keyboardButtonRequestGeoLocation': ErrorService.confirm({type: 'BOT_ACCESS_GEO'}).then(function () { @@ -1874,830 +1858,826 @@ angular.module('myApp.controllers', ['myApp.i18n']) 'lat': coords['lat'], 'long': coords['long'] } - }, sendOptions); + }, sendOptions) }, function (error) { ErrorService.alert( _('error_modal_bad_request_title_raw'), _('error_modal_gelocation_na_raw') - ); - }); - }); - break; + ) + }) + }) + break default: - AppMessagesManager.sendText(peerID, button.text, sendOptions); + AppMessagesManager.sendText(peerID, button.text, sendOptions) } - }); + }) $scope.$on('history_reload', function (e, updPeerID) { if (updPeerID == $scope.curDialog.peerID) { - loadHistory(); + loadHistory() } - }); + }) $scope.$on('history_forbidden', function (e, updPeerID) { if (updPeerID == $scope.curDialog.peerID) { - $location.url('/im'); + $location.url('/im') } - historiesQueuePop(updPeerID); - }); + historiesQueuePop(updPeerID) + }) $scope.$on('dialog_migrate', function (e, data) { if (data.migrateFrom == $scope.curDialog.peerID) { - var peerString = AppPeersManager.getPeerString(data.migrateTo); - $rootScope.$broadcast('history_focus', {peerString: peerString}); + var peerString = AppPeersManager.getPeerString(data.migrateTo) + $rootScope.$broadcast('history_focus', {peerString: peerString}) } - historiesQueuePop(data.migrateFrom); - }); + historiesQueuePop(data.migrateFrom) + }) $scope.$on('notify_settings', function (e, data) { if (data.peerID == $scope.curDialog.peerID) { - updateChannelActions(); + updateChannelActions() } - }); + }) $scope.$on('channel_settings', function (e, data) { if (data.channelID == -$scope.curDialog.peerID) { - updateChannelActions(); + updateChannelActions() } - }); + }) - var typingTimeouts = {}; + var typingTimeouts = {} $scope.$on('history_append', function (e, addedMessage) { - var history = historiesQueueFind(addedMessage.peerID); + var history = historiesQueueFind(addedMessage.peerID) if (!history) { - return; + return } - var curPeer = addedMessage.peerID == $scope.curDialog.peerID; + var curPeer = addedMessage.peerID == $scope.curDialog.peerID if (curPeer) { if ($scope.historyFilter.mediaType || - $scope.historyState.skipped) { + $scope.historyState.skipped) { if (addedMessage.my) { - returnToRecent(); + returnToRecent() } else { - $scope.historyState.missedCount++; + $scope.historyState.missedCount++ } - return; + return } if ($scope.curDialog.messageID && addedMessage.my) { - returnToRecent(); + returnToRecent() } - delete $scope.state.empty; + delete $scope.state.empty } - // console.log('append', addedMessage); - // console.trace(); - var historyMessage = AppMessagesManager.wrapForHistory(addedMessage.messageID); - history.messages.push(historyMessage); - history.ids.push(addedMessage.messageID); + // console.log('append', addedMessage) + // console.trace() + var historyMessage = AppMessagesManager.wrapForHistory(addedMessage.messageID) + history.messages.push(historyMessage) + history.ids.push(addedMessage.messageID) if (AppMessagesManager.regroupWrappedHistory(history.messages, -3)) { - $scope.$broadcast('messages_regroup'); + $scope.$broadcast('messages_regroup') } if (curPeer) { - $scope.historyState.typing.splice(0, $scope.historyState.typing.length); + $scope.historyState.typing.splice(0, $scope.historyState.typing.length) $scope.$broadcast('ui_history_append_new', { my: addedMessage.my, idleScroll: unreadAfterIdle && !historyMessage.pFlags.out && $rootScope.idle.isIDLE - }); + }) if (addedMessage.my && $scope.historyUnreadAfter) { - delete $scope.historyUnreadAfter; - $scope.$broadcast('messages_unread_after'); + delete $scope.historyUnreadAfter + $scope.$broadcast('messages_unread_after') } - // console.log('append check', $rootScope.idle.isIDLE, addedMessage.peerID, $scope.curDialog.peerID, historyMessage, history.messages[history.messages.length - 2]); + // console.log('append check', $rootScope.idle.isIDLE, addedMessage.peerID, $scope.curDialog.peerID, historyMessage, history.messages[history.messages.length - 2]) if ($rootScope.idle.isIDLE) { if (historyMessage.pFlags.unread && - !historyMessage.pFlags.out && - !(history.messages[history.messages.length - 2] || {}).pFlags.unread) { - - $scope.historyUnreadAfter = historyMessage.mid; - unreadAfterIdle = true; - $scope.$broadcast('messages_unread_after'); + !historyMessage.pFlags.out && + !(history.messages[history.messages.length - 2] || {}).pFlags.unread) { + $scope.historyUnreadAfter = historyMessage.mid + unreadAfterIdle = true + $scope.$broadcast('messages_unread_after') } } else { $timeout(function () { - AppMessagesManager.readHistory($scope.curDialog.peerID); - }); + AppMessagesManager.readHistory($scope.curDialog.peerID) + }) } - updateBotActions(); - updateChannelActions(); + updateBotActions() + updateChannelActions() } - }); + }) $scope.$on('history_multiappend', function (e, historyMultiAdded) { - // console.log(dT(), 'multiappend', angular.copy(historyMultiAdded)); - var regroupped = false; - var unreadAfterChanged = false; - var isIDLE = $rootScope.idle.isIDLE; + // console.log(dT(), 'multiappend', angular.copy(historyMultiAdded)) + var regroupped = false + var unreadAfterChanged = false + var isIDLE = $rootScope.idle.isIDLE angular.forEach(historyMultiAdded, function (msgs, peerID) { - var history = historiesQueueFind(peerID); - // var history = historiesQueuePush(peerID); + var history = historiesQueueFind(peerID) + // var history = historiesQueuePush(peerID) if (!history) { - return; + return } - var curPeer = peerID == $scope.curDialog.peerID; - var exlen = history.messages.length; - var len = msgs.length; + var curPeer = peerID == $scope.curDialog.peerID + var exlen = history.messages.length + var len = msgs.length if (curPeer) { if ($scope.historyFilter.mediaType || - $scope.historyState.skipped) { - $scope.historyState.missedCount += len; - return; + $scope.historyState.skipped) { + $scope.historyState.missedCount += len + return } - delete $scope.state.empty; + delete $scope.state.empty } if ((!curPeer || isIDLE) && - exlen > (len > 10 ? 10 : 100)) { - console.warn(dT(), 'Drop too many messages', len, exlen, isIDLE, curPeer, peerID); + exlen > (len > 10 ? 10 : 100)) { + console.warn(dT(), 'Drop too many messages', len, exlen, isIDLE, curPeer, peerID) if (curPeer) { - minID = history.messages[exlen - 1].mid; - $scope.historyState.skipped = hasLess = minID > 0; + minID = history.messages[exlen - 1].mid + $scope.historyState.skipped = hasLess = minID > 0 if (hasLess) { - loadAfterSync = peerID; - $scope.$broadcast('ui_history_append'); + loadAfterSync = peerID + $scope.$broadcast('ui_history_append') } } else { - historiesQueuePop(peerID); + historiesQueuePop(peerID) } - return; + return } - var messageID, historyMessage, i; - var hasOut = false; - var unreadAfterNew = false; - var historyMessage = history.messages[history.messages.length - 1]; - var lastIsRead = !historyMessage || !historyMessage.pFlags.unread; + var messageID, historyMessage, i + var hasOut = false + var unreadAfterNew = false + var historyMessage = history.messages[history.messages.length - 1] + var lastIsRead = !historyMessage || !historyMessage.pFlags.unread for (i = 0; i < len; i++) { - messageID = msgs[i]; + messageID = msgs[i] if (messageID < maxID || - history.ids.indexOf(messageID) !== -1) { - continue; + history.ids.indexOf(messageID) !== -1) { + continue } - historyMessage = AppMessagesManager.wrapForHistory(messageID); - history.messages.push(historyMessage); - history.ids.push(messageID); + historyMessage = AppMessagesManager.wrapForHistory(messageID) + history.messages.push(historyMessage) + history.ids.push(messageID) if (!unreadAfterNew && isIDLE) { if (historyMessage.pFlags.unread && - !historyMessage.pFlags.out && - lastIsRead) { - unreadAfterNew = messageID; + !historyMessage.pFlags.out && + lastIsRead) { + unreadAfterNew = messageID } else { - lastIsRead = !historyMessage.pFlags.unread; + lastIsRead = !historyMessage.pFlags.unread } } if (!hasOut && historyMessage.pFlags.out) { - hasOut = true; + hasOut = true } } - // console.log('after append', angular.copy(history.messages), angular.copy(history.ids)); + // console.log('after append', angular.copy(history.messages), angular.copy(history.ids)) if (AppMessagesManager.regroupWrappedHistory(history.messages, -len - 2)) { - regroupped = true; + regroupped = true } if (curPeer) { if ($scope.historyState.typing.length) { - $scope.historyState.typing.splice(0, $scope.historyState.typing.length); + $scope.historyState.typing.splice(0, $scope.historyState.typing.length) } $scope.$broadcast('ui_history_append_new', { idleScroll: unreadAfterIdle && !hasOut && isIDLE - }); + }) if (isIDLE) { if (unreadAfterNew) { - $scope.historyUnreadAfter = unreadAfterNew; - unreadAfterIdle = true; - unreadAfterChanged = true; + $scope.historyUnreadAfter = unreadAfterNew + unreadAfterIdle = true + unreadAfterChanged = true } } else { $timeout(function () { - AppMessagesManager.readHistory($scope.curDialog.peerID); - }); + AppMessagesManager.readHistory($scope.curDialog.peerID) + }) } - updateBotActions(); - updateChannelActions(); + updateBotActions() + updateChannelActions() } - }); + }) if (regroupped) { - $scope.$broadcast('messages_regroup'); + $scope.$broadcast('messages_regroup') } if (unreadAfterChanged) { - $scope.$broadcast('messages_unread_after'); + $scope.$broadcast('messages_unread_after') } - }); + }) $scope.$on('history_delete', function (e, historyUpdate) { - var history = historiesQueueFind(historyUpdate.peerID); + var history = historiesQueueFind(historyUpdate.peerID) if (!history) { - return; + return } var newMessages = [], - i; + i for (i = 0; i < history.messages.length; i++) { if (!historyUpdate.msgs[history.messages[i].mid]) { - newMessages.push(history.messages[i]); + newMessages.push(history.messages[i]) } - }; - history.messages = newMessages; - AppMessagesManager.regroupWrappedHistory(history.messages); - $scope.$broadcast('messages_regroup'); + } + history.messages = newMessages + AppMessagesManager.regroupWrappedHistory(history.messages) + $scope.$broadcast('messages_regroup') if (historyUpdate.peerID == $scope.curDialog.peerID) { - $scope.state.empty = !newMessages.length; - updateBotActions(); + $scope.state.empty = !newMessages.length + updateBotActions() } - }); + }) $scope.$on('dialog_flush', function (e, dialog) { - var history = historiesQueueFind(dialog.peerID); + var history = historiesQueueFind(dialog.peerID) if (history) { - history.messages = []; - history.ids = []; + history.messages = [] + history.ids = [] if (dialog.peerID == $scope.curDialog.peerID) { - $scope.state.empty = true; - updateBotActions(); + $scope.state.empty = true + updateBotActions() } } - }); + }) $scope.$on('history_focus', function (e, peerData) { if ($scope.historyFilter.mediaType) { - toggleMedia(); + toggleMedia() } - }); + }) $scope.$on('apiUpdate', function (e, update) { switch (update._) { case 'updateUserTyping': case 'updateChatUserTyping': - AppUsersManager.forceUserOnline(update.user_id); + AppUsersManager.forceUserOnline(update.user_id) if (AppUsersManager.hasUser(update.user_id) && - $scope.curDialog.peerID == (update._ == 'updateUserTyping' - ? update.user_id - : -update.chat_id - )) { + $scope.curDialog.peerID == (update._ == 'updateUserTyping' + ? update.user_id + : -update.chat_id + )) { if ($scope.historyState.typing.indexOf(update.user_id) == -1) { - $scope.historyState.typing.push(update.user_id); + $scope.historyState.typing.push(update.user_id) } - $timeout.cancel(typingTimeouts[update.user_id]); + $timeout.cancel(typingTimeouts[update.user_id]) typingTimeouts[update.user_id] = $timeout(function () { - var pos = $scope.historyState.typing.indexOf(update.user_id); + var pos = $scope.historyState.typing.indexOf(update.user_id) if (pos !== -1) { - $scope.historyState.typing.splice(pos, 1); + $scope.historyState.typing.splice(pos, 1) } - }, 6000); + }, 6000) } - break; + break } - }); + }) - $scope.$on('history_need_less', showLessHistory); - $scope.$on('history_need_more', showMoreHistory); + $scope.$on('history_need_less', showLessHistory) + $scope.$on('history_need_more', showMoreHistory) $rootScope.$watch('idle.isIDLE', function (newVal) { if (!newVal && $scope.curDialog && $scope.curDialog.peerID && !$scope.historyFilter.mediaType && !$scope.historyState.skipped) { - AppMessagesManager.readHistory($scope.curDialog.peerID); + AppMessagesManager.readHistory($scope.curDialog.peerID) } if (!newVal) { - unreadAfterIdle = false; + unreadAfterIdle = false if (loadAfterSync && - loadAfterSync == $scope.curDialog.peerID) { - loadHistory(); - loadAfterSync = false; + loadAfterSync == $scope.curDialog.peerID) { + loadHistory() + loadAfterSync = false } } - }); - + }) }) - .controller('AppImPanelController', function($scope) { - $scope.$on('user_update', angular.noop); + .controller('AppImPanelController', function ($scope) { + $scope.$on('user_update', angular.noop) }) .controller('AppImSendController', function ($rootScope, $q, $scope, $timeout, MtpApiManager, Storage, AppProfileManager, AppChatsManager, AppUsersManager, AppPeersManager, AppDocsManager, AppMessagesManager, AppInlineBotsManager, MtpApiFileManager, DraftsManager, RichTextProcessor) { - - $scope.$watch('curDialog.peer', resetDraft); - $scope.$on('user_update', angular.noop); - $scope.$on('peer_draft_attachment', applyDraftAttachment); + $scope.$watch('curDialog.peer', resetDraft) + $scope.$on('user_update', angular.noop) + $scope.$on('peer_draft_attachment', applyDraftAttachment) $scope.$on('reply_selected', function (e, messageID) { - replySelect(messageID, true); - }); - $scope.$on('ui_typing', onTyping); + replySelect(messageID, true) + }) + $scope.$on('ui_typing', onTyping) $scope.draftMessage = { text: '', send: sendMessage, replyClear: replyClear, fwdsClear: fwdsClear - }; - $scope.mentions = {}; - $scope.commands = {}; - $scope.$watch('draftMessage.text', onMessageChange); - $scope.$watch('draftMessage.files', onFilesSelected); - $scope.$watch('draftMessage.sticker', onStickerSelected); - $scope.$watch('draftMessage.command', onCommandSelected); - $scope.$watch('draftMessage.inlineResultID', onInlineResultSelected); + } + $scope.mentions = {} + $scope.commands = {} + $scope.$watch('draftMessage.text', onMessageChange) + $scope.$watch('draftMessage.files', onFilesSelected) + $scope.$watch('draftMessage.sticker', onStickerSelected) + $scope.$watch('draftMessage.command', onCommandSelected) + $scope.$watch('draftMessage.inlineResultID', onInlineResultSelected) $scope.$on('history_reply_markup', function (e, peerData) { if (peerData.peerID == $scope.curDialog.peerID) { - updateReplyKeyboard(); + updateReplyKeyboard() } - }); + }) $scope.$on('inline_bot_select', function (e, botID) { - var bot = AppUsersManager.getUser(botID); - $scope.draftMessage.text = '@' + bot.username + ' ';; - $scope.$broadcast('ui_peer_draft', {focus: true}); - }); + var bot = AppUsersManager.getUser(botID) + $scope.draftMessage.text = '@' + bot.username + ' ' + $scope.$broadcast('ui_peer_draft', {focus: true}) + }) - $scope.$on('inline_bots_popular', updateMentions); + $scope.$on('inline_bots_popular', updateMentions) - $scope.replyKeyboardToggle = replyKeyboardToggle; - $scope.toggleSlash = toggleSlash; + $scope.replyKeyboardToggle = replyKeyboardToggle + $scope.toggleSlash = toggleSlash $rootScope.$watch('idle.isIDLE', function (newVal) { if (newVal && $scope.curDialog.peerID) { - DraftsManager.syncDraft($scope.curDialog.peerID); + DraftsManager.syncDraft($scope.curDialog.peerID) } - }); + }) $scope.$on('draft_updated', function (e, draftUpdate) { if (draftUpdate.peerID == $scope.curDialog.peerID) { - getDraft(); + getDraft() } - }); + }) - var replyToMarkup = false; - var forceDraft = false; + var replyToMarkup = false + var forceDraft = false function sendMessage (e) { - $scope.$broadcast('ui_message_before_send'); + $scope.$broadcast('ui_message_before_send') $timeout(function () { - var text = $scope.draftMessage.text; + var text = $scope.draftMessage.text if (angular.isString(text) && text.length > 0) { - text = RichTextProcessor.parseEmojis(text); + text = RichTextProcessor.parseEmojis(text) var options = { replyToMsgID: $scope.draftMessage.replyToMessage && $scope.draftMessage.replyToMessage.mid, clearDraft: true - }; + } do { - AppMessagesManager.sendText($scope.curDialog.peerID, text.substr(0, 4096), options); - text = text.substr(4096); - } while (text.length); + AppMessagesManager.sendText($scope.curDialog.peerID, text.substr(0, 4096), options) + text = text.substr(4096) + } while (text.length) } - fwdsSend(); + fwdsSend() if (forceDraft == $scope.curDialog.peer) { - forceDraft = false; + forceDraft = false } else { - DraftsManager.changeDraft($scope.curDialog.peerID); + DraftsManager.changeDraft($scope.curDialog.peerID) } - resetDraft(); - $scope.$broadcast('ui_message_send'); - }); + resetDraft() + $scope.$broadcast('ui_message_send') + }) - return cancelEvent(e); + return cancelEvent(e) } function updateMentions () { - var peerID = $scope.curDialog.peerID; + var peerID = $scope.curDialog.peerID if (!peerID) { - safeReplaceObject($scope.mentions, {}); - $scope.$broadcast('mentions_update'); - return; + safeReplaceObject($scope.mentions, {}) + $scope.$broadcast('mentions_update') + return } - var mentionUsers = []; - var mentionIndex = SearchIndexManager.createIndex(); + var mentionUsers = [] + var mentionIndex = SearchIndexManager.createIndex() var inlineBotsPromise = AppInlineBotsManager.getPopularBots().then(function (inlineBots) { - var ids = []; + var ids = [] angular.forEach(inlineBots, function (bot) { - ids.push(bot.id); - }); - return ids; - }); - var chatParticipantsPromise; + ids.push(bot.id) + }) + return ids + }) + var chatParticipantsPromise if (peerID < 0) { chatParticipantsPromise = AppProfileManager.getChatFull(-peerID).then(function (chatFull) { - var participantsVector = (chatFull.participants || {}).participants || []; - var ids = []; + var participantsVector = (chatFull.participants || {}).participants || [] + var ids = [] angular.forEach(participantsVector, function (participant) { - ids.push(participant.user_id); - }); - return ids; - }); + ids.push(participant.user_id) + }) + return ids + }) } else { - chatParticipantsPromise = $q.when([]); + chatParticipantsPromise = $q.when([]) } $q.all({pop: inlineBotsPromise, chat: chatParticipantsPromise}).then(function (result) { - var done = {}; - var ids = result.pop.concat(result.chat); + var done = {} + var ids = result.pop.concat(result.chat) angular.forEach(ids, function (userID) { if (done[userID]) { - return; + return } - done[userID] = true; - var user = AppUsersManager.getUser(userID); + done[userID] = true + var user = AppUsersManager.getUser(userID) if (user.username) { - mentionUsers.push(user); - SearchIndexManager.indexObject(user.id, AppUsersManager.getUserSearchText(user.id), mentionIndex); + mentionUsers.push(user) + SearchIndexManager.indexObject(user.id, AppUsersManager.getUserSearchText(user.id), mentionIndex) } - }); + }) safeReplaceObject($scope.mentions, { users: mentionUsers, index: mentionIndex - }); - $scope.$broadcast('mentions_update'); - - }); + }) + $scope.$broadcast('mentions_update') + }) } function updateCommands () { - var peerID = $scope.curDialog.peerID; + var peerID = $scope.curDialog.peerID if (!peerID) { - safeReplaceObject($scope.commands, {}); - $scope.$broadcast('mentions_update'); - return; + safeReplaceObject($scope.commands, {}) + $scope.$broadcast('mentions_update') + return } AppProfileManager.getPeerBots(peerID).then(function (peerBots) { if (!peerBots.length) { - safeReplaceObject($scope.commands, {}); - $scope.$broadcast('mentions_update'); - return; + safeReplaceObject($scope.commands, {}) + $scope.$broadcast('mentions_update') + return } - var needMentions = peerID < 0; - var commandsList = []; - var commandsIndex = SearchIndexManager.createIndex(); + var needMentions = peerID < 0 + var commandsList = [] + var commandsIndex = SearchIndexManager.createIndex() angular.forEach(peerBots, function (peerBot) { - var mention = ''; + var mention = '' if (needMentions) { - var bot = AppUsersManager.getUser(peerBot.id); + var bot = AppUsersManager.getUser(peerBot.id) if (bot && bot.username) { - mention += '@' + bot.username; + mention += '@' + bot.username } } - var botSearchText = AppUsersManager.getUserSearchText(peerBot.id); + var botSearchText = AppUsersManager.getUserSearchText(peerBot.id) angular.forEach(peerBot.commands, function (description, command) { - var value = '/' + command + mention; + var value = '/' + command + mention commandsList.push({ botID: peerBot.id, value: value, rDescription: RichTextProcessor.wrapRichText(description, {noLinks: true, noLineBreaks: true}) - }); - SearchIndexManager.indexObject(value, botSearchText + ' ' + command + ' ' + description, commandsIndex); + }) + SearchIndexManager.indexObject(value, botSearchText + ' ' + command + ' ' + description, commandsIndex) }) - }); + }) safeReplaceObject($scope.commands, { list: commandsList, index: commandsIndex - }); - $scope.$broadcast('mentions_update'); - }); + }) + $scope.$broadcast('mentions_update') + }) } function resetDraft (newPeer, prevPeer) { if (prevPeer) { - var prevPeerID = AppPeersManager.getPeerID(prevPeer); + var prevPeerID = AppPeersManager.getPeerID(prevPeer) if (prevPeerID) { - DraftsManager.syncDraft(prevPeerID); + DraftsManager.syncDraft(prevPeerID) } } - updateMentions(); - updateCommands(); - replyClear(); - updateReplyKeyboard(); + updateMentions() + updateCommands() + replyClear() + updateReplyKeyboard() - delete $scope.draftMessage.inlineProgress; - $scope.$broadcast('inline_results', false); + delete $scope.draftMessage.inlineProgress + $scope.$broadcast('inline_results', false) - // console.log(dT(), 'reset draft', $scope.curDialog.peer, forceDraft); + // console.log(dT(), 'reset draft', $scope.curDialog.peer, forceDraft) if (forceDraft) { if (forceDraft == $scope.curDialog.peer) { - $scope.draftMessage.isBroadcast = AppPeersManager.isChannel($scope.curDialog.peerID) && !AppPeersManager.isMegagroup($scope.curDialog.peerID); - $scope.$broadcast('ui_peer_draft'); - return; + $scope.draftMessage.isBroadcast = AppPeersManager.isChannel($scope.curDialog.peerID) && !AppPeersManager.isMegagroup($scope.curDialog.peerID) + $scope.$broadcast('ui_peer_draft') + return } else { - forceDraft = false; + forceDraft = false } } - fwdsClear(); - getDraft(); + fwdsClear() + getDraft() } - function getDraft() { + function getDraft () { if ($scope.curDialog.peerID) { DraftsManager.getDraft($scope.curDialog.peerID).then(function (draftData) { - $scope.draftMessage.text = draftData ? draftData.text : ''; - $scope.draftMessage.isBroadcast = AppPeersManager.isChannel($scope.curDialog.peerID) && !AppPeersManager.isMegagroup($scope.curDialog.peerID); + $scope.draftMessage.text = draftData ? draftData.text : '' + $scope.draftMessage.isBroadcast = AppPeersManager.isChannel($scope.curDialog.peerID) && !AppPeersManager.isMegagroup($scope.curDialog.peerID) if (draftData.replyToMsgID) { - var replyToMsgID = draftData.replyToMsgID; - replySelect(replyToMsgID); + var replyToMsgID = draftData.replyToMsgID + replySelect(replyToMsgID) } else { - replyClear(); + replyClear() } - $scope.$broadcast('ui_peer_draft'); - }); + $scope.$broadcast('ui_peer_draft') + }) } else { - // console.log('Reset peer'); - $scope.draftMessage.text = ''; - $scope.$broadcast('ui_peer_draft'); + // console.log('Reset peer') + $scope.draftMessage.text = '' + $scope.$broadcast('ui_peer_draft') } } function applyDraftAttachment (e, attachment) { - console.log('apply draft attach', attachment); + console.log('apply draft attach', attachment) if (!attachment || !attachment._) { - return; + return } if (attachment._ == 'share_url') { - var url = attachment.url; - var text = attachment.text || ' '; - forceDraft = $scope.curDialog.peer; + var url = attachment.url + var text = attachment.text || ' ' + forceDraft = $scope.curDialog.peer $timeout(function () { - $scope.draftMessage.text = url + "\n" + text; + $scope.draftMessage.text = url + '\n' + text $scope.$broadcast('ui_peer_draft', { customSelection: [ - url + "\n", + url + '\n', text, '' ] - }); - }, 1000); + }) + }, 1000) } else if (attachment._ == 'fwd_messages') { $timeout(function () { - $scope.draftMessage.fwdMessages = attachment.id; - $scope.$broadcast('ui_peer_reply'); - }, 100); + $scope.draftMessage.fwdMessages = attachment.id + $scope.$broadcast('ui_peer_reply') + }, 100) } else if (attachment._ == 'inline_query') { - var mention = attachment.mention; - var query = attachment.query; - forceDraft = $scope.curDialog.peer; + var mention = attachment.mention + var query = attachment.query + forceDraft = $scope.curDialog.peer $timeout(function () { - $scope.draftMessage.text = mention + ' ' + query; + $scope.draftMessage.text = mention + ' ' + query $scope.$broadcast('ui_peer_draft', { customSelection: [ - mention + " " + query, + mention + ' ' + query, '', '' ] - }); - }, 1000); + }) + }, 1000) } } - function replySelect(messageID, byUser) { - $scope.draftMessage.replyToMessage = AppMessagesManager.wrapSingleMessage(messageID); - $scope.$broadcast('ui_peer_reply'); - replyToMarkup = false; + function replySelect (messageID, byUser) { + $scope.draftMessage.replyToMessage = AppMessagesManager.wrapSingleMessage(messageID) + $scope.$broadcast('ui_peer_reply') + replyToMarkup = false if (byUser) { DraftsManager.changeDraft($scope.curDialog.peerID, { text: $scope.draftMessage.text, replyToMsgID: messageID - }); + }) } } - function replyClear(byUser) { - var message = $scope.draftMessage.replyToMessage; + function replyClear (byUser) { + var message = $scope.draftMessage.replyToMessage if (message && - $scope.historyState.replyKeyboard && - $scope.historyState.replyKeyboard.mid == message.mid && - !$scope.historyState.replyKeyboard.pFlags.hidden) { - $scope.historyState.replyKeyboard.pFlags.hidden = true; - $scope.$broadcast('ui_keyboard_update'); + $scope.historyState.replyKeyboard && + $scope.historyState.replyKeyboard.mid == message.mid && + !$scope.historyState.replyKeyboard.pFlags.hidden) { + $scope.historyState.replyKeyboard.pFlags.hidden = true + $scope.$broadcast('ui_keyboard_update') } - delete $scope.draftMessage.replyToMessage; - $scope.$broadcast('ui_peer_reply'); + delete $scope.draftMessage.replyToMessage + $scope.$broadcast('ui_peer_reply') if (byUser) { DraftsManager.changeDraft($scope.curDialog.peerID, { text: $scope.draftMessage.text - }); + }) } } function fwdsClear () { if ($scope.draftMessage.fwdMessages && - $scope.draftMessage.fwdMessages.length) { - delete $scope.draftMessage.fwdMessages; - $scope.$broadcast('ui_peer_reply'); + $scope.draftMessage.fwdMessages.length) { + delete $scope.draftMessage.fwdMessages + $scope.$broadcast('ui_peer_reply') if (forceDraft == $scope.curDialog.peer) { - forceDraft = false; + forceDraft = false } } } function fwdsSend () { if ($scope.draftMessage.fwdMessages && - $scope.draftMessage.fwdMessages.length) { - var ids = $scope.draftMessage.fwdMessages.slice(); - fwdsClear(); + $scope.draftMessage.fwdMessages.length) { + var ids = $scope.draftMessage.fwdMessages.slice() + fwdsClear() setZeroTimeout(function () { - AppMessagesManager.forwardMessages($scope.curDialog.peerID, ids); - }); + AppMessagesManager.forwardMessages($scope.curDialog.peerID, ids) + }) } } function toggleSlash ($event) { if ($scope.draftMessage.text && - $scope.draftMessage.text.charAt(0) == '/') { - $scope.draftMessage.text = ''; + $scope.draftMessage.text.charAt(0) == '/') { + $scope.draftMessage.text = '' } else { - $scope.draftMessage.text = '/'; + $scope.draftMessage.text = '/' } - $scope.$broadcast('ui_peer_draft', {focus: true}); - return cancelEvent($event); + $scope.$broadcast('ui_peer_draft', {focus: true}) + return cancelEvent($event) } function updateReplyKeyboard () { - var peerID = $scope.curDialog.peerID; - var replyKeyboard = AppMessagesManager.getReplyKeyboard(peerID); + var peerID = $scope.curDialog.peerID + var replyKeyboard = AppMessagesManager.getReplyKeyboard(peerID) if (replyKeyboard) { - replyKeyboard = AppMessagesManager.wrapReplyMarkup(replyKeyboard); + replyKeyboard = AppMessagesManager.wrapReplyMarkup(replyKeyboard) } - // console.log('update reply markup', peerID, replyKeyboard); - $scope.historyState.replyKeyboard = replyKeyboard; + // console.log('update reply markup', peerID, replyKeyboard) + $scope.historyState.replyKeyboard = replyKeyboard var addReplyMessage = - replyKeyboard && - !replyKeyboard.pFlags.hidden && - (replyKeyboard._ == 'replyKeyboardForceReply' || - (replyKeyboard._ == 'replyKeyboardMarkup' && peerID < 0)); + replyKeyboard && + !replyKeyboard.pFlags.hidden && + (replyKeyboard._ == 'replyKeyboardForceReply' || + (replyKeyboard._ == 'replyKeyboardMarkup' && peerID < 0)) if (addReplyMessage) { - replySelect(replyKeyboard.mid); - replyToMarkup = true; + replySelect(replyKeyboard.mid) + replyToMarkup = true } else if (replyToMarkup) { - replyClear(); + replyClear() } var enabled = replyKeyboard && - !replyKeyboard.pFlags.hidden && - replyKeyboard._ == 'replyKeyboardMarkup'; - $scope.$broadcast('ui_keyboard_update', {enabled: enabled}); - $scope.$emit('ui_panel_update', {blur: enabled}); + !replyKeyboard.pFlags.hidden && + replyKeyboard._ == 'replyKeyboardMarkup' + $scope.$broadcast('ui_keyboard_update', {enabled: enabled}) + $scope.$emit('ui_panel_update', {blur: enabled}) } function replyKeyboardToggle ($event) { - var replyKeyboard = $scope.historyState.replyKeyboard; + var replyKeyboard = $scope.historyState.replyKeyboard if (replyKeyboard) { - replyKeyboard.pFlags.hidden = !replyKeyboard.pFlags.hidden; - updateReplyKeyboard(); + replyKeyboard.pFlags.hidden = !replyKeyboard.pFlags.hidden + updateReplyKeyboard() } - return cancelEvent($event); + return cancelEvent($event) } - function onMessageChange(newVal) { - // console.log('ctrl text changed', newVal); - // console.trace('ctrl text changed', newVal); + function onMessageChange (newVal) { + // console.log('ctrl text changed', newVal) + // console.trace('ctrl text changed', newVal) if (newVal && newVal.length) { if (!$scope.historyFilter.mediaType && !$scope.historyState.skipped) { - AppMessagesManager.readHistory($scope.curDialog.peerID); + AppMessagesManager.readHistory($scope.curDialog.peerID) } } if ($scope.curDialog.peerID) { - var replyToMessage = $scope.draftMessage.replyToMessage; + var replyToMessage = $scope.draftMessage.replyToMessage DraftsManager.changeDraft($scope.curDialog.peerID, { text: newVal, replyToMsgID: replyToMessage && replyToMessage.mid - }); - checkInlinePattern(newVal); + }) + checkInlinePattern(newVal) } } - var inlineUsernameRegex = /^@([a-zA-Z\d_]{1,32})( | )([\s\S]*)$/; - var getInlineResultsTO = false; - var lastInlineBot = false; - var jump = 0; + var inlineUsernameRegex = /^@([a-zA-Z\d_]{1,32})( | )([\s\S]*)$/ + var getInlineResultsTO = false + var lastInlineBot = false + var jump = 0 function checkInlinePattern (message) { if (getInlineResultsTO) { - $timeout.cancel(getInlineResultsTO); + $timeout.cancel(getInlineResultsTO) } - var curJump = ++jump; + var curJump = ++jump if (!message || !message.length) { - delete $scope.draftMessage.inlineProgress; - $scope.$broadcast('inline_results', false); - return; + delete $scope.draftMessage.inlineProgress + $scope.$broadcast('inline_results', false) + return } - var matches = message.match(inlineUsernameRegex); + var matches = message.match(inlineUsernameRegex) if (!matches) { - delete $scope.draftMessage.inlineProgress; - $scope.$broadcast('inline_results', false); - return; + delete $scope.draftMessage.inlineProgress + $scope.$broadcast('inline_results', false) + return } - var username = matches[1]; - var inlineBotPromise; - $scope.draftMessage.inlineProgress = true; + var username = matches[1] + var inlineBotPromise + $scope.draftMessage.inlineProgress = true if (lastInlineBot && lastInlineBot.username == username) { - inlineBotPromise = $q.when(lastInlineBot); + inlineBotPromise = $q.when(lastInlineBot) } else { - inlineBotPromise = AppInlineBotsManager.resolveInlineMention(username); + inlineBotPromise = AppInlineBotsManager.resolveInlineMention(username) } inlineBotPromise.then(function (inlineBot) { if (curJump != jump) { - return; + return } - lastInlineBot = inlineBot; + lastInlineBot = inlineBot $scope.$broadcast('inline_placeholder', { prefix: '@' + username + matches[2], placeholder: inlineBot.placeholder - }); + }) if (getInlineResultsTO) { - $timeout.cancel(getInlineResultsTO); + $timeout.cancel(getInlineResultsTO) } getInlineResultsTO = $timeout(function () { - var query = RichTextProcessor.parseEmojis(matches[3]); + var query = RichTextProcessor.parseEmojis(matches[3]) AppInlineBotsManager.getInlineResults($scope.curDialog.peerID, inlineBot.id, query, inlineBot.geo, '').then(function (botResults) { - getInlineResultsTO = false; + getInlineResultsTO = false if (curJump != jump) { - return; + return } - botResults.text = message; - $scope.$broadcast('inline_results', botResults); - delete $scope.draftMessage.inlineProgress; + botResults.text = message + $scope.$broadcast('inline_results', botResults) + delete $scope.draftMessage.inlineProgress }, function () { - $scope.$broadcast('inline_results', false); - delete $scope.draftMessage.inlineProgress; - }); - }, 500); + $scope.$broadcast('inline_results', false) + delete $scope.draftMessage.inlineProgress + }) + }, 500) }, function (error) { - $scope.$broadcast('inline_results', false); - delete $scope.draftMessage.inlineProgress; - }); + $scope.$broadcast('inline_results', false) + delete $scope.draftMessage.inlineProgress + }) } function onTyping () { if (AppPeersManager.isChannel($scope.curDialog.peerID) && - !AppPeersManager.isMegagroup($scope.curDialog.peerID)) { - return false; + !AppPeersManager.isMegagroup($scope.curDialog.peerID)) { + return false } MtpApiManager.invokeApi('messages.setTyping', { peer: AppPeersManager.getInputPeerByID($scope.curDialog.peerID), action: {_: 'sendMessageTypingAction'} })['catch'](function (error) { - error.handled = true; - }); + error.handled = true + }) } function onFilesSelected (newVal) { if (!angular.isArray(newVal) || !newVal.length) { - return; + return } var options = { replyToMsgID: $scope.draftMessage.replyToMessage && $scope.draftMessage.replyToMessage.mid, isMedia: $scope.draftMessage.isMedia - }; + } - delete $scope.draftMessage.replyToMessage; + delete $scope.draftMessage.replyToMessage if (newVal[0].lastModified) { newVal.sort(function (file1, file2) { - return file1.lastModified - file2.lastModified; - }); + return file1.lastModified - file2.lastModified + }) } for (var i = 0; i < newVal.length; i++) { - AppMessagesManager.sendFile($scope.curDialog.peerID, newVal[i], options); - $scope.$broadcast('ui_message_send'); + AppMessagesManager.sendFile($scope.curDialog.peerID, newVal[i], options) + $scope.$broadcast('ui_message_send') } - fwdsSend(); + fwdsSend() } function onStickerSelected (newVal) { if (!newVal) { - return; + return } - var doc = AppDocsManager.getDoc(newVal); + var doc = AppDocsManager.getDoc(newVal) if (doc.id && doc.access_hash) { var inputMedia = { _: 'inputMediaDocument', @@ -2709,98 +2689,96 @@ angular.module('myApp.controllers', ['myApp.i18n']) } var options = { replyToMsgID: $scope.draftMessage.replyToMessage && $scope.draftMessage.replyToMessage.mid - }; - AppMessagesManager.sendOther($scope.curDialog.peerID, inputMedia, options); - $scope.$broadcast('ui_message_send'); + } + AppMessagesManager.sendOther($scope.curDialog.peerID, inputMedia, options) + $scope.$broadcast('ui_message_send') - fwdsSend(); - resetDraft(); + fwdsSend() + resetDraft() } - delete $scope.draftMessage.sticker; + delete $scope.draftMessage.sticker } function onCommandSelected (command) { if (!command) { - return; - } - AppMessagesManager.sendText($scope.curDialog.peerID, command); - resetDraft(); - delete $scope.draftMessage.sticker; - delete $scope.draftMessage.text; - delete $scope.draftMessage.command; - delete $scope.draftMessage.inlineResultID; - $scope.$broadcast('ui_message_send'); - $scope.$broadcast('ui_peer_draft'); + return + } + AppMessagesManager.sendText($scope.curDialog.peerID, command) + resetDraft() + delete $scope.draftMessage.sticker + delete $scope.draftMessage.text + delete $scope.draftMessage.command + delete $scope.draftMessage.inlineResultID + $scope.$broadcast('ui_message_send') + $scope.$broadcast('ui_peer_draft') } function onInlineResultSelected (qID) { if (!qID) { - return; + return } if (qID.substr(0, 11) == '_switch_pm_') { - var botID = lastInlineBot.id; - var startParam = qID.substr(11); - return AppInlineBotsManager.switchToPM($scope.curDialog.peerID, botID, startParam); + var botID = lastInlineBot.id + var startParam = qID.substr(11) + return AppInlineBotsManager.switchToPM($scope.curDialog.peerID, botID, startParam) } var options = { replyToMsgID: $scope.draftMessage.replyToMessage && $scope.draftMessage.replyToMessage.mid - }; - AppInlineBotsManager.sendInlineResult($scope.curDialog.peerID, qID, options); - fwdsSend(); - resetDraft(); - delete $scope.draftMessage.sticker; - delete $scope.draftMessage.text; - delete $scope.draftMessage.command; - delete $scope.draftMessage.inlineResultID; - $scope.$broadcast('ui_message_send'); - $scope.$broadcast('ui_peer_draft'); + } + AppInlineBotsManager.sendInlineResult($scope.curDialog.peerID, qID, options) + fwdsSend() + resetDraft() + delete $scope.draftMessage.sticker + delete $scope.draftMessage.text + delete $scope.draftMessage.command + delete $scope.draftMessage.inlineResultID + $scope.$broadcast('ui_message_send') + $scope.$broadcast('ui_peer_draft') } }) .controller('AppLangSelectController', function ($scope, _, Storage, ErrorService, AppRuntimeManager) { - $scope.supportedLocales = Config.I18n.supported; - $scope.langNames = Config.I18n.languages; - $scope.curLocale = Config.I18n.locale; - $scope.form = {locale: Config.I18n.locale}; + $scope.supportedLocales = Config.I18n.supported + $scope.langNames = Config.I18n.languages + $scope.curLocale = Config.I18n.locale + $scope.form = {locale: Config.I18n.locale} $scope.localeSelect = function localeSelect (newLocale) { - newLocale = newLocale || $scope.form.locale; + newLocale = newLocale || $scope.form.locale if ($scope.curLocale !== newLocale) { ErrorService.confirm({type: 'APPLY_LANG_WITH_RELOAD'}).then(function () { Storage.set({i18n_locale: newLocale}).then(function () { - AppRuntimeManager.reload(); - }); + AppRuntimeManager.reload() + }) }, function () { - $scope.form.locale = $scope.curLocale; - }); + $scope.form.locale = $scope.curLocale + }) } - }; + } }) .controller('AppFooterController', function ($scope, LayoutSwitchService) { $scope.switchLayout = function (mobile) { - LayoutSwitchService.switchLayout(mobile); + LayoutSwitchService.switchLayout(mobile) } }) .controller('PhotoModalController', function ($q, $scope, $rootScope, $modalInstance, AppPhotosManager, AppMessagesManager, AppPeersManager, AppWebPagesManager, PeersSelectService, ErrorService) { - - $scope.photo = AppPhotosManager.wrapForFull($scope.photoID); - $scope.nav = {}; + $scope.photo = AppPhotosManager.wrapForFull($scope.photoID) + $scope.nav = {} $scope.download = function () { - AppPhotosManager.downloadPhoto($scope.photoID); - }; + AppPhotosManager.downloadPhoto($scope.photoID) + } if (!$scope.messageID) { - return; + return } - $scope.forward = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID PeersSelectService.selectPeer({canSend: true}).then(function (peerString) { $rootScope.$broadcast('history_focus', { @@ -2809,346 +2787,341 @@ angular.module('myApp.controllers', ['myApp.i18n']) _: 'fwd_messages', id: [messageID] } - }); - }); - }; + }) + }) + } $scope.goToMessage = function () { - var messageID = $scope.messageID; - var peerID = AppMessagesManager.getMessagePeer(AppMessagesManager.getMessage(messageID)); - var peerString = AppPeersManager.getPeerString(peerID); - $modalInstance.dismiss(); - $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: messageID}); - }; + var messageID = $scope.messageID + var peerID = AppMessagesManager.getMessagePeer(AppMessagesManager.getMessage(messageID)) + var peerString = AppPeersManager.getPeerString(peerID) + $modalInstance.dismiss() + $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: messageID}) + } $scope['delete'] = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID ErrorService.confirm({type: 'MESSAGE_DELETE'}).then(function () { - AppMessagesManager.deleteMessages([messageID]); - }); - }; - - var peerID = AppMessagesManager.getMessagePeer(AppMessagesManager.getMessage($scope.messageID)), - inputPeer = AppPeersManager.getInputPeerByID(peerID), - inputQuery = '', - inputFilter = {_: 'inputMessagesFilterPhotos'}, - list = [$scope.messageID], - preloaded = {}, - maxID = $scope.messageID, - hasMore = true; + AppMessagesManager.deleteMessages([messageID]) + }) + } - preloaded[$scope.messageID] = true; + var peerID = AppMessagesManager.getMessagePeer(AppMessagesManager.getMessage($scope.messageID)) + var inputPeer = AppPeersManager.getInputPeerByID(peerID) + var inputQuery = '' + var inputFilter = {_: 'inputMessagesFilterPhotos'} + var list = [$scope.messageID] + var preloaded = {} + var maxID = $scope.messageID + var hasMore = true - updatePrevNext(); + preloaded[$scope.messageID] = true + updatePrevNext() function preloadPhotos (sign) { - // var preloadOffsets = sign < 0 ? [-1,-2,1,-3,2] : [1,2,-1,3,-2]; - var preloadOffsets = sign < 0 ? [-1,-2] : [1,2]; - var index = list.indexOf($scope.messageID); + // var preloadOffsets = sign < 0 ? [-1,-2,1,-3,2] : [1,2,-1,3,-2] + var preloadOffsets = sign < 0 ? [-1, -2] : [1, 2] + var index = list.indexOf($scope.messageID) angular.forEach(preloadOffsets, function (offset) { - var messageID = list[index + offset]; + var messageID = list[index + offset] if (messageID !== undefined && preloaded[messageID] === undefined) { - preloaded[messageID] = true; - var message = AppMessagesManager.getMessage(messageID); - var photoID = message.media.photo.id; - AppPhotosManager.preloadPhoto(photoID); + preloaded[messageID] = true + var message = AppMessagesManager.getMessage(messageID) + var photoID = message.media.photo.id + AppPhotosManager.preloadPhoto(photoID) } }) } function updatePrevNext (count) { - var index = list.indexOf($scope.messageID); + var index = list.indexOf($scope.messageID) if (hasMore) { if (count) { - $scope.count = Math.max(count, list.length); + $scope.count = Math.max(count, list.length) } } else { - $scope.count = list.length; + $scope.count = list.length } - $scope.pos = $scope.count - index; - $scope.nav.hasNext = index > 0; - $scope.nav.hasPrev = hasMore || index < list.length - 1; - $scope.canForward = $scope.canDelete = $scope.messageID > 0; - }; + $scope.pos = $scope.count - index + $scope.nav.hasNext = index > 0 + $scope.nav.hasPrev = hasMore || index < list.length - 1 + $scope.canForward = $scope.canDelete = $scope.messageID > 0 + } $scope.nav.next = function () { if (!$scope.nav.hasNext) { - return false; + return false } - movePosition(-1); - }; + movePosition(-1) + } $scope.nav.prev = function () { if (!$scope.nav.hasPrev) { - return false; + return false } - movePosition(+1); - }; + movePosition(+1) + } $scope.$on('history_delete', function (e, historyUpdate) { if (historyUpdate.peerID == peerID) { if (historyUpdate.msgs[$scope.messageID]) { if ($scope.nav.hasNext) { - $scope.nav.next(); + $scope.nav.next() } else if ($scope.nav.hasPrev) { - $scope.nav.prev(); + $scope.nav.prev() } else { - return $modalInstance.dismiss(); + return $modalInstance.dismiss() } } - var newList = []; + var newList = [] for (var i = 0; i < list.length; i++) { if (!historyUpdate.msgs[list[i]]) { - newList.push(list[i]); + newList.push(list[i]) } - }; - list = newList; + } + list = newList } - }); + }) if ($scope.webpageID) { - $scope.webpage = AppWebPagesManager.wrapForHistory($scope.webpageID); - return; + $scope.webpage = AppWebPagesManager.wrapForHistory($scope.webpageID) + return } AppMessagesManager.getSearch(peerID, inputQuery, inputFilter, 0, 1000).then(function (searchCachedResult) { if (searchCachedResult.history.indexOf($scope.messageID) >= 0) { - list = searchCachedResult.history; - maxID = list[list.length - 1]; + list = searchCachedResult.history + maxID = list[list.length - 1] - updatePrevNext(); - preloadPhotos(+1); + updatePrevNext() + preloadPhotos(+1) } - loadMore(); - }, loadMore); - + loadMore() + }, loadMore) - var jump = 0; + var jump = 0 function movePosition (sign) { - var curIndex = list.indexOf($scope.messageID), - index = curIndex >= 0 ? curIndex + sign : 0, - curJump = ++jump; + var curIndex = list.indexOf($scope.messageID) + var index = curIndex >= 0 ? curIndex + sign : 0 + var curJump = ++jump - var promise = index >= list.length ? loadMore() : $q.when(); + var promise = index >= list.length ? loadMore() : $q.when() promise.then(function () { if (curJump != jump) { - return; + return } - var messageID = list[index]; - var message = AppMessagesManager.getMessage(messageID); + var messageID = list[index] + var message = AppMessagesManager.getMessage(messageID) var photoID = message && message.media && (message.media.photo && message.media.photo.id || message.media.webpage && message.media.webpage.photo && message.media.webpage.photo.id) if (!photoID) { - console.error('Invalid photo message', index, list, messageID, message); - return; + console.error('Invalid photo message', index, list, messageID, message) + return } - $scope.messageID = messageID; - $scope.photoID = photoID; - $scope.photo = AppPhotosManager.wrapForFull($scope.photoID); + $scope.messageID = messageID + $scope.photoID = photoID + $scope.photo = AppPhotosManager.wrapForFull($scope.photoID) - preloaded[$scope.messageID] = true; + preloaded[$scope.messageID] = true - updatePrevNext(); + updatePrevNext() if (sign > 0 && hasMore && list.indexOf(messageID) + 1 >= list.length) { - loadMore(); + loadMore() } else { - preloadPhotos(sign); + preloadPhotos(sign) } - }); - }; + }) + } - var loadingPromise = false; + var loadingPromise = false function loadMore () { - if (loadingPromise) return loadingPromise; + if (loadingPromise) return loadingPromise return loadingPromise = AppMessagesManager.getSearch(peerID, inputQuery, inputFilter, maxID).then(function (searchResult) { if (searchResult.history.length) { - maxID = searchResult.history[searchResult.history.length - 1]; - list = list.concat(searchResult.history); - hasMore = list.length < searchResult.count; + maxID = searchResult.history[searchResult.history.length - 1] + list = list.concat(searchResult.history) + hasMore = list.length < searchResult.count } else { - hasMore = false; + hasMore = false } - updatePrevNext(searchResult.count); - loadingPromise = false; + updatePrevNext(searchResult.count) + loadingPromise = false if (searchResult.history.length) { - return $q.reject(); + return $q.reject() } - preloadPhotos(+1); - }); - }; - + preloadPhotos(+1) + }) + } }) .controller('UserpicModalController', function ($q, $scope, $rootScope, $modalInstance, MtpApiManager, AppPhotosManager, AppUsersManager, AppPeersManager, AppMessagesManager, ApiUpdatesManager, PeersSelectService, ErrorService) { - - $scope.photo = AppPhotosManager.wrapForFull($scope.photoID); + $scope.photo = AppPhotosManager.wrapForFull($scope.photoID) $scope.photo.thumb = { location: AppPhotosManager.choosePhotoSize($scope.photo, 0, 0).location - }; + } - $scope.nav = {}; - $scope.canForward = true; + $scope.nav = {} + $scope.canForward = true - var list = [$scope.photoID], - maxID = $scope.photoID, - preloaded = {}, - myID = 0, - hasMore = true; + var list = [$scope.photoID] + var maxID = $scope.photoID + var preloaded = {} + var myID = 0 + var hasMore = true - updatePrevNext(); + updatePrevNext() AppPhotosManager.getUserPhotos($scope.userID, 0, 1000).then(function (userpicCachedResult) { if (userpicCachedResult.photos.indexOf($scope.photoID) >= 0) { - list = userpicCachedResult.photos; - maxID = list[list.length - 1]; + list = userpicCachedResult.photos + maxID = list[list.length - 1] } - hasMore = list.length < userpicCachedResult.count; - updatePrevNext(); - }); + hasMore = list.length < userpicCachedResult.count + updatePrevNext() + }) MtpApiManager.getUserID().then(function (id) { - myID = id; - $scope.canDelete = $scope.photo.user_id == myID; - }); - + myID = id + $scope.canDelete = $scope.photo.user_id == myID + }) - var jump = 0; + var jump = 0 function movePosition (sign, deleteCurrent) { - var curIndex = list.indexOf($scope.photoID), - index = curIndex >= 0 ? curIndex + sign : 0, - curJump = ++jump; + var curIndex = list.indexOf($scope.photoID) + var index = curIndex >= 0 ? curIndex + sign : 0 + var curJump = ++jump - var promise = index >= list.length ? loadMore() : $q.when(); + var promise = index >= list.length ? loadMore() : $q.when() promise.then(function () { if (curJump != jump) { - return; + return } - $scope.photoID = list[index]; - $scope.photo = AppPhotosManager.wrapForFull($scope.photoID); + $scope.photoID = list[index] + $scope.photo = AppPhotosManager.wrapForFull($scope.photoID) $scope.photo.thumb = { location: AppPhotosManager.choosePhotoSize($scope.photo, 0, 0).location - }; + } - var newCount; + var newCount if (deleteCurrent) { - list.splice(curIndex, 1); - newCount = $scope.count - 1; + list.splice(curIndex, 1) + newCount = $scope.count - 1 } - updatePrevNext(newCount); + updatePrevNext(newCount) - preloaded[$scope.photoID] = true; + preloaded[$scope.photoID] = true - updatePrevNext(); + updatePrevNext() if (sign > 0 && hasMore && list.indexOf($scope.photoID) + 1 >= list.length) { - loadMore(); + loadMore() } else { - preloadPhotos(sign); + preloadPhotos(sign) } - }); - }; + }) + } function preloadPhotos (sign) { - var preloadOffsets = sign < 0 ? [-1,-2] : [1,2]; - var index = list.indexOf($scope.photoID); + var preloadOffsets = sign < 0 ? [-1, -2] : [1, 2] + var index = list.indexOf($scope.photoID) angular.forEach(preloadOffsets, function (offset) { - var photoID = list[index + offset]; + var photoID = list[index + offset] if (photoID !== undefined && preloaded[photoID] === undefined) { - preloaded[photoID] = true; - AppPhotosManager.preloadPhoto(photoID); + preloaded[photoID] = true + AppPhotosManager.preloadPhoto(photoID) } }) } - var loadingPromise = false; + var loadingPromise = false function loadMore () { - if (loadingPromise) return loadingPromise; + if (loadingPromise) return loadingPromise return loadingPromise = AppPhotosManager.getUserPhotos($scope.userID, maxID).then(function (userpicResult) { if (userpicResult.photos.length) { - maxID = userpicResult.photos[userpicResult.photos.length - 1]; - list = list.concat(userpicResult.photos); + maxID = userpicResult.photos[userpicResult.photos.length - 1] + list = list.concat(userpicResult.photos) - hasMore = list.length < userpicResult.count; + hasMore = list.length < userpicResult.count } else { - hasMore = false; + hasMore = false } - updatePrevNext(userpicResult.count); - loadingPromise = false; + updatePrevNext(userpicResult.count) + loadingPromise = false if (userpicResult.photos.length) { - return $q.reject(); + return $q.reject() } - preloadPhotos(+1); - }); - }; + preloadPhotos(+1) + }) + } function updatePrevNext (count) { - var index = list.indexOf($scope.photoID); + var index = list.indexOf($scope.photoID) if (hasMore) { if (count) { - $scope.count = Math.max(count, list.length); + $scope.count = Math.max(count, list.length) } } else { - $scope.count = list.length; + $scope.count = list.length } - $scope.pos = $scope.count - index; - $scope.nav.hasNext = index > 0; - $scope.nav.hasPrev = hasMore || index < list.length - 1; - $scope.canDelete = $scope.photo.user_id == myID; - }; + $scope.pos = $scope.count - index + $scope.nav.hasNext = index > 0 + $scope.nav.hasPrev = hasMore || index < list.length - 1 + $scope.canDelete = $scope.photo.user_id == myID + } $scope.nav.next = function () { if (!$scope.nav.hasNext) { - return false; + return false } - movePosition(-1); - }; + movePosition(-1) + } $scope.nav.prev = function () { if (!$scope.nav.hasPrev) { - return false; + return false } - movePosition(+1); - }; + movePosition(+1) + } $scope.forward = function () { PeersSelectService.selectPeer({confirm_type: 'FORWARD_PEER', canSend: true}).then(function (peerString) { - var peerID = AppPeersManager.getPeerID(peerString); + var peerID = AppPeersManager.getPeerID(peerString) AppMessagesManager.sendOther(peerID, { _: 'inputMediaPhoto', id: { _: 'inputPhoto', id: $scope.photoID, - access_hash: $scope.photo.access_hash, + access_hash: $scope.photo.access_hash } - }); - $rootScope.$broadcast('history_focus', {peerString: peerString}); - }); - }; + }) + $rootScope.$broadcast('history_focus', {peerString: peerString}) + }) + } $scope['delete'] = function () { - var photoID = $scope.photoID; - var myUser = AppUsersManager.getUser(myID); + var photoID = $scope.photoID + var myUser = AppUsersManager.getUser(myID) var onDeleted = function () { if (!$scope.nav.hasNext && !$scope.nav.hasPrev) { - return $modalInstance.dismiss(); + return $modalInstance.dismiss() } - movePosition($scope.nav.hasNext ? -1 : +1, true); - }; + movePosition($scope.nav.hasNext ? -1 : +1, true) + } ErrorService.confirm({type: 'PHOTO_DELETE'}).then(function () { if (myUser && myUser.photo && myUser.photo.photo_id == photoID) { @@ -3165,93 +3138,87 @@ angular.module('myApp.controllers', ['myApp.i18n']) photo: updateResult, previous: true } - }); - onDeleted(); - }); - } - else { + }) + onDeleted() + }) + }else { MtpApiManager.invokeApi('photos.deletePhotos', { id: [{_: 'inputPhoto', id: photoID, access_hash: 0}] - }).then(onDeleted); + }).then(onDeleted) } - }); - }; + }) + } $scope.download = function () { - AppPhotosManager.downloadPhoto($scope.photoID); - }; - + AppPhotosManager.downloadPhoto($scope.photoID) + } }) .controller('ChatpicModalController', function ($q, $scope, $rootScope, $modalInstance, MtpApiManager, AppPhotosManager, AppChatsManager, AppPeersManager, AppMessagesManager, ApiUpdatesManager, PeersSelectService, ErrorService) { - - $scope.photo = AppPhotosManager.wrapForFull($scope.photoID); + $scope.photo = AppPhotosManager.wrapForFull($scope.photoID) $scope.photo.thumb = { location: AppPhotosManager.choosePhotoSize($scope.photo, 0, 0).location - }; + } - var chat = AppChatsManager.getChat($scope.chatID); - var isChannel = AppChatsManager.isChannel($scope.chatID); + var chat = AppChatsManager.getChat($scope.chatID) + var isChannel = AppChatsManager.isChannel($scope.chatID) - $scope.canForward = true; - $scope.canDelete = isChannel ? chat.pFlags.creator : true; + $scope.canForward = true + $scope.canDelete = isChannel ? chat.pFlags.creator : true $scope.forward = function () { PeersSelectService.selectPeer({confirm_type: 'FORWARD_PEER', canSend: true}).then(function (peerString) { - var peerID = AppPeersManager.getPeerID(peerString); + var peerID = AppPeersManager.getPeerID(peerString) AppMessagesManager.sendOther(peerID, { _: 'inputMediaPhoto', id: { _: 'inputPhoto', id: $scope.photoID, - access_hash: $scope.photo.access_hash, + access_hash: $scope.photo.access_hash } - }); - $rootScope.$broadcast('history_focus', {peerString: peerString}); - }); - }; + }) + $rootScope.$broadcast('history_focus', {peerString: peerString}) + }) + } $scope['delete'] = function () { ErrorService.confirm({type: 'PHOTO_DELETE'}).then(function () { - $scope.photo.updating = true; - var apiPromise; + $scope.photo.updating = true + var apiPromise if (AppChatsManager.isChannel($scope.chatID)) { apiPromise = MtpApiManager.invokeApi('channels.editPhoto', { channel: AppChatsManager.getChannelInput($scope.chatID), photo: {_: 'inputChatPhotoEmpty'} - }); + }) } else { apiPromise = MtpApiManager.invokeApi('messages.editChatPhoto', { chat_id: AppChatsManager.getChatInput($scope.chatID), photo: {_: 'inputChatPhotoEmpty'} - }); + }) } apiPromise.then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - $modalInstance.dismiss(); - $rootScope.$broadcast('history_focus', {peerString: AppChatsManager.getChatString($scope.chatID)}); + ApiUpdatesManager.processUpdateMessage(updates) + $modalInstance.dismiss() + $rootScope.$broadcast('history_focus', {peerString: AppChatsManager.getChatString($scope.chatID)}) })['finally'](function () { - $scope.photo.updating = false; - }); - }); - }; + $scope.photo.updating = false + }) + }) + } $scope.download = function () { - AppPhotosManager.downloadPhoto($scope.photoID); - }; - + AppPhotosManager.downloadPhoto($scope.photoID) + } }) .controller('VideoModalController', function ($scope, $rootScope, $modalInstance, PeersSelectService, AppMessagesManager, AppDocsManager, AppPeersManager, ErrorService) { + $scope.video = AppDocsManager.wrapVideoForFull($scope.docID) - $scope.video = AppDocsManager.wrapVideoForFull($scope.docID); - - $scope.progress = {enabled: false}; - $scope.player = {}; - + $scope.progress = {enabled: false} + $scope.player = {} $scope.forward = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID PeersSelectService.selectPeer({canSend: true}).then(function (peerString) { $rootScope.$broadcast('history_focus', { peerString: peerString, @@ -3259,34 +3226,33 @@ angular.module('myApp.controllers', ['myApp.i18n']) _: 'fwd_messages', id: [messageID] } - }); - }); - }; + }) + }) + } $scope['delete'] = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID ErrorService.confirm({type: 'MESSAGE_DELETE'}).then(function () { - AppMessagesManager.deleteMessages([messageID]); - }); - }; + AppMessagesManager.deleteMessages([messageID]) + }) + } $scope.download = function () { - AppDocsManager.saveDocFile($scope.docID); - }; + AppDocsManager.saveDocFile($scope.docID) + } $scope.$on('history_delete', function (e, historyUpdate) { if (historyUpdate.msgs[$scope.messageID]) { - $modalInstance.dismiss(); + $modalInstance.dismiss() } - }); + }) }) .controller('DocumentModalController', function ($scope, $rootScope, $modalInstance, PeersSelectService, AppMessagesManager, AppDocsManager, AppPeersManager, ErrorService) { - - $scope.document = AppDocsManager.wrapForHistory($scope.docID); + $scope.document = AppDocsManager.wrapForHistory($scope.docID) $scope.forward = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID PeersSelectService.selectPeer({canSend: true}).then(function (peerString) { $rootScope.$broadcast('history_focus', { peerString: peerString, @@ -3294,36 +3260,35 @@ angular.module('myApp.controllers', ['myApp.i18n']) _: 'fwd_messages', id: [messageID] } - }); - }); - }; + }) + }) + } $scope['delete'] = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID ErrorService.confirm({type: 'MESSAGE_DELETE'}).then(function () { - AppMessagesManager.deleteMessages([messageID]); - }); - }; + AppMessagesManager.deleteMessages([messageID]) + }) + } $scope.download = function () { - AppDocsManager.saveDocFile($scope.docID); - }; + AppDocsManager.saveDocFile($scope.docID) + } $scope.$on('history_delete', function (e, historyUpdate) { if (historyUpdate.msgs[$scope.messageID]) { - $modalInstance.dismiss(); + $modalInstance.dismiss() } - }); + }) }) .controller('EmbedModalController', function ($q, $scope, $rootScope, $modalInstance, AppPhotosManager, AppMessagesManager, AppPeersManager, AppWebPagesManager, PeersSelectService, ErrorService) { + $scope.webpage = AppWebPagesManager.wrapForFull($scope.webpageID) - $scope.webpage = AppWebPagesManager.wrapForFull($scope.webpageID); - - $scope.nav = {}; + $scope.nav = {} $scope.forward = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID PeersSelectService.selectPeer({canSend: true}).then(function (peerString) { $rootScope.$broadcast('history_focus', { peerString: peerString, @@ -3331,73 +3296,70 @@ angular.module('myApp.controllers', ['myApp.i18n']) _: 'fwd_messages', id: [messageID] } - }); - }); - }; + }) + }) + } $scope['delete'] = function () { - var messageID = $scope.messageID; + var messageID = $scope.messageID ErrorService.confirm({type: 'MESSAGE_DELETE'}).then(function () { - AppMessagesManager.deleteMessages([messageID]); - }); - }; - + AppMessagesManager.deleteMessages([messageID]) + }) + } }) .controller('UserModalController', function ($scope, $location, $rootScope, $modalInstance, AppProfileManager, $modal, AppUsersManager, MtpApiManager, NotificationsManager, AppPhotosManager, AppMessagesManager, AppPeersManager, PeersSelectService, ErrorService) { + var peerString = AppUsersManager.getUserString($scope.userID) - var peerString = AppUsersManager.getUserString($scope.userID); - - $scope.user = AppUsersManager.getUser($scope.userID); - $scope.blocked = false; + $scope.user = AppUsersManager.getUser($scope.userID) + $scope.blocked = false - $scope.settings = {notifications: true}; + $scope.settings = {notifications: true} AppProfileManager.getProfile($scope.userID, $scope.override).then(function (userFull) { - $scope.blocked = userFull.pFlags.blocked; - $scope.bot_info = userFull.bot_info; - $scope.rAbout = userFull.rAbout; + $scope.blocked = userFull.pFlags.blocked + $scope.bot_info = userFull.bot_info + $scope.rAbout = userFull.rAbout NotificationsManager.getPeerMuted($scope.userID).then(function (muted) { - $scope.settings.notifications = !muted; + $scope.settings.notifications = !muted - $scope.$watch('settings.notifications', function(newValue, oldValue) { + $scope.$watch('settings.notifications', function (newValue, oldValue) { if (newValue === oldValue) { - return false; + return false } NotificationsManager.getPeerSettings($scope.userID).then(function (settings) { - settings.mute_until = newValue ? 0 : 2000000000; - NotificationsManager.updatePeerSettings($scope.userID, settings); - }); - }); - }); - }); - + settings.mute_until = newValue ? 0 : 2000000000 + NotificationsManager.updatePeerSettings($scope.userID, settings) + }) + }) + }) + }) $scope.goToHistory = function () { - $rootScope.$broadcast('history_focus', {peerString: peerString}); - }; + $rootScope.$broadcast('history_focus', {peerString: peerString}) + } $scope.flushHistory = function (justClear) { ErrorService.confirm({type: justClear ? 'HISTORY_FLUSH' : 'HISTORY_FLUSH_AND_DELETE'}).then(function () { AppMessagesManager.flushHistory($scope.userID, justClear).then(function () { if (justClear) { - $scope.goToHistory(); + $scope.goToHistory() } else { - $modalInstance.close(); - $location.url('/im'); + $modalInstance.close() + $location.url('/im') } - }); - }); - }; + }) + }) + } $scope.importContact = function (edit) { - var scope = $rootScope.$new(); + var scope = $rootScope.$new() scope.importContact = { phone: $scope.user.phone, first_name: $scope.user.first_name, - last_name: $scope.user.last_name, - }; + last_name: $scope.user.last_name + } $modal.open({ templateUrl: templateUrl(edit ? 'edit_contact_modal' : 'import_contact_modal'), @@ -3406,129 +3368,125 @@ angular.module('myApp.controllers', ['myApp.i18n']) scope: scope }).result.then(function (foundUserID) { if ($scope.userID == foundUserID) { - $scope.user = AppUsersManager.getUser($scope.userID); + $scope.user = AppUsersManager.getUser($scope.userID) } - }); - }; + }) + } $scope.deleteContact = function () { AppUsersManager.deleteContacts([$scope.userID]).then(function () { - $scope.user = AppUsersManager.getUser($scope.userID); - }); - }; + $scope.user = AppUsersManager.getUser($scope.userID) + }) + } $scope.inviteToGroup = function () { PeersSelectService.selectPeer({ confirm_type: 'INVITE_TO_GROUP', noUsers: true }).then(function (peerString) { - var peerID = AppPeersManager.getPeerID(peerString); - var chatID = peerID < 0 ? -peerID : 0; + var peerID = AppPeersManager.getPeerID(peerString) + var chatID = peerID < 0 ? -peerID : 0 AppMessagesManager.startBot($scope.user.id, chatID).then(function () { - $rootScope.$broadcast('history_focus', {peerString: peerString}); - }); - }); - }; + $rootScope.$broadcast('history_focus', {peerString: peerString}) + }) + }) + } $scope.sendCommand = function (command) { - AppMessagesManager.sendText($scope.userID, '/' + command); + AppMessagesManager.sendText($scope.userID, '/' + command) $rootScope.$broadcast('history_focus', { peerString: peerString - }); - }; + }) + } $scope.toggleBlock = function (block) { MtpApiManager.invokeApi(block ? 'contacts.block' : 'contacts.unblock', { id: AppUsersManager.getUserInput($scope.userID) }).then(function () { - $scope.blocked = block; - }); - }; + $scope.blocked = block + }) + } $scope.shareContact = function () { PeersSelectService.selectPeer({confirm_type: 'SHARE_CONTACT_PEER', canSend: true}).then(function (peerString) { - var peerID = AppPeersManager.getPeerID(peerString); + var peerID = AppPeersManager.getPeerID(peerString) AppMessagesManager.sendOther(peerID, { _: 'inputMediaContact', phone_number: $scope.user.phone, first_name: $scope.user.first_name, last_name: $scope.user.last_name, user_id: $scope.user.id - }); - $rootScope.$broadcast('history_focus', {peerString: peerString}); - }); + }) + $rootScope.$broadcast('history_focus', {peerString: peerString}) + }) } - }) .controller('ChatModalController', function ($scope, $modalInstance, $location, $timeout, $rootScope, $modal, AppUsersManager, AppChatsManager, AppProfileManager, AppPhotosManager, MtpApiManager, MtpApiFileManager, NotificationsManager, AppMessagesManager, AppPeersManager, ApiUpdatesManager, ContactsSelectService, ErrorService) { + $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, {}) + $scope.settings = {notifications: true} - $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, {}); - $scope.settings = {notifications: true}; - - $scope.maxParticipants = 200; + $scope.maxParticipants = 200 AppProfileManager.getChatFull($scope.chatID).then(function (chatFull) { - $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, chatFull); - $scope.$broadcast('ui_height'); + $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, chatFull) + $scope.$broadcast('ui_height') $scope.needMigrate = $scope.chatFull && - $scope.chatFull.participants && - $scope.chatFull.participants.participants && - $scope.chatFull.participants.participants.length >= 200; + $scope.chatFull.participants && + $scope.chatFull.participants.participants && + $scope.chatFull.participants.participants.length >= 200 if (Config.Modes.test || Config.Modes.debug) { - $scope.needMigrate = true; + $scope.needMigrate = true } - NotificationsManager.savePeerSettings(-$scope.chatID, chatFull.notify_settings); + NotificationsManager.savePeerSettings(-$scope.chatID, chatFull.notify_settings) NotificationsManager.getPeerMuted(-$scope.chatID).then(function (muted) { - $scope.settings.notifications = !muted; + $scope.settings.notifications = !muted - $scope.$watch('settings.notifications', function(newValue, oldValue) { + $scope.$watch('settings.notifications', function (newValue, oldValue) { if (newValue === oldValue) { - return false; + return false } NotificationsManager.getPeerSettings(-$scope.chatID).then(function (settings) { if (newValue) { - settings.mute_until = 0; + settings.mute_until = 0 } else { - settings.mute_until = 2000000000; + settings.mute_until = 2000000000 } - NotificationsManager.updatePeerSettings(-$scope.chatID, settings); - }); - }); - }); - }); - + NotificationsManager.updatePeerSettings(-$scope.chatID, settings) + }) + }) + }) + }) function onChatUpdated (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); + ApiUpdatesManager.processUpdateMessage(updates) + $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}) } - $scope.leaveGroup = function () { ErrorService.confirm({type: 'HISTORY_LEAVE_AND_FLUSH'}).then(function () { MtpApiManager.invokeApi('messages.deleteChatUser', { chat_id: AppChatsManager.getChatInput($scope.chatID), user_id: {_: 'inputUserSelf'} }).then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); + ApiUpdatesManager.processUpdateMessage(updates) AppMessagesManager.flushHistory(-$scope.chatID).then(function () { - $modalInstance.close(); - $location.url('/im'); - }); - }); - }); - }; + $modalInstance.close() + $location.url('/im') + }) + }) + }) + } $scope.inviteToGroup = function () { - var disabled = []; - angular.forEach($scope.chatFull.participants.participants, function(participant){ - disabled.push(participant.user_id); - }); + var disabled = [] + angular.forEach($scope.chatFull.participants.participants, function (participant) { + disabled.push(participant.user_id) + }) ContactsSelectService.selectContacts({disabled: disabled}).then(function (userIDs) { angular.forEach(userIDs, function (userID) { @@ -3537,66 +3495,63 @@ angular.module('myApp.controllers', ['myApp.i18n']) user_id: AppUsersManager.getUserInput(userID), fwd_limit: 100 }).then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - }); - }); + ApiUpdatesManager.processUpdateMessage(updates) + }) + }) - $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); - }); - }; + $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}) + }) + } $scope.migrateToSuperGroup = function () { ErrorService.confirm({type: 'SUPERGROUP_MIGRATE'}).then(function () { MtpApiManager.invokeApi('messages.migrateChat', { chat_id: AppChatsManager.getChatInput($scope.chatID) - }).then(onChatUpdated); - }); + }).then(onChatUpdated) + }) } $scope.kickFromGroup = function (userID) { MtpApiManager.invokeApi('messages.deleteChatUser', { chat_id: AppChatsManager.getChatInput($scope.chatID), user_id: AppUsersManager.getUserInput(userID) - }).then(onChatUpdated); - }; - - + }).then(onChatUpdated) + } $scope.flushHistory = function (justClear) { ErrorService.confirm({type: justClear ? 'HISTORY_FLUSH' : 'HISTORY_FLUSH_AND_DELETE'}).then(function () { AppMessagesManager.flushHistory(-$scope.chatID, justClear).then(function () { if (justClear) { - $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); + $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}) } else { - $modalInstance.close(); - $location.url('/im'); + $modalInstance.close() + $location.url('/im') } - }); - }); - }; + }) + }) + } $scope.inviteViaLink = function () { - var scope = $rootScope.$new(); - scope.chatID = $scope.chatID; + var scope = $rootScope.$new() + scope.chatID = $scope.chatID $modal.open({ templateUrl: templateUrl('chat_invite_link_modal'), controller: 'ChatInviteLinkModalController', scope: scope, windowClass: 'md_simple_modal_window' - }); + }) } + $scope.photo = {} - $scope.photo = {}; - - $scope.$watch('photo.file', onPhotoSelected); + $scope.$watch('photo.file', onPhotoSelected) function onPhotoSelected (photo) { if (!photo || !photo.type || photo.type.indexOf('image') !== 0) { - return; + return } - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiFileManager.uploadFile(photo).then(function (inputFile) { return MtpApiManager.invokeApi('messages.editChatPhoto', { chat_id: AppChatsManager.getChatInput($scope.chatID), @@ -3605,156 +3560,152 @@ angular.module('myApp.controllers', ['myApp.i18n']) file: inputFile, crop: {_: 'inputPhotoCropAuto'} } - }).then(onChatUpdated); + }).then(onChatUpdated) })['finally'](function () { - $scope.photo.updating = false; - }); - }; + $scope.photo.updating = false + }) + } $scope.deletePhoto = function () { - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiManager.invokeApi('messages.editChatPhoto', { chat_id: AppChatsManager.getChatInput($scope.chatID), photo: {_: 'inputChatPhotoEmpty'} }).then(onChatUpdated)['finally'](function () { - $scope.photo.updating = false; - }); - }; + $scope.photo.updating = false + }) + } $scope.editTitle = function () { - var scope = $rootScope.$new(); - scope.chatID = $scope.chatID; + var scope = $rootScope.$new() + scope.chatID = $scope.chatID $modal.open({ templateUrl: templateUrl('chat_edit_modal'), controller: 'ChatEditModalController', scope: scope, windowClass: 'md_simple_modal_window mobile_modal' - }); + }) } $scope.hasRights = function (action) { - return AppChatsManager.hasRights($scope.chatID, action); + return AppChatsManager.hasRights($scope.chatID, action) } - }) .controller('ChannelModalController', function ($scope, $timeout, $rootScope, $modal, AppUsersManager, AppChatsManager, AppProfileManager, AppPhotosManager, MtpApiManager, MtpApiFileManager, NotificationsManager, AppMessagesManager, AppPeersManager, ApiUpdatesManager, ContactsSelectService, ErrorService) { - - $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, {}); - $scope.settings = {notifications: true}; - $scope.isMegagroup = AppChatsManager.isMegagroup($scope.chatID); + $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, {}) + $scope.settings = {notifications: true} + $scope.isMegagroup = AppChatsManager.isMegagroup($scope.chatID) AppProfileManager.getChannelFull($scope.chatID, true).then(function (chatFull) { - $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, chatFull); - $scope.$broadcast('ui_height'); + $scope.chatFull = AppChatsManager.wrapForFull($scope.chatID, chatFull) + $scope.$broadcast('ui_height') - NotificationsManager.savePeerSettings(-$scope.chatID, chatFull.notify_settings); + NotificationsManager.savePeerSettings(-$scope.chatID, chatFull.notify_settings) NotificationsManager.getPeerMuted(-$scope.chatID).then(function (muted) { - $scope.settings.notifications = !muted; + $scope.settings.notifications = !muted - $scope.$watch('settings.notifications', function(newValue, oldValue) { + $scope.$watch('settings.notifications', function (newValue, oldValue) { if (newValue === oldValue) { - return false; + return false } NotificationsManager.getPeerSettings(-$scope.chatID).then(function (settings) { if (newValue) { - settings.mute_until = 0; + settings.mute_until = 0 } else { - settings.mute_until = 2000000000; + settings.mute_until = 2000000000 } - NotificationsManager.updatePeerSettings(-$scope.chatID, settings); - }); - }); - }); + NotificationsManager.updatePeerSettings(-$scope.chatID, settings) + }) + }) + }) if ($scope.chatFull.chat && - $scope.chatFull.chat.pFlags.creator && - $scope.chatFull.exported_invite && - $scope.chatFull.exported_invite._ == 'chatInviteEmpty') { + $scope.chatFull.chat.pFlags.creator && + $scope.chatFull.exported_invite && + $scope.chatFull.exported_invite._ == 'chatInviteEmpty') { AppProfileManager.getChatInviteLink($scope.chatID, true).then(function (link) { - $scope.chatFull.exported_invite = {_: 'chatInviteExported', link: link}; - }); + $scope.chatFull.exported_invite = {_: 'chatInviteExported', link: link} + }) } - }); - + }) function onChatUpdated (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); + ApiUpdatesManager.processUpdateMessage(updates) + $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}) } $scope.leaveChannel = function () { MtpApiManager.invokeApi('channels.leaveChannel', { channel: AppChatsManager.getChannelInput($scope.chatID) - }).then(onChatUpdated); - }; + }).then(onChatUpdated) + } $scope.deleteChannel = function () { return ErrorService.confirm({type: $scope.isMegagroup ? 'MEGAGROUP_DELETE' : 'CHANNEL_DELETE'}).then(function () { MtpApiManager.invokeApi('channels.deleteChannel', { channel: AppChatsManager.getChannelInput($scope.chatID) - }).then(onChatUpdated); - }); + }).then(onChatUpdated) + }) } $scope.joinChannel = function () { MtpApiManager.invokeApi('channels.joinChannel', { channel: AppChatsManager.getChannelInput($scope.chatID) - }).then(onChatUpdated); - }; + }).then(onChatUpdated) + } $scope.inviteToChannel = function () { - var disabled = []; - angular.forEach(($scope.chatFull.participants || {}).participants || [], function(participant){ - disabled.push(participant.user_id); - }); + var disabled = [] + angular.forEach(($scope.chatFull.participants || {}).participants || [], function (participant) { + disabled.push(participant.user_id) + }) ContactsSelectService.selectContacts({disabled: disabled}).then(function (userIDs) { - var inputUsers = []; + var inputUsers = [] angular.forEach(userIDs, function (userID) { - inputUsers.push(AppUsersManager.getUserInput(userID)); - }); + inputUsers.push(AppUsersManager.getUserInput(userID)) + }) MtpApiManager.invokeApi('channels.inviteToChannel', { channel: AppChatsManager.getChannelInput($scope.chatID), users: inputUsers - }).then(onChatUpdated); - }); - }; + }).then(onChatUpdated) + }) + } $scope.kickFromChannel = function (userID) { MtpApiManager.invokeApi('channels.kickFromChannel', { channel: AppChatsManager.getChannelInput($scope.chatID), user_id: AppUsersManager.getUserInput(userID), kicked: true - }).then(onChatUpdated); - }; + }).then(onChatUpdated) + } $scope.shareLink = function ($event) { - var scope = $rootScope.$new(); - scope.chatID = $scope.chatID; + var scope = $rootScope.$new() + scope.chatID = $scope.chatID $modal.open({ templateUrl: templateUrl('chat_invite_link_modal'), controller: 'ChatInviteLinkModalController', scope: scope, windowClass: 'md_simple_modal_window' - }); + }) - return cancelEvent($event); + return cancelEvent($event) } + $scope.photo = {} - $scope.photo = {}; - - $scope.$watch('photo.file', onPhotoSelected); + $scope.$watch('photo.file', onPhotoSelected) function onPhotoSelected (photo) { if (!photo || !photo.type || photo.type.indexOf('image') !== 0) { - return; + return } - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiFileManager.uploadFile(photo).then(function (inputFile) { return MtpApiManager.invokeApi('channels.editPhoto', { channel: AppChatsManager.getChannelInput($scope.chatID), @@ -3763,125 +3714,122 @@ angular.module('myApp.controllers', ['myApp.i18n']) file: inputFile, crop: {_: 'inputPhotoCropAuto'} } - }).then(onChatUpdated); + }).then(onChatUpdated) })['finally'](function () { - $scope.photo.updating = false; - }); - }; + $scope.photo.updating = false + }) + } $scope.deletePhoto = function () { - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiManager.invokeApi('channels.editPhoto', { channel: AppChatsManager.getChannelInput($scope.chatID), photo: {_: 'inputChatPhotoEmpty'} }).then(onChatUpdated)['finally'](function () { - $scope.photo.updating = false; - }); - }; + $scope.photo.updating = false + }) + } $scope.editChannel = function () { - var scope = $rootScope.$new(); - scope.chatID = $scope.chatID; + var scope = $rootScope.$new() + scope.chatID = $scope.chatID $modal.open({ templateUrl: templateUrl($scope.isMegagroup ? 'megagroup_edit_modal' : 'channel_edit_modal'), controller: 'ChannelEditModalController', scope: scope, windowClass: 'md_simple_modal_window mobile_modal' - }); + }) } $scope.goToHistory = function () { - $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}); - }; + $rootScope.$broadcast('history_focus', {peerString: $scope.chatFull.peerString}) + } $scope.hasRights = function (action) { - return AppChatsManager.hasRights($scope.chatID, action); + return AppChatsManager.hasRights($scope.chatID, action) } - }) .controller('SettingsModalController', function ($rootScope, $scope, $timeout, $modal, AppUsersManager, AppChatsManager, AppPhotosManager, MtpApiManager, Storage, NotificationsManager, MtpApiFileManager, PasswordManager, ApiUpdatesManager, ChangelogNotifyService, LayoutSwitchService, AppRuntimeManager, ErrorService, _) { - - $scope.profile = {}; - $scope.photo = {}; - $scope.version = Config.App.version; + $scope.profile = {} + $scope.photo = {} + $scope.version = Config.App.version MtpApiManager.getUserID().then(function (id) { - $scope.profile = AppUsersManager.getUser(id); - }); + $scope.profile = AppUsersManager.getUser(id) + }) MtpApiManager.invokeApi('users.getFullUser', { id: {_: 'inputUserSelf'} }).then(function (userFullResult) { - AppUsersManager.saveApiUser(userFullResult.user); + AppUsersManager.saveApiUser(userFullResult.user) if (userFullResult.profile_photo) { AppPhotosManager.savePhoto(userFullResult.profile_photo, { user_id: userFullResult.user.id - }); + }) } - }); + }) - $scope.notify = {volume: 0.5}; - $scope.send = {}; + $scope.notify = {volume: 0.5} + $scope.send = {} - $scope.$watch('photo.file', onPhotoSelected); + $scope.$watch('photo.file', onPhotoSelected) - $scope.password = {_: 'account.noPassword'}; - updatePasswordState(); - var updatePasswordTimeout = false; - var stopped = false; + $scope.password = {_: 'account.noPassword'} + updatePasswordState() + var updatePasswordTimeout = false + var stopped = false $scope.changePassword = function (options) { - options = options || {}; + options = options || {} if (options.action == 'cancel_email') { return ErrorService.confirm({type: 'PASSWORD_ABORT_SETUP'}).then(function () { - PasswordManager.updateSettings($scope.password, {email: ''}).then(updatePasswordState); - }); + PasswordManager.updateSettings($scope.password, {email: ''}).then(updatePasswordState) + }) } - var scope = $rootScope.$new(); - scope.password = $scope.password; - angular.extend(scope, options); + var scope = $rootScope.$new() + scope.password = $scope.password + angular.extend(scope, options) var modal = $modal.open({ scope: scope, templateUrl: templateUrl('password_update_modal'), controller: 'PasswordUpdateModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); + }) - modal.result['finally'](updatePasswordState); - }; + modal.result['finally'](updatePasswordState) + } $scope.showSessions = function () { $modal.open({ templateUrl: templateUrl('sessions_list_modal'), controller: 'SessionsListModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); - }; + }) + } function updatePasswordState () { - $timeout.cancel(updatePasswordTimeout); - updatePasswordTimeout = false; + $timeout.cancel(updatePasswordTimeout) + updatePasswordTimeout = false PasswordManager.getState().then(function (result) { - $scope.password = result; + $scope.password = result if (result._ == 'account.noPassword' && result.email_unconfirmed_pattern && !stopped) { - updatePasswordTimeout = $timeout(updatePasswordState, 5000); + updatePasswordTimeout = $timeout(updatePasswordState, 5000) } - }); + }) } $scope.$on('$destroy', function () { - $timeout.cancel(updatePasswordTimeout); - stopped = true; - }); - + $timeout.cancel(updatePasswordTimeout) + stopped = true + }) function onPhotoSelected (photo) { if (!photo || !photo.type || photo.type.indexOf('image') !== 0) { - return; + return } - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiFileManager.uploadFile(photo).then(function (inputFile) { MtpApiManager.invokeApi('photos.uploadProfilePhoto', { file: inputFile, @@ -3889,11 +3837,11 @@ angular.module('myApp.controllers', ['myApp.i18n']) geo_point: {_: 'inputGeoPointEmpty'}, crop: {_: 'inputPhotoCropAuto'} }).then(function (updateResult) { - AppUsersManager.saveApiUsers(updateResult.users); + AppUsersManager.saveApiUsers(updateResult.users) MtpApiManager.getUserID().then(function (id) { AppPhotosManager.savePhoto(updateResult.photo, { user_id: id - }); + }) ApiUpdatesManager.processUpdateMessage({ _: 'updateShort', update: { @@ -3903,17 +3851,17 @@ angular.module('myApp.controllers', ['myApp.i18n']) photo: AppUsersManager.getUser(id).photo, previous: true } - }); - $scope.photo = {}; - }); - }); + }) + $scope.photo = {} + }) + }) })['finally'](function () { - delete $scope.photo.updating; - }); - }; + delete $scope.photo.updating + }) + } $scope.deletePhoto = function () { - $scope.photo.updating = true; + $scope.photo.updating = true MtpApiManager.invokeApi('photos.updateProfilePhoto', { id: {_: 'inputPhotoEmpty'}, crop: {_: 'inputPhotoCropAuto'} @@ -3928,380 +3876,372 @@ angular.module('myApp.controllers', ['myApp.i18n']) photo: updateResult, previous: true } - }); - $scope.photo = {}; - }); + }) + $scope.photo = {} + }) })['finally'](function () { - delete $scope.photo.updating; - }); - }; + delete $scope.photo.updating + }) + } $scope.editProfile = function () { $modal.open({ templateUrl: templateUrl('profile_edit_modal'), controller: 'ProfileEditModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); - }; + }) + } $scope.changeUsername = function () { $modal.open({ templateUrl: templateUrl('username_edit_modal'), controller: 'UsernameEditModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); - }; + }) + } $scope.terminateSessions = function () { ErrorService.confirm({type: 'TERMINATE_SESSIONS'}).then(function () { - MtpApiManager.invokeApi('auth.resetAuthorizations', {}); - }); - }; + MtpApiManager.invokeApi('auth.resetAuthorizations', {}) + }) + } Storage.get('notify_nodesktop', 'send_ctrlenter', 'notify_volume', 'notify_novibrate', 'notify_nopreview').then(function (settings) { - $scope.notify.desktop = !settings[0]; - $scope.send.enter = settings[1] ? '' : '1'; + $scope.notify.desktop = !settings[0] + $scope.send.enter = settings[1] ? '' : '1' if (settings[2] !== false) { - $scope.notify.volume = settings[2] > 0 && settings[2] <= 1.0 ? settings[2] : 0; + $scope.notify.volume = settings[2] > 0 && settings[2] <= 1.0 ? settings[2] : 0 } else { - $scope.notify.volume = 0.5; + $scope.notify.volume = 0.5 } - $scope.notify.canVibrate = NotificationsManager.getVibrateSupport(); - $scope.notify.vibrate = !settings[3]; + $scope.notify.canVibrate = NotificationsManager.getVibrateSupport() + $scope.notify.vibrate = !settings[3] - $scope.notify.preview = !settings[4]; + $scope.notify.preview = !settings[4] $scope.notify.volumeOf4 = function () { - return 1 + Math.ceil(($scope.notify.volume - 0.1) / 0.33); - }; + return 1 + Math.ceil(($scope.notify.volume - 0.1) / 0.33) + } $scope.toggleSound = function () { if ($scope.notify.volume) { - $scope.notify.volume = 0; + $scope.notify.volume = 0 } else { - $scope.notify.volume = 0.5; + $scope.notify.volume = 0.5 } } - var testSoundPromise; + var testSoundPromise $scope.$watch('notify.volume', function (newValue, oldValue) { if (newValue !== oldValue) { - Storage.set({notify_volume: newValue}); - $rootScope.$broadcast('settings_changed'); - NotificationsManager.clear(); + Storage.set({notify_volume: newValue}) + $rootScope.$broadcast('settings_changed') + NotificationsManager.clear() if (testSoundPromise) { - $timeout.cancel(testSoundPromise); + $timeout.cancel(testSoundPromise) } testSoundPromise = $timeout(function () { - NotificationsManager.testSound(newValue); - }, 500); + NotificationsManager.testSound(newValue) + }, 500) } - }); + }) $scope.toggleDesktop = function () { - $scope.notify.desktop = !$scope.notify.desktop; + $scope.notify.desktop = !$scope.notify.desktop if ($scope.notify.desktop) { - Storage.remove('notify_nodesktop'); + Storage.remove('notify_nodesktop') } else { - Storage.set({notify_nodesktop: true}); + Storage.set({notify_nodesktop: true}) } - $rootScope.$broadcast('settings_changed'); + $rootScope.$broadcast('settings_changed') } $scope.togglePreview = function () { - $scope.notify.preview = !$scope.notify.preview; + $scope.notify.preview = !$scope.notify.preview if ($scope.notify.preview) { - Storage.remove('notify_nopreview'); + Storage.remove('notify_nopreview') } else { - Storage.set({notify_nopreview: true}); + Storage.set({notify_nopreview: true}) } - $rootScope.$broadcast('settings_changed'); + $rootScope.$broadcast('settings_changed') } $scope.toggleVibrate = function () { - $scope.notify.vibrate = !$scope.notify.vibrate; + $scope.notify.vibrate = !$scope.notify.vibrate if ($scope.notify.vibrate) { - Storage.remove('notify_novibrate'); + Storage.remove('notify_novibrate') } else { - Storage.set({notify_novibrate: true}); + Storage.set({notify_novibrate: true}) } - $rootScope.$broadcast('settings_changed'); + $rootScope.$broadcast('settings_changed') } $scope.toggleCtrlEnter = function (newValue) { - $scope.send.enter = newValue; + $scope.send.enter = newValue if ($scope.send.enter) { - Storage.remove('send_ctrlenter'); + Storage.remove('send_ctrlenter') } else { - Storage.set({send_ctrlenter: true}); + Storage.set({send_ctrlenter: true}) } - $rootScope.$broadcast('settings_changed'); + $rootScope.$broadcast('settings_changed') } - }); + }) $scope.openChangelog = function () { - ChangelogNotifyService.showChangelog(false); - }; + ChangelogNotifyService.showChangelog(false) + } $scope.logOut = function () { ErrorService.confirm({type: 'LOGOUT'}).then(function () { MtpApiManager.logOut().then(function () { - location.hash = '/login'; - AppRuntimeManager.reload(); - }); + location.hash = '/login' + AppRuntimeManager.reload() + }) }) - }; + } - $scope.switchBackToDesktop = Config.Mobile && !Config.Navigator.mobile; + $scope.switchBackToDesktop = Config.Mobile && !Config.Navigator.mobile $scope.switchToDesktop = function () { - LayoutSwitchService.switchLayout(false); - }; + LayoutSwitchService.switchLayout(false) + } }) .controller('ChangelogModalController', function ($scope, $modal) { - - $scope.currentVersion = Config.App.version; + $scope.currentVersion = Config.App.version if (!$scope.lastVersion) { - var versionParts = $scope.currentVersion.split('.'); - $scope.lastVersion = versionParts[0] + '.' + versionParts[1] + '.' + Math.max(0, versionParts[2] - 1); + var versionParts = $scope.currentVersion.split('.') + $scope.lastVersion = versionParts[0] + '.' + versionParts[1] + '.' + Math.max(0, versionParts[2] - 1) } - $scope.changelogHidden = false; - $scope.changelogShown = false; + $scope.changelogHidden = false + $scope.changelogShown = false $scope.canShowVersion = function (curVersion) { if ($scope.changelogShown) { - return true; + return true } - var show = versionCompare(curVersion, $scope.lastVersion) >= 0; + var show = versionCompare(curVersion, $scope.lastVersion) >= 0 if (!show) { - $scope.changelogHidden = true; + $scope.changelogHidden = true } - return show; - }; + return show + } $scope.showAllVersions = function () { - $scope.changelogShown = true; - $scope.changelogHidden = false; - $scope.$emit('ui_height'); - $scope.$broadcast('ui_height'); - }; + $scope.changelogShown = true + $scope.changelogHidden = false + $scope.$emit('ui_height') + $scope.$broadcast('ui_height') + } $scope.changeUsername = function () { $modal.open({ templateUrl: templateUrl('username_edit_modal'), controller: 'UsernameEditModalController', windowClass: 'md_simple_modal_window mobile_modal' - }); - }; + }) + } }) - .controller('ProfileEditModalController', function ($scope, $modalInstance, AppUsersManager, MtpApiManager) { - - $scope.profile = {}; - $scope.error = {}; + .controller('ProfileEditModalController', function ($scope, $modalInstance, AppUsersManager, MtpApiManager) { + $scope.profile = {} + $scope.error = {} MtpApiManager.getUserID().then(function (id) { - var user = AppUsersManager.getUser(id); + var user = AppUsersManager.getUser(id) $scope.profile = { first_name: user.first_name, last_name: user.last_name - }; - }); - + } + }) $scope.updateProfile = function () { - $scope.profile.updating = true; - var flags = (1 << 0) | (1 << 1); + $scope.profile.updating = true + var flags = (1 << 0) | (1 << 1) MtpApiManager.invokeApi('account.updateProfile', { flags: flags, first_name: $scope.profile.first_name || '', last_name: $scope.profile.last_name || '' }).then(function (user) { - $scope.error = {}; - AppUsersManager.saveApiUser(user); - $modalInstance.close(); + $scope.error = {} + AppUsersManager.saveApiUser(user) + $modalInstance.close() }, function (error) { switch (error.type) { case 'FIRSTNAME_INVALID': - $scope.error = {field: 'first_name'}; - error.handled = true; - break; + $scope.error = {field: 'first_name'} + error.handled = true + break case 'LASTNAME_INVALID': - $scope.error = {field: 'last_name'}; - error.handled = true; - break; + $scope.error = {field: 'last_name'} + error.handled = true + break case 'NAME_NOT_MODIFIED': - error.handled = true; - $modalInstance.close(); - break; + error.handled = true + $modalInstance.close() + break } })['finally'](function () { - delete $scope.profile.updating; - }); + delete $scope.profile.updating + }) } }) - .controller('UsernameEditModalController', function ($scope, $modalInstance, AppUsersManager, MtpApiManager) { - - $scope.profile = {}; - $scope.error = {}; + .controller('UsernameEditModalController', function ($scope, $modalInstance, AppUsersManager, MtpApiManager) { + $scope.profile = {} + $scope.error = {} MtpApiManager.getUserID().then(function (id) { - var user = AppUsersManager.getUser(id); + var user = AppUsersManager.getUser(id) $scope.profile = { username: user.username - }; - }); + } + }) $scope.updateUsername = function () { - $scope.profile.updating = true; + $scope.profile.updating = true MtpApiManager.invokeApi('account.updateUsername', { username: $scope.profile.username || '' }).then(function (user) { - $scope.checked = {}; - AppUsersManager.saveApiUser(user); - $modalInstance.close(); + $scope.checked = {} + AppUsersManager.saveApiUser(user) + $modalInstance.close() }, function (error) { if (error.type == 'USERNAME_NOT_MODIFIED') { - error.handled = true; - $modalInstance.close(); + error.handled = true + $modalInstance.close() } })['finally'](function () { - delete $scope.profile.updating; - }); + delete $scope.profile.updating + }) } $scope.$watch('profile.username', function (newVal) { if (!newVal || !newVal.length) { - $scope.checked = {}; - return; + $scope.checked = {} + return } MtpApiManager.invokeApi('account.checkUsername', { username: newVal || '' }).then(function (valid) { if ($scope.profile.username != newVal) { - return; + return } if (valid) { - $scope.checked = {success: true}; + $scope.checked = {success: true} } else { - $scope.checked = {error: true}; + $scope.checked = {error: true} } }, function (error) { if ($scope.profile.username != newVal) { - return; + return } switch (error.type) { case 'USERNAME_INVALID': - $scope.checked = {error: true}; - error.handled = true; - break; + $scope.checked = {error: true} + error.handled = true + break } - }); + }) }) }) .controller('SessionsListModalController', function ($scope, $q, $timeout, _, MtpApiManager, ErrorService, $modalInstance) { + $scope.slice = {limit: 20, limitDelta: 20} - $scope.slice = {limit: 20, limitDelta: 20}; - - var updateSessionsTimeout = false; - var stopped = false; + var updateSessionsTimeout = false + var stopped = false function updateSessions () { - $timeout.cancel(updateSessionsTimeout); + $timeout.cancel(updateSessionsTimeout) MtpApiManager.invokeApi('account.getAuthorizations').then(function (result) { - $scope.sessionsLoaded = true; - $scope.authorizations = result.authorizations; + $scope.sessionsLoaded = true + $scope.authorizations = result.authorizations - var authorization; + var authorization for (var i = 0, len = $scope.authorizations.length; i < len; i++) { - authorization = $scope.authorizations[i]; - authorization.current = (authorization.flags & 1) == 1; + authorization = $scope.authorizations[i] + authorization.current = (authorization.flags & 1) == 1 } $scope.authorizations.sort(function (sA, sB) { if (sA.current) { - return -1; + return -1 } if (sB.current) { - return 1; + return 1 } - return sB.date_active - sA.date_active; - }); + return sB.date_active - sA.date_active + }) if (!stopped) { - updateSessionsTimeout = $timeout(updateSessions, 5000); + updateSessionsTimeout = $timeout(updateSessions, 5000) } }) } $scope.terminateSession = function (hash) { ErrorService.confirm({type: 'TERMINATE_SESSION'}).then(function () { - MtpApiManager.invokeApi('account.resetAuthorization', {hash: hash}).then(updateSessions); + MtpApiManager.invokeApi('account.resetAuthorization', {hash: hash}).then(updateSessions) }) - }; + } $scope.terminateAllSessions = function () { ErrorService.confirm({type: 'TERMINATE_SESSIONS'}).then(function () { - MtpApiManager.invokeApi('auth.resetAuthorizations', {}); - }); - }; + MtpApiManager.invokeApi('auth.resetAuthorizations', {}) + }) + } - updateSessions(); + updateSessions() $scope.$on('apiUpdate', function (e, update) { if (update._ == 'updateNewAuthorization') { - updateSessions(); + updateSessions() } - }); + }) $scope.$on('$destroy', function () { - $timeout.cancel(updateSessionsTimeout); - stopped = true; - }); - + $timeout.cancel(updateSessionsTimeout) + stopped = true + }) }) .controller('PasswordUpdateModalController', function ($scope, $q, _, PasswordManager, MtpApiManager, ErrorService, $modalInstance) { - - $scope.passwordSettings = {}; + $scope.passwordSettings = {} $scope.updatePassword = function () { - delete $scope.passwordSettings.error_field; + delete $scope.passwordSettings.error_field - var confirmPromise; + var confirmPromise if ($scope.action == 'disable') { - confirmPromise = $q.when(); - } - else { + confirmPromise = $q.when() + }else { if (!$scope.passwordSettings.new_password) { - $scope.passwordSettings.error_field = 'new_password'; - $scope.$broadcast('new_password_focus'); - return false; + $scope.passwordSettings.error_field = 'new_password' + $scope.$broadcast('new_password_focus') + return false } if ($scope.passwordSettings.new_password != $scope.passwordSettings.confirm_password) { - $scope.passwordSettings.error_field = 'confirm_password'; - $scope.$broadcast('confirm_password_focus'); - return false; + $scope.passwordSettings.error_field = 'confirm_password' + $scope.$broadcast('confirm_password_focus') + return false } confirmPromise = $scope.passwordSettings.email ? $q.when() - : ErrorService.confirm({type: 'RECOVERY_EMAIL_EMPTY'}); + : ErrorService.confirm({type: 'RECOVERY_EMAIL_EMPTY'}) } - $scope.passwordSettings.loading = true; + $scope.passwordSettings.loading = true confirmPromise.then(function () { PasswordManager.updateSettings($scope.password, { @@ -4310,483 +4250,470 @@ angular.module('myApp.controllers', ['myApp.i18n']) email: $scope.passwordSettings.email, hint: $scope.passwordSettings.hint }).then(function (result) { - delete $scope.passwordSettings.loading; - $modalInstance.close(true); + delete $scope.passwordSettings.loading + $modalInstance.close(true) if ($scope.action == 'disable') { ErrorService.alert( _('error_modal_password_disabled_title_raw'), _('error_modal_password_disabled_descripion_raw') - ); + ) } else { ErrorService.alert( _('error_modal_password_success_title_raw'), _('error_modal_password_success_descripion_raw') - ); + ) } }, function (error) { switch (error.type) { case 'PASSWORD_HASH_INVALID': case 'NEW_PASSWORD_BAD': - $scope.passwordSettings.error_field = 'cur_password'; - error.handled = true; - $scope.$broadcast('cur_password_focus'); - break; + $scope.passwordSettings.error_field = 'cur_password' + error.handled = true + $scope.$broadcast('cur_password_focus') + break case 'NEW_PASSWORD_BAD': - $scope.passwordSettings.error_field = 'new_password'; - error.handled = true; - break; + $scope.passwordSettings.error_field = 'new_password' + error.handled = true + break case 'EMAIL_INVALID': - $scope.passwordSettings.error_field = 'email'; - error.handled = true; - break; + $scope.passwordSettings.error_field = 'email' + error.handled = true + break case 'EMAIL_UNCONFIRMED': ErrorService.alert( _('error_modal_email_unconfirmed_title_raw'), _('error_modal_email_unconfirmed_descripion_raw') - ); - $modalInstance.close(true); - error.handled = true; - break; + ) + $modalInstance.close(true) + error.handled = true + break } - delete $scope.passwordSettings.loading; - }); + delete $scope.passwordSettings.loading + }) }) } switch ($scope.action) { case 'disable': - $scope.passwordSettings.new_password = ''; - break; + $scope.passwordSettings.new_password = '' + break case 'create': onContentLoaded(function () { - $scope.$broadcast('new_password_focus'); - }); - break; + $scope.$broadcast('new_password_focus') + }) + break } $scope.$watch('passwordSettings.new_password', function (newValue) { - var len = newValue && newValue.length || 0; + var len = newValue && newValue.length || 0 if (!len) { - $scope.passwordSettings.hint = ''; + $scope.passwordSettings.hint = '' } else if (len <= 3) { - $scope.passwordSettings.hint = '***'; + $scope.passwordSettings.hint = '***' + }else { + $scope.passwordSettings.hint = newValue.charAt(0) + (new Array(len - 1)).join('*') + newValue.charAt(len - 1) } - else { - $scope.passwordSettings.hint = newValue.charAt(0) + (new Array(len - 1)).join('*') + newValue.charAt(len - 1); - } - $scope.$broadcast('value_updated'); + $scope.$broadcast('value_updated') }) }) .controller('PasswordRecoveryModalController', function ($scope, $q, _, PasswordManager, MtpApiManager, ErrorService, $modalInstance) { - $scope.checkCode = function () { - $scope.recovery.updating = true; + $scope.recovery.updating = true PasswordManager.recover($scope.recovery.code, $scope.options).then(function (result) { ErrorService.alert( _('error_modal_password_disabled_title_raw'), _('error_modal_password_disabled_descripion_raw') - ); - $modalInstance.close(result); + ) + $modalInstance.close(result) }, function (error) { - delete $scope.recovery.updating; + delete $scope.recovery.updating switch (error.type) { case 'CODE_EMPTY': case 'CODE_INVALID': - $scope.recovery.error_field = 'code'; - error.handled = true; - break; + $scope.recovery.error_field = 'code' + error.handled = true + break case 'PASSWORD_EMPTY': case 'PASSWORD_RECOVERY_NA': case 'PASSWORD_RECOVERY_EXPIRED': - $modalInstance.dismiss(); - error.handled = true; - break; + $modalInstance.dismiss() + error.handled = true + break } - }); - }; - + }) + } }) .controller('ContactsModalController', function ($scope, $timeout, $modal, $modalInstance, MtpApiManager, AppUsersManager, ErrorService) { + $scope.contacts = [] + $scope.foundPeers = [] + $scope.search = {} + $scope.slice = {limit: 20, limitDelta: 20} - $scope.contacts = []; - $scope.foundPeers = []; - $scope.search = {}; - $scope.slice = {limit: 20, limitDelta: 20}; - - var jump = 0; + var jump = 0 - resetSelected(); - $scope.disabledContacts = {}; + resetSelected() + $scope.disabledContacts = {} if ($scope.disabled) { for (var i = 0; i < $scope.disabled.length; i++) { - $scope.disabledContacts[$scope.disabled[i]] = true; + $scope.disabledContacts[$scope.disabled[i]] = true } } if ($scope.selected) { for (var i = 0; i < $scope.selected.length; i++) { if (!$scope.selectedContacts[$scope.selected[i]]) { - $scope.selectedContacts[$scope.selected[i]] = true; - $scope.selectedCount++; + $scope.selectedContacts[$scope.selected[i]] = true + $scope.selectedCount++ } } } function resetSelected () { - $scope.selectedContacts = {}; - $scope.selectedCount = 0; - }; + $scope.selectedContacts = {} + $scope.selectedCount = 0 + } function updateContacts (query) { - var curJump = ++jump; - var doneIDs = []; + var curJump = ++jump + var doneIDs = [] AppUsersManager.getContacts(query).then(function (contactsList) { - if (curJump != jump) return; - $scope.contacts = []; - $scope.slice.limit = 20; + if (curJump != jump) return + $scope.contacts = [] + $scope.slice.limit = 20 - angular.forEach(contactsList, function(userID) { + angular.forEach(contactsList, function (userID) { var contact = { userID: userID, user: AppUsersManager.getUser(userID) } - doneIDs.push(userID); - $scope.contacts.push(contact); - }); - $scope.contactsEmpty = query ? false : !$scope.contacts.length; - $scope.$broadcast('contacts_change'); - }); + doneIDs.push(userID) + $scope.contacts.push(contact) + }) + $scope.contactsEmpty = query ? false : !$scope.contacts.length + $scope.$broadcast('contacts_change') + }) if (query && query.length >= 5) { - $timeout(function() { - if (curJump != jump) return; + $timeout(function () { + if (curJump != jump) return MtpApiManager.invokeApi('contacts.search', {q: query, limit: 10}).then(function (result) { - AppUsersManager.saveApiUsers(result.users); - if (curJump != jump) return; - angular.forEach(result.results, function(contactFound) { - var userID = contactFound.user_id; - if (doneIDs.indexOf(userID) != -1) return; + AppUsersManager.saveApiUsers(result.users) + if (curJump != jump) return + angular.forEach(result.results, function (contactFound) { + var userID = contactFound.user_id + if (doneIDs.indexOf(userID) != -1) return $scope.contacts.push({ userID: userID, user: AppUsersManager.getUser(userID), peerString: AppUsersManager.getUserString(userID), found: true - }); - }); + }) + }) }, function (error) { if (error.code == 400) { - error.handled = true; + error.handled = true } - }); - }, 500); + }) + }, 500) } - }; + } - $scope.$watch('search.query', updateContacts); + $scope.$watch('search.query', updateContacts) $scope.$on('contacts_update', function () { - updateContacts($scope.search && $scope.search.query || ''); - }); + updateContacts($scope.search && $scope.search.query || '') + }) $scope.toggleEdit = function (enabled) { - $scope.action = enabled ? 'edit' : ''; - $scope.multiSelect = enabled; - resetSelected(); - }; + $scope.action = enabled ? 'edit' : '' + $scope.multiSelect = enabled + resetSelected() + } $scope.contactSelect = function (userID) { if ($scope.disabledContacts[userID]) { - return false; + return false } if (!$scope.multiSelect) { - return $modalInstance.close(userID); + return $modalInstance.close(userID) } if ($scope.selectedContacts[userID]) { - delete $scope.selectedContacts[userID]; - $scope.selectedCount--; + delete $scope.selectedContacts[userID] + $scope.selectedCount-- } else { - $scope.selectedContacts[userID] = true; - $scope.selectedCount++; + $scope.selectedContacts[userID] = true + $scope.selectedCount++ } - }; + } $scope.submitSelected = function () { if ($scope.selectedCount > 0) { - var selectedUserIDs = []; + var selectedUserIDs = [] angular.forEach($scope.selectedContacts, function (t, userID) { - selectedUserIDs.push(userID); - }); - return $modalInstance.close(selectedUserIDs); + selectedUserIDs.push(userID) + }) + return $modalInstance.close(selectedUserIDs) } - }; + } $scope.deleteSelected = function () { if ($scope.selectedCount > 0) { - var selectedUserIDs = []; + var selectedUserIDs = [] angular.forEach($scope.selectedContacts, function (t, userID) { - selectedUserIDs.push(userID); - }); + selectedUserIDs.push(userID) + }) AppUsersManager.deleteContacts(selectedUserIDs).then(function () { - $scope.toggleEdit(false); - }); + $scope.toggleEdit(false) + }) } - }; + } $scope.importContact = function () { - AppUsersManager.openImportContact(); - }; - + AppUsersManager.openImportContact() + } }) .controller('PeerSelectController', function ($scope, $modalInstance, $q, AppPeersManager, ErrorService) { - - $scope.selectedPeers = {}; - $scope.selectedPeerIDs = []; - $scope.selectedCount = 0; + $scope.selectedPeers = {} + $scope.selectedPeerIDs = [] + $scope.selectedCount = 0 if ($scope.shareLinkPromise) { - $scope.shareLink = {loading: true}; + $scope.shareLink = {loading: true} $scope.shareLinkPromise.then(function (url) { - $scope.shareLink = {url: url}; + $scope.shareLink = {url: url} }, function () { - delete $scope.shareLink; - }); + delete $scope.shareLink + }) } $scope.dialogSelect = function (peerString) { if (!$scope.multiSelect) { - var promise; + var promise if ($scope.confirm_type) { - var peerID = AppPeersManager.getPeerID(peerString), - peerData = AppPeersManager.getPeer(peerID); + var peerID = AppPeersManager.getPeerID(peerString) + var peerData = AppPeersManager.getPeer(peerID) promise = ErrorService.confirm({ type: $scope.confirm_type, peer_id: peerID, peer_data: peerData - }); + }) } else { - promise = $q.when(); + promise = $q.when() } promise.then(function () { - $modalInstance.close(peerString); - }); - return; + $modalInstance.close(peerString) + }) + return } - var peerID = AppPeersManager.getPeerID(peerString); + var peerID = AppPeersManager.getPeerID(peerString) if ($scope.selectedPeers[peerID]) { - delete $scope.selectedPeers[peerID]; - $scope.selectedCount--; - var pos = $scope.selectedPeerIDs.indexOf(peerID); + delete $scope.selectedPeers[peerID] + $scope.selectedCount-- + var pos = $scope.selectedPeerIDs.indexOf(peerID) if (pos >= 0) { - $scope.selectedPeerIDs.splice(pos, 1); + $scope.selectedPeerIDs.splice(pos, 1) } } else { - $scope.selectedPeers[peerID] = AppPeersManager.getPeer(peerID); - $scope.selectedCount++; - $scope.selectedPeerIDs.unshift(peerID); + $scope.selectedPeers[peerID] = AppPeersManager.getPeer(peerID) + $scope.selectedCount++ + $scope.selectedPeerIDs.unshift(peerID) } - }; + } $scope.submitSelected = function () { if ($scope.selectedCount > 0) { - var selectedPeerStrings = []; + var selectedPeerStrings = [] angular.forEach($scope.selectedPeers, function (t, peerID) { - selectedPeerStrings.push(AppPeersManager.getPeerString(peerID)); - }); - return $modalInstance.close(selectedPeerStrings); + selectedPeerStrings.push(AppPeersManager.getPeerString(peerID)) + }) + return $modalInstance.close(selectedPeerStrings) } - }; + } $scope.toggleSearch = function () { - $scope.$broadcast('dialogs_search_toggle'); - }; + $scope.$broadcast('dialogs_search_toggle') + } }) .controller('ChatCreateModalController', function ($scope, $modalInstance, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, ApiUpdatesManager) { - $scope.group = {name: ''}; + $scope.group = {name: ''} $scope.createGroup = function () { if (!$scope.group.name) { - return; + return } - $scope.group.creating = true; - var inputUsers = []; - angular.forEach($scope.userIDs, function(userID) { - inputUsers.push(AppUsersManager.getUserInput(userID)); - }); + $scope.group.creating = true + var inputUsers = [] + angular.forEach($scope.userIDs, function (userID) { + inputUsers.push(AppUsersManager.getUserInput(userID)) + }) return MtpApiManager.invokeApi('messages.createChat', { title: $scope.group.name, users: inputUsers }).then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); + ApiUpdatesManager.processUpdateMessage(updates) if (updates.updates && updates.updates.length) { for (var i = 0, len = updates.updates.length, update; i < len; i++) { - update = updates.updates[i]; + update = updates.updates[i] if (update._ == 'updateNewMessage') { $rootScope.$broadcast('history_focus', {peerString: AppChatsManager.getChatString(update.message.to_id.chat_id) - }); - break; + }) + break } } - $modalInstance.close(); + $modalInstance.close() } - })['finally'](function () { - delete $scope.group.creating; - }); - }; - + delete $scope.group.creating + }) + } }) .controller('ChatEditModalController', function ($scope, $modalInstance, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, ApiUpdatesManager) { - - var chat = AppChatsManager.getChat($scope.chatID); - $scope.group = {name: chat.title}; + var chat = AppChatsManager.getChat($scope.chatID) + $scope.group = {name: chat.title} $scope.updateGroup = function () { if (!$scope.group.name) { - return; + return } if ($scope.group.name == chat.title) { - return $modalInstance.close(); + return $modalInstance.close() } - $scope.group.updating = true; + $scope.group.updating = true - var apiPromise; + var apiPromise if (AppChatsManager.isChannel($scope.chatID)) { apiPromise = MtpApiManager.invokeApi('channels.editTitle', { channel: AppChatsManager.getChannelInput($scope.chatID), title: $scope.group.name - }); + }) } else { apiPromise = MtpApiManager.invokeApi('messages.editChatTitle', { chat_id: AppChatsManager.getChatInput($scope.chatID), title: $scope.group.name - }); + }) } return apiPromise.then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - var peerString = AppChatsManager.getChatString($scope.chatID); - $rootScope.$broadcast('history_focus', {peerString: peerString}); + ApiUpdatesManager.processUpdateMessage(updates) + var peerString = AppChatsManager.getChatString($scope.chatID) + $rootScope.$broadcast('history_focus', {peerString: peerString}) })['finally'](function () { - delete $scope.group.updating; - }); - }; + delete $scope.group.updating + }) + } }) .controller('ChannelEditModalController', function ($q, $scope, $modalInstance, $rootScope, MtpApiManager, AppUsersManager, AppChatsManager, AppProfileManager, ApiUpdatesManager) { - - var channel = AppChatsManager.getChat($scope.chatID); - var initial = {title: channel.title}; - $scope.channel = {title: channel.title}; + var channel = AppChatsManager.getChat($scope.chatID) + var initial = {title: channel.title} + $scope.channel = {title: channel.title} AppProfileManager.getChannelFull($scope.chatID).then(function (channelFull) { - initial.about = channelFull.about; - $scope.channel.about = channelFull.about; - }); + initial.about = channelFull.about + $scope.channel.about = channelFull.about + }) $scope.updateChannel = function () { if (!$scope.channel.title.length) { - return; + return } - var promises = []; + var promises = [] if ($scope.channel.title != initial.title) { - promises.push(editTitle()); + promises.push(editTitle()) } if ($scope.channel.about != initial.about) { - promises.push(editAbout()); + promises.push(editAbout()) } - $scope.channel.updating = true; + $scope.channel.updating = true return $q.all(promises).then(function () { - var peerString = AppChatsManager.getChatString($scope.chatID); - $rootScope.$broadcast('history_focus', {peerString: peerString}); + var peerString = AppChatsManager.getChatString($scope.chatID) + $rootScope.$broadcast('history_focus', {peerString: peerString}) })['finally'](function () { - delete $scope.channel.updating; - }); - }; + delete $scope.channel.updating + }) + } function editTitle () { return MtpApiManager.invokeApi('channels.editTitle', { channel: AppChatsManager.getChannelInput($scope.chatID), title: $scope.channel.title }).then(function (updates) { - ApiUpdatesManager.processUpdateMessage(updates); - }); + ApiUpdatesManager.processUpdateMessage(updates) + }) } function editAbout () { return MtpApiManager.invokeApi('channels.editAbout', { channel: AppChatsManager.getChannelInput($scope.chatID), about: $scope.channel.about - }); + }) } }) .controller('ChatInviteLinkModalController', function (_, $scope, $timeout, $modalInstance, AppChatsManager, AppProfileManager, ErrorService) { + $scope.exportedInvite = {link: _('group_invite_link_loading_raw')} - $scope.exportedInvite = {link: _('group_invite_link_loading_raw')}; - - var isChannel = AppChatsManager.isChannel($scope.chatID); - var isMegagroup = AppChatsManager.isMegagroup($scope.chatID); + var isChannel = AppChatsManager.isChannel($scope.chatID) + var isMegagroup = AppChatsManager.isMegagroup($scope.chatID) function selectLink () { $timeout(function () { - $scope.$broadcast('ui_invite_select'); - }, 100); + $scope.$broadcast('ui_invite_select') + }, 100) } function updateLink (force) { - var chat = AppChatsManager.getChat($scope.chatID); + var chat = AppChatsManager.getChat($scope.chatID) if (chat.username) { - $scope.exportedInvite = {link: 'https://telegram.me/' + chat.username, short: true}; - selectLink(); - return; + $scope.exportedInvite = {link: 'https://telegram.me/' + chat.username, short: true} + selectLink() + return } if (force) { - $scope.exportedInvite.revoking = true; + $scope.exportedInvite.revoking = true } AppProfileManager.getChatInviteLink($scope.chatID, force).then(function (link) { - $scope.exportedInvite = {link: link, canRevoke: true}; - selectLink(); - + $scope.exportedInvite = {link: link, canRevoke: true} + selectLink() })['finally'](function () { - delete $scope.exportedInvite.revoking; - }); + delete $scope.exportedInvite.revoking + }) } $scope.revokeLink = function () { ErrorService.confirm({ type: isChannel && !isMegagroup ? 'REVOKE_CHANNEL_INVITE_LINK' : 'REVOKE_GROUP_INVITE_LINK' }).then(function () { - updateLink(true); + updateLink(true) }) } - updateLink(); - + updateLink() }) .controller('ImportContactModalController', function ($scope, $modalInstance, $rootScope, AppUsersManager, ErrorService, PhonebookContactsService) { if ($scope.importContact === undefined) { - $scope.importContact = {}; + $scope.importContact = {} } - $scope.phonebookAvailable = PhonebookContactsService.isAvailable(); + $scope.phonebookAvailable = PhonebookContactsService.isAvailable() $scope.doImport = function () { if ($scope.importContact && $scope.importContact.phone) { - $scope.progress = {enabled: true}; + $scope.progress = {enabled: true} AppUsersManager.importContact( $scope.importContact.phone, $scope.importContact.first_name || '', @@ -4795,217 +4722,211 @@ angular.module('myApp.controllers', ['myApp.i18n']) if (!foundUserID) { ErrorService.show({ error: {code: 404, type: 'USER_NOT_USING_TELEGRAM'} - }); + }) } - $modalInstance.close(foundUserID); + $modalInstance.close(foundUserID) })['finally'](function () { - delete $scope.progress.enabled; - }); + delete $scope.progress.enabled + }) } - }; + } $scope.importPhonebook = function () { PhonebookContactsService.openPhonebookImport().result.then(function (foundContacts) { if (foundContacts) { - $modalInstance.close(foundContacts[0]); + $modalInstance.close(foundContacts[0]) } else { - $modalInstance.dismiss(); + $modalInstance.dismiss() } }) - }; - + } }) .controller('CountrySelectModalController', function ($scope, $modalInstance, $rootScope, _) { - - $scope.search = {}; + $scope.search = {} $scope.slice = {limit: 20, limitDelta: 20} - var searchIndex = SearchIndexManager.createIndex(); + var searchIndex = SearchIndexManager.createIndex() for (var i = 0; i < Config.CountryCodes.length; i++) { - var searchString = Config.CountryCodes[i][0]; - searchString += ' ' + _(Config.CountryCodes[i][1] + '_raw'); - searchString += ' ' + Config.CountryCodes[i].slice(2).join(' '); - SearchIndexManager.indexObject(i, searchString, searchIndex); + var searchString = Config.CountryCodes[i][0] + searchString += ' ' + _(Config.CountryCodes[i][1] + '_raw') + searchString += ' ' + Config.CountryCodes[i].slice(2).join(' ') + SearchIndexManager.indexObject(i, searchString, searchIndex) } $scope.$watch('search.query', function (newValue) { - var filtered = false, - results = {}; + var filtered = false + var results = {} if (angular.isString(newValue) && newValue.length) { - filtered = true; - results = SearchIndexManager.search(newValue, searchIndex); + filtered = true + results = SearchIndexManager.search(newValue, searchIndex) } - $scope.countries = []; - $scope.slice.limit = 20; + $scope.countries = [] + $scope.slice.limit = 20 - var j; + var j for (var i = 0; i < Config.CountryCodes.length; i++) { if (!filtered || results[i]) { for (j = 2; j < Config.CountryCodes[i].length; j++) { - $scope.countries.push({name: _(Config.CountryCodes[i][1] + '_raw'), code: Config.CountryCodes[i][j]}); + $scope.countries.push({name: _(Config.CountryCodes[i][1] + '_raw'), code: Config.CountryCodes[i][j]}) } } } if (String.prototype.localeCompare) { - $scope.countries.sort(function(a, b) { - return a.name.localeCompare(b.name); - }); + $scope.countries.sort(function (a, b) { + return a.name.localeCompare(b.name) + }) } - }); + }) }) - .controller('PhonebookModalController', function ($scope, $modalInstance, $rootScope, AppUsersManager, PhonebookContactsService, ErrorService) { + $scope.search = {} + $scope.phonebook = [] + $scope.selectedContacts = {} + $scope.selectedCount = 0 + $scope.slice = {limit: 20, limitDelta: 20} + $scope.progress = {enabled: false} + $scope.multiSelect = true - $scope.search = {}; - $scope.phonebook = []; - $scope.selectedContacts = {}; - $scope.selectedCount = 0; - $scope.slice = {limit: 20, limitDelta: 20}; - $scope.progress = {enabled: false}; - $scope.multiSelect = true; - - var searchIndex = SearchIndexManager.createIndex(), - phonebookReady = false; + var searchIndex = SearchIndexManager.createIndex() + var phonebookReady = false PhonebookContactsService.getPhonebookContacts().then(function (phonebook) { for (var i = 0; i < phonebook.length; i++) { - SearchIndexManager.indexObject(i, phonebook[i].first_name + ' ' + phonebook[i].last_name + ' ' + phonebook[i].phones.join(' '), searchIndex); + SearchIndexManager.indexObject(i, phonebook[i].first_name + ' ' + phonebook[i].last_name + ' ' + phonebook[i].phones.join(' '), searchIndex) } - $scope.phonebook = phonebook; - $scope.toggleSelection(true); - phonebookReady = true; - updateList(); + $scope.phonebook = phonebook + $scope.toggleSelection(true) + phonebookReady = true + updateList() }, function (error) { ErrorService.show({ error: {code: 403, type: 'PHONEBOOK_GET_CONTACTS_FAILED', originalError: error} - }); - }); + }) + }) function updateList () { - var filtered = false, - results = {}; + var filtered = false + var results = {} if (angular.isString($scope.search.query) && $scope.search.query.length) { - filtered = true; - results = SearchIndexManager.search($scope.search.query, searchIndex); + filtered = true + results = SearchIndexManager.search($scope.search.query, searchIndex) - $scope.contacts = []; - delete $scope.contactsEmpty; + $scope.contacts = [] + delete $scope.contactsEmpty for (var i = 0; i < $scope.phonebook.length; i++) { if (!filtered || results[i]) { - $scope.contacts.push($scope.phonebook[i]); + $scope.contacts.push($scope.phonebook[i]) } } } else { - $scope.contacts = $scope.phonebook; - $scope.contactsEmpty = !$scope.contacts.length; + $scope.contacts = $scope.phonebook + $scope.contactsEmpty = !$scope.contacts.length } - $scope.slice.limit = 20; + $scope.slice.limit = 20 } $scope.$watch('search.query', function (newValue) { if (phonebookReady) { - updateList(); + updateList() } - }); + }) $scope.contactSelect = function (i) { if (!$scope.multiSelect) { - return $modalInstance.close($scope.phonebook[i]); + return $modalInstance.close($scope.phonebook[i]) } if ($scope.selectedContacts[i]) { - delete $scope.selectedContacts[i]; - $scope.selectedCount--; + delete $scope.selectedContacts[i] + $scope.selectedCount-- } else { - $scope.selectedContacts[i] = true; - $scope.selectedCount++; + $scope.selectedContacts[i] = true + $scope.selectedCount++ } - }; + } $scope.toggleSelection = function (fill) { if (!$scope.selectedCount || fill) { - $scope.selectedCount = $scope.phonebook.length; + $scope.selectedCount = $scope.phonebook.length for (var i = 0; i < $scope.phonebook.length; i++) { - $scope.selectedContacts[i] = true; + $scope.selectedContacts[i] = true } } else { - $scope.selectedCount = 0; - $scope.selectedContacts = {}; + $scope.selectedCount = 0 + $scope.selectedContacts = {} } - }; + } $scope.submitSelected = function () { if ($scope.selectedCount <= 0) { - $modalInstance.dismiss(); + $modalInstance.dismiss() } - var selectedContacts = []; + var selectedContacts = [] angular.forEach($scope.selectedContacts, function (t, i) { - selectedContacts.push($scope.phonebook[i]); - }); + selectedContacts.push($scope.phonebook[i]) + }) ErrorService.confirm({ type: 'CONTACTS_IMPORT_PERFORM' }).then(function () { - $scope.progress.enabled = true; + $scope.progress.enabled = true AppUsersManager.importContacts(selectedContacts).then(function (foundContacts) { if (!foundContacts.length) { ErrorService.show({ error: {code: 404, type: 'USERS_NOT_USING_TELEGRAM'} - }); + }) } - $modalInstance.close(foundContacts); + $modalInstance.close(foundContacts) })['finally'](function () { - $scope.progress.enabled = false; - }); - }); - }; - + $scope.progress.enabled = false + }) + }) + } }) .controller('StickersetModalController', function ($scope, $rootScope, $modalInstance, MtpApiManager, RichTextProcessor, AppStickersManager, AppDocsManager, AppMessagesManager, LocationParamsService) { - $scope.slice = {limit: 20, limitDelta: 20}; + $scope.slice = {limit: 20, limitDelta: 20} - var fullSet; + var fullSet AppStickersManager.getStickerset($scope.inputStickerset).then(function (result) { - $scope.$broadcast('ui_height'); - $scope.stickersetLoaded = true; - fullSet = result; - $scope.stickerset = result.set; - $scope.stickersetInstalled = result.set.pFlags.installed == true; - $scope.documents = result.documents; - - $scope.stickerEmojis = {}; - $scope.stickerDimensions = {}; + $scope.$broadcast('ui_height') + $scope.stickersetLoaded = true + fullSet = result + $scope.stickerset = result.set + $scope.stickersetInstalled = result.set.pFlags.installed == true + $scope.documents = result.documents + + $scope.stickerEmojis = {} + $scope.stickerDimensions = {} angular.forEach($scope.documents, function (doc) { $scope.stickerEmojis[doc.id] = RichTextProcessor.wrapRichText(doc.stickerEmojiRaw, { noLinks: true, noLinebreaks: true, emojiIconSize: 26 - }); - var dim = calcImageInBox(doc.w, doc.h, 192, 192); - $scope.stickerDimensions[doc.id] = {width: dim.w, height: dim.h}; - }); - - }); + }) + var dim = calcImageInBox(doc.w, doc.h, 192, 192) + $scope.stickerDimensions[doc.id] = {width: dim.w, height: dim.h} + }) + }) $scope.toggleInstalled = function (installed) { AppStickersManager.installStickerset(fullSet, !installed).then(function () { - $scope.stickersetInstalled = installed; + $scope.stickersetInstalled = installed }) - }; + } $scope.chooseSticker = function (docID) { - var doc = AppDocsManager.getDoc(docID); + var doc = AppDocsManager.getDoc(docID) if (!doc.id || !doc.access_hash || !$rootScope.selectedPeerID) { - return; + return } var inputMedia = { _: 'inputMediaDocument', @@ -5015,11 +4936,11 @@ angular.module('myApp.controllers', ['myApp.i18n']) access_hash: doc.access_hash } } - AppMessagesManager.sendOther($rootScope.selectedPeerID, inputMedia); - $modalInstance.close(doc.id); - }; + AppMessagesManager.sendOther($rootScope.selectedPeerID, inputMedia) + $modalInstance.close(doc.id) + } $scope.share = function () { - LocationParamsService.shareUrl('https://telegram.me/addstickers/' + $scope.stickerset.short_name, $scope.stickerset.title); - }; + LocationParamsService.shareUrl('https://telegram.me/addstickers/' + $scope.stickerset.short_name, $scope.stickerset.title) + } }) diff --git a/app/js/directives.js b/app/js/directives.js index b3a37f6c..c167a681 100755 --- a/app/js/directives.js +++ b/app/js/directives.js @@ -5,379 +5,373 @@ * https://github.com/zhukov/webogram/blob/master/LICENSE */ -'use strict'; +'use strict' /* Directives */ - angular.module('myApp.directives', ['myApp.filters']) .constant('shouldFocusOnInteraction', !Config.Navigator.mobile) - .directive('myHead', function() { + .directive('myHead', function () { return { restrict: 'AE', templateUrl: templateUrl('head') - }; + } }) - .directive('myLangFooter', function() { + .directive('myLangFooter', function () { return { restrict: 'AE', templateUrl: templateUrl('lang_footer') - }; + } }) - .directive('myFooter', function() { + .directive('myFooter', function () { return { restrict: 'AE', templateUrl: templateUrl('footer') - }; + } }) - .directive('myDialog', function() { + .directive('myDialog', function () { return { restrict: 'AE', templateUrl: templateUrl('dialog') - }; + } }) - .directive('myMessage', function($filter, _) { - - var dateFilter = $filter('myDate'), - dateSplitHtml = '

--- 
 ---
', - unreadSplitHtml = '
' + _('unread_messages_split') + '
', - selectedClass = 'im_message_selected', - focusClass = 'im_message_focus', - unreadClass = 'im_message_unread', - errorClass = 'im_message_error', - pendingClass = 'im_message_pending'; + .directive('myMessage', function ($filter, _) { + var dateFilter = $filter('myDate') + var dateSplitHtml = '

--- 
 ---
', + unreadSplitHtml = '
' + _('unread_messages_split') + '
', + selectedClass = 'im_message_selected', + focusClass = 'im_message_focus', + unreadClass = 'im_message_unread', + errorClass = 'im_message_error', + pendingClass = 'im_message_pending' return { templateUrl: templateUrl('message'), link: link - }; - - function link($scope, element, attrs) { - var selected = false, - grouped = false, - focused = false, - error = false, - pending = false, - needDate = false, - unreadAfter = false, - applySelected = function () { - if (selected != ($scope.selectedMsgs[$scope.historyMessage.mid] || false)) { - selected = !selected; - element.toggleClass(selectedClass, selected); + } + + function link ($scope, element, attrs) { + var selected = false + var grouped = false + var focused = false + var error = false + var pending = false + var needDate = false + var unreadAfter = false + var applySelected = function () { + if (selected != ($scope.selectedMsgs[$scope.historyMessage.mid] || false)) { + selected = !selected + element.toggleClass(selectedClass, selected) + } + }, + needDateSplit, + applyGrouped = function () { + if (grouped != $scope.historyMessage.grouped) { + if (grouped) { + element.removeClass(grouped) } - }, - needDateSplit, - applyGrouped = function () { - if (grouped != $scope.historyMessage.grouped) { - if (grouped) { - element.removeClass(grouped); - } - grouped = $scope.historyMessage.grouped; - if (grouped) { - element.addClass(grouped); - } + grouped = $scope.historyMessage.grouped + if (grouped) { + element.addClass(grouped) } - if (needDate != ($scope.historyMessage.needDate || false)) { - needDate = !needDate; - if (needDate) { - if (needDateSplit) { - needDateSplit.show(); + } + if (needDate != ($scope.historyMessage.needDate || false)) { + needDate = !needDate + if (needDate) { + if (needDateSplit) { + needDateSplit.show() + } else { + needDateSplit = $(dateSplitHtml) + $('.im_message_date_split_text', needDateSplit).text(dateFilter($scope.historyMessage.date)) + if (unreadAfterSplit) { + needDateSplit.insertBefore(unreadAfterSplit) } else { - needDateSplit = $(dateSplitHtml); - $('.im_message_date_split_text', needDateSplit).text(dateFilter($scope.historyMessage.date)); - if (unreadAfterSplit) { - needDateSplit.insertBefore(unreadAfterSplit) - } else { - needDateSplit.prependTo(element); - } + needDateSplit.prependTo(element) } - } else { - needDateSplit.hide(); } + } else { + needDateSplit.hide() } - }, - unreadAfterSplit; + } + }, + unreadAfterSplit - applySelected(); - applyGrouped(); + applySelected() + applyGrouped() - $scope.$on('messages_select', applySelected); - $scope.$on('messages_regroup', applyGrouped); + $scope.$on('messages_select', applySelected) + $scope.$on('messages_regroup', applyGrouped) $scope.$on('messages_focus', function (e, focusedMsgID) { if ((focusedMsgID == $scope.historyMessage.mid) != focused) { - focused = !focused; - element.toggleClass(focusClass, focused); + focused = !focused + element.toggleClass(focusClass, focused) } - }); + }) - var deregisterUnreadAfter; + var deregisterUnreadAfter if (!$scope.historyMessage.pFlags.out && - ($scope.historyMessage.pFlags.unread || $scope.historyMessage.unreadAfter)) { + ($scope.historyMessage.pFlags.unread || $scope.historyMessage.unreadAfter)) { var applyUnreadAfter = function () { if ($scope.peerHistory.peerID != $scope.historyPeer.id) { - return; + return } if (unreadAfter != ($scope.historyUnreadAfter == $scope.historyMessage.mid)) { - unreadAfter = !unreadAfter; + unreadAfter = !unreadAfter if (unreadAfter) { if (unreadAfterSplit) { - unreadAfterSplit.show(); + unreadAfterSplit.show() } else { - unreadAfterSplit = $(unreadSplitHtml).prependTo(element); + unreadAfterSplit = $(unreadSplitHtml).prependTo(element) } } else { - unreadAfterSplit.hide(); + unreadAfterSplit.hide() if (deregisterUnreadAfter) { - deregisterUnreadAfter(); + deregisterUnreadAfter() } } } - }; - applyUnreadAfter(); - deregisterUnreadAfter = $scope.$on('messages_unread_after', applyUnreadAfter); + } + applyUnreadAfter() + deregisterUnreadAfter = $scope.$on('messages_unread_after', applyUnreadAfter) } if ($scope.historyMessage.pFlags.unread && $scope.historyMessage.pFlags.out) { - element.addClass(unreadClass); + element.addClass(unreadClass) var deregisterUnread = $scope.$on('messages_read', function () { if (!$scope.historyMessage.pFlags.unread) { - element.removeClass(unreadClass); - deregisterUnread(); + element.removeClass(unreadClass) + deregisterUnread() if (deregisterUnreadAfter && !unreadAfter) { - deregisterUnreadAfter(); + deregisterUnreadAfter() } } - }); + }) } if ($scope.historyMessage.error || $scope.historyMessage.pending) { var applyPending = function () { - if (pending != ($scope.historyMessage.pending || false)) { - pending = !pending; - element.toggleClass(pendingClass, pending); - } - if (error != ($scope.historyMessage.error || false)) { - error = !error; - element.toggleClass(errorClass, error); - } - if (!error && !pending) { - deregisterPending(); - } - }, - deregisterPending = $scope.$on('messages_pending', applyPending); + if (pending != ($scope.historyMessage.pending || false)) { + pending = !pending + element.toggleClass(pendingClass, pending) + } + if (error != ($scope.historyMessage.error || false)) { + error = !error + element.toggleClass(errorClass, error) + } + if (!error && !pending) { + deregisterPending() + } + }, + deregisterPending = $scope.$on('messages_pending', applyPending) - applyPending(); + applyPending() } } }) - .directive('myMessageBody', function($compile, AppPeersManager, AppChatsManager, AppUsersManager, AppMessagesManager, AppInlineBotsManager, RichTextProcessor) { - - var messageMediaCompiled = $compile('
'); - var messageKeyboardCompiled = $compile('
'); - var messageSignCompiled = $compile('
'); + .directive('myMessageBody', function ($compile, AppPeersManager, AppChatsManager, AppUsersManager, AppMessagesManager, AppInlineBotsManager, RichTextProcessor) { + var messageMediaCompiled = $compile('
') + var messageKeyboardCompiled = $compile('
') + var messageSignCompiled = $compile('
') return { link: link, scope: { message: '=myMessageBody' } - }; + } function updateMessageText ($scope, element, message) { if (typeof message.message !== 'string' || - !message.message.length) { - $('.im_message_text', element).hide(); - return; + !message.message.length) { + $('.im_message_text', element).hide() + return } - var fromUser = message.from_id && AppUsersManager.getUser(message.from_id); - var fromBot = fromUser && fromUser.pFlags.bot && fromUser.username || false; - var toPeerID = AppPeersManager.getPeerID(message.to_id); + var fromUser = message.from_id && AppUsersManager.getUser(message.from_id) + var fromBot = fromUser && fromUser.pFlags.bot && fromUser.username || false + var toPeerID = AppPeersManager.getPeerID(message.to_id) var withBot = (fromBot || - toPeerID < 0 && !(AppChatsManager.isChannel(-toPeerID) && !AppChatsManager.isMegagroup(-toPeerID)) || - toPeerID > 0 && AppUsersManager.isBot(toPeerID)); + toPeerID < 0 && !(AppChatsManager.isChannel(-toPeerID) && !AppChatsManager.isMegagroup(-toPeerID)) || + toPeerID > 0 && AppUsersManager.isBot(toPeerID)) var options = { noCommands: !withBot, fromBot: fromBot, entities: message.totalEntities - }; + } if (message.pFlags.mentioned) { - var user = AppUsersManager.getSelf(); + var user = AppUsersManager.getSelf() if (user) { - options.highlightUsername = user.username; + options.highlightUsername = user.username } } - var html = RichTextProcessor.wrapRichText(message.message, options); + var html = RichTextProcessor.wrapRichText(message.message, options) - $('.im_message_text', element).html(html.valueOf()); + $('.im_message_text', element).html(html.valueOf()) } - function updateMessageMedia($scope, element, message) { + function updateMessageMedia ($scope, element, message) { if (!message.media) { - $('.im_message_media', element).hide(); - return; + $('.im_message_media', element).hide() + return } - var scope = $scope.$new(true); - scope.media = message.media; - scope.messageId = message.mid; + var scope = $scope.$new(true) + scope.media = message.media + scope.messageId = message.mid messageMediaCompiled(scope, function (clonedElement) { - $('.im_message_media', element).replaceWith(clonedElement); - }); + $('.im_message_media', element).replaceWith(clonedElement) + }) } - function updateMessageSignature($scope, element, message) { + function updateMessageSignature ($scope, element, message) { if (!message.signID) { - $('.im_message_sign', element).hide(); - return; + $('.im_message_sign', element).hide() + return } - var scope = $scope.$new(true); - scope.signID = message.signID; + var scope = $scope.$new(true) + scope.signID = message.signID messageSignCompiled(scope, function (clonedElement) { - $('.im_message_sign', element).replaceWith(clonedElement); - }); + $('.im_message_sign', element).replaceWith(clonedElement) + }) } - function updateMessageKeyboard($scope, element, message) { + function updateMessageKeyboard ($scope, element, message) { if (!message.reply_markup || - message.reply_markup._ != 'replyInlineMarkup') { - $('.im_message_keyboard', element).hide(); - return; + message.reply_markup._ != 'replyInlineMarkup') { + $('.im_message_keyboard', element).hide() + return } - var scope = $scope.$new(true); - scope.markup = AppMessagesManager.wrapReplyMarkup(message.reply_markup); - scope.messageId = message.mid; + var scope = $scope.$new(true) + scope.markup = AppMessagesManager.wrapReplyMarkup(message.reply_markup) + scope.messageId = message.mid messageKeyboardCompiled(scope, function (clonedElement) { - $('.im_message_keyboard', element).replaceWith(clonedElement); - }); + $('.im_message_keyboard', element).replaceWith(clonedElement) + }) scope.$on('reply_inline_button_press', function (e, button) { switch (button._) { case 'keyboardButtonSwitchInline': - AppInlineBotsManager.switchInlineButtonClick(message.mid, button); - break; + AppInlineBotsManager.switchInlineButtonClick(message.mid, button) + break case 'keyboardButtonCallback': - AppInlineBotsManager.callbackButtonClick(message.mid, button); - break; + AppInlineBotsManager.callbackButtonClick(message.mid, button) + break } - }); + }) } - function updateMessageBody($scope, element, message) { - updateMessageText($scope, element, message); - updateMessageMedia($scope, element, message); - updateMessageSignature($scope, element, message); - updateMessageKeyboard($scope, element, message); + function updateMessageBody ($scope, element, message) { + updateMessageText($scope, element, message) + updateMessageMedia($scope, element, message) + updateMessageSignature($scope, element, message) + updateMessageKeyboard($scope, element, message) } function link ($scope, element, attrs) { - var message = $scope.message; - message.dir = true; - var msgID = message.mid; + var message = $scope.message + message.dir = true + var msgID = message.mid - updateMessageBody($scope, element, message); + updateMessageBody($scope, element, message) if (message.pending) { var unlink = $scope.$on('messages_pending', function () { if (message.mid != msgID) { - updateMessageBody($scope, element, message); - unlink(); + updateMessageBody($scope, element, message) + unlink() } - }); + }) } $scope.$on('message_edit', function (e, data) { if (data.mid == message.mid) { if (data.justMedia) { - updateMessageMedia($scope, element, message); + updateMessageMedia($scope, element, message) } else { - updateMessageBody($scope, element, message); + updateMessageBody($scope, element, message) } } - }); + }) } }) - .directive('myMessageViews', function($filter, AppMessagesManager) { - - var formatNumberFilter = $filter('formatShortNumber'); + .directive('myMessageViews', function ($filter, AppMessagesManager) { + var formatNumberFilter = $filter('formatShortNumber') return { link: link - }; + } function updateHtml (views, element) { - element.html(formatNumberFilter(views)); + element.html(formatNumberFilter(views)) } function link ($scope, element, attrs) { - var mid = $scope.$eval(attrs.myMessageViews); - // console.log(element[0], mid); - var views = AppMessagesManager.getMessage(mid).views || 0; + var mid = $scope.$eval(attrs.myMessageViews) + // console.log(element[0], mid) + var views = AppMessagesManager.getMessage(mid).views || 0 - updateHtml(views, element); + updateHtml(views, element) $scope.$on('message_views', function (e, viewData) { if (viewData.mid == mid) { - updateHtml(viewData.views, element); + updateHtml(viewData.views, element) } }) } }) - .directive('myReplyMarkup', function() { - + .directive('myReplyMarkup', function () { return { templateUrl: templateUrl('reply_markup'), scope: { 'replyMarkup': '=myReplyMarkup' }, link: link - }; + } function link ($scope, element, attrs) { - var scrollable = $('.reply_markup', element); + var scrollable = $('.reply_markup', element) var scroller = new Scroller(scrollable, { classPrefix: 'reply_markup', maxHeight: 170 - }); + }) $scope.buttonClick = function (button) { - $scope.$emit('reply_button_press', button); + $scope.$emit('reply_button_press', button) } $scope.$on('ui_keyboard_update', function (e, data) { onContentLoaded(function () { - scroller.updateHeight(); - scroller.scrollTo(0); - $scope.$emit('ui_panel_update', {blur: data && data.enabled}); + scroller.updateHeight() + scroller.scrollTo(0) + $scope.$emit('ui_panel_update', {blur: data && data.enabled}) }) - }); + }) onContentLoaded(function () { - scroller.updateHeight(); - $scope.$emit('ui_panel_update'); - }); + scroller.updateHeight() + $scope.$emit('ui_panel_update') + }) } - }) - .directive('myMessageMedia', function() { + .directive('myMessageMedia', function () { return { scope: { 'media': '=myMessageMedia', 'messageId': '=messageId' }, templateUrl: templateUrl('message_media') - }; + } }) - .directive('myMessagePhoto', function(AppPhotosManager) { + .directive('myMessagePhoto', function (AppPhotosManager) { return { scope: { 'media': '=myMessagePhoto', @@ -385,12 +379,12 @@ angular.module('myApp.directives', ['myApp.filters']) }, templateUrl: templateUrl('message_attach_photo'), link: function ($scope, element, attrs) { - $scope.openPhoto = AppPhotosManager.openPhoto; - $scope.preloadPhoto = AppPhotosManager.preloadPhoto; + $scope.openPhoto = AppPhotosManager.openPhoto + $scope.preloadPhoto = AppPhotosManager.preloadPhoto } - }; + } }) - .directive('myMessageDocument', function(AppDocsManager) { + .directive('myMessageDocument', function (AppDocsManager) { return { scope: { 'media': '=myMessageDocument', @@ -398,47 +392,47 @@ angular.module('myApp.directives', ['myApp.filters']) }, templateUrl: templateUrl('message_attach_document'), link: function ($scope, element, attrs) { - AppDocsManager.updateDocDownloaded($scope.media.document.id); + AppDocsManager.updateDocDownloaded($scope.media.document.id) $scope.docSave = function () { - AppDocsManager.saveDocFile($scope.media.document.id); - }; + AppDocsManager.saveDocFile($scope.media.document.id) + } $scope.docOpen = function () { if (!$scope.media.document.withPreview) { - return $scope.docSave(); + return $scope.docSave() } - AppDocsManager.openDoc($scope.media.document.id, $scope.messageId); - }; + AppDocsManager.openDoc($scope.media.document.id, $scope.messageId) + } $scope.videoOpen = function () { - AppDocsManager.openVideo($scope.media.document.id, $scope.messageId); - }; + AppDocsManager.openVideo($scope.media.document.id, $scope.messageId) + } } - }; + } }) - .directive('myMessageGeo', function() { + .directive('myMessageGeo', function () { return { scope: { 'media': '=myMessageGeo' }, templateUrl: templateUrl('message_attach_geo') - }; + } }) - .directive('myMessageVenue', function() { + .directive('myMessageVenue', function () { return { scope: { 'media': '=myMessageVenue' }, templateUrl: templateUrl('message_attach_venue') - }; + } }) - .directive('myMessageContact', function() { + .directive('myMessageContact', function () { return { scope: { 'media': '=myMessageContact' }, templateUrl: templateUrl('message_attach_contact') - }; + } }) - .directive('myMessageWebpage', function(AppWebPagesManager, AppPhotosManager) { + .directive('myMessageWebpage', function (AppWebPagesManager, AppPhotosManager) { return { scope: { 'media': '=myMessageWebpage', @@ -446,1008 +440,978 @@ angular.module('myApp.directives', ['myApp.filters']) }, templateUrl: templateUrl('message_attach_webpage'), link: function ($scope) { - $scope.openPhoto = AppPhotosManager.openPhoto; + $scope.openPhoto = AppPhotosManager.openPhoto $scope.openEmbed = function ($event) { if ($scope.media.webpage && - $scope.media.webpage.embed_url) { - AppWebPagesManager.openEmbed($scope.media.webpage.id, $scope.messageId); - return cancelEvent($event); + $scope.media.webpage.embed_url) { + AppWebPagesManager.openEmbed($scope.media.webpage.id, $scope.messageId) + return cancelEvent($event) } - }; + } $scope.$on('webpage_updated', function (e, eventData) { if ($scope.media.webpage && - $scope.media.webpage.id == eventData.id) { - $scope.$emit('ui_height'); + $scope.media.webpage.id == eventData.id) { + $scope.$emit('ui_height') } - }); + }) } - }; + } }) - .directive('myMessagePending', function() { + .directive('myMessagePending', function () { return { scope: { 'media': '=myMessagePending' }, templateUrl: templateUrl('message_attach_pending') - }; + } }) - .directive('myInlineReplyMarkup', function() { - + .directive('myInlineReplyMarkup', function () { return { templateUrl: templateUrl('reply_markup'), scope: { 'replyMarkup': '=myInlineReplyMarkup' }, link: link - }; + } function link ($scope, element, attrs) { $scope.buttonClick = function (button) { - $scope.$emit('reply_inline_button_press', button); + $scope.$emit('reply_inline_button_press', button) } } - }) - .directive('myServiceMessage', function() { + .directive('myServiceMessage', function () { return { templateUrl: templateUrl('message_service') - }; + } }) - .directive('myShortMessage', function() { + .directive('myShortMessage', function () { return { scope: { message: '=myShortMessage' }, templateUrl: templateUrl('short_message') - }; + } }) - .directive('myReplyMessage', function(AppMessagesManager, AppPeersManager, $rootScope) { - + .directive('myReplyMessage', function (AppMessagesManager, AppPeersManager, $rootScope) { return { templateUrl: templateUrl('reply_message'), scope: { 'replyMessage': '=myReplyMessage' }, link: link - }; + } function link ($scope, element, attrs) { if (attrs.watch) { $scope.$watch('replyMessage', function () { - checkMessage($scope, element); - }); + checkMessage($scope, element) + }) } else { - checkMessage($scope, element); + checkMessage($scope, element) } } function checkMessage ($scope, element) { - var message = $scope.replyMessage; + var message = $scope.replyMessage if (!message.loading) { - updateMessage($scope, element); + updateMessage($scope, element) } else { - var mid = message.mid; + var mid = message.mid var stopWaiting = $scope.$on('messages_downloaded', function (e, mids) { if (mids.indexOf(mid) != -1) { - $scope.replyMessage = AppMessagesManager.wrapForDialog(mid); - updateMessage($scope, element); - stopWaiting(); + $scope.replyMessage = AppMessagesManager.wrapForDialog(mid) + updateMessage($scope, element) + stopWaiting() } - }); + }) } } - function updateMessage($scope, element) { - var message = $scope.replyMessage; + function updateMessage ($scope, element) { + var message = $scope.replyMessage if (!message || message.deleted || !message.to_id) { - $(element).remove(); - return; + $(element).remove() + return } - $scope.thumb = AppMessagesManager.getMessageThumb(message, 42, 42); + $scope.thumb = AppMessagesManager.getMessageThumb(message, 42, 42) if (element[0].tagName == 'A') { element.on('click', function () { - var peerID = AppMessagesManager.getMessagePeer(message); - var peerString = AppPeersManager.getPeerString(peerID); - - $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: message.mid}); + var peerID = AppMessagesManager.getMessagePeer(message) + var peerString = AppPeersManager.getPeerString(peerID) + $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: message.mid}) }) } onContentLoaded(function () { - $scope.$emit('ui_height'); + $scope.$emit('ui_height') }) } - }) - .directive('myPinnedMessage', function(AppMessagesManager, AppPeersManager, $rootScope) { - + .directive('myPinnedMessage', function (AppMessagesManager, AppPeersManager, $rootScope) { return { templateUrl: templateUrl('pinned_message'), scope: { 'pinnedMessage': '=myPinnedMessage' }, link: link - }; + } function link ($scope, element, attrs) { - var message = $scope.pinnedMessage; + var message = $scope.pinnedMessage if (!message.loading) { - updateMessage($scope, element); + updateMessage($scope, element) } else { - var mid = message.mid; + var mid = message.mid var stopWaiting = $scope.$on('messages_downloaded', function (e, mids) { if (mids.indexOf(mid) != -1) { - $scope.pinnedMessage = AppMessagesManager.wrapForDialog(mid); - updateMessage($scope, element); - stopWaiting(); + $scope.pinnedMessage = AppMessagesManager.wrapForDialog(mid) + updateMessage($scope, element) + stopWaiting() } - }); + }) } } - function updateMessage($scope, element) { - var message = $scope.pinnedMessage; + function updateMessage ($scope, element) { + var message = $scope.pinnedMessage if (!message || message.deleted || !message.to_id) { - $(element).remove(); - return; + $(element).remove() + return } if (element[0].tagName == 'A') { element.on('click', function () { - var peerID = AppMessagesManager.getMessagePeer(message); - var peerString = AppPeersManager.getPeerString(peerID); + var peerID = AppMessagesManager.getMessagePeer(message) + var peerString = AppPeersManager.getPeerString(peerID) - $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: message.mid}); + $rootScope.$broadcast('history_focus', {peerString: peerString, messageID: message.mid}) }) } onContentLoaded(function () { - $scope.$emit('ui_height'); + $scope.$emit('ui_height') }) } - }) - .directive('myForwardedMessages', function(AppPhotosManager, AppMessagesManager, AppPeersManager, $rootScope) { - + .directive('myForwardedMessages', function (AppPhotosManager, AppMessagesManager, AppPeersManager, $rootScope) { return { templateUrl: templateUrl('forwarded_messages'), scope: { 'forwardMessages': '=myForwardedMessages' }, link: link - }; + } function link ($scope, element, attrs) { if (attrs.watch) { $scope.$watch('forwardMessages', function () { - updateMessages($scope, element); - }); + updateMessages($scope, element) + }) } else { - updateMessages($scope, element); + updateMessages($scope, element) } } function updateMessages ($scope, element) { - var mids = $scope.forwardMessages; - var length = mids.length; - var fromID = false; - var single = length == 1; - $scope.thumb = false; - $scope.singleMessage = false; + var mids = $scope.forwardMessages + var length = mids.length + var fromID = false + var single = length == 1 + $scope.thumb = false + $scope.singleMessage = false angular.forEach(mids, function (mid) { - var message = AppMessagesManager.getMessage(mid); + var message = AppMessagesManager.getMessage(mid) if (fromID === false) { - fromID = message.fromID; + fromID = message.fromID } else { if (fromID !== message.fromID) { - fromID = AppMessagesManager.getMessagePeer(message); + fromID = AppMessagesManager.getMessagePeer(message) } } if (single) { - $scope.thumb = AppMessagesManager.getMessageThumb(message, 42, 42); - $scope.singleMessage = AppMessagesManager.wrapForDialog(mid); + $scope.thumb = AppMessagesManager.getMessageThumb(message, 42, 42) + $scope.singleMessage = AppMessagesManager.wrapForDialog(mid) } - }); - $scope.fromID = fromID; - $scope.count = length; + }) + $scope.fromID = fromID + $scope.count = length onContentLoaded(function () { - $scope.$emit('ui_height'); + $scope.$emit('ui_height') }) } - }) .directive('myDialogs', function ($modalStack, $transition, $window, $timeout) { - return { link: link - }; - + } function link ($scope, element, attrs) { - var dialogsWrap = $('.im_dialogs_wrap', element)[0], - scrollableWrap = $('.im_dialogs_scrollable_wrap', element)[0], - searchField = $('.im_dialogs_search_field', element)[0], - panelWrap = $('.im_dialogs_panel', element)[0], - searchClear = $('.im_dialogs_search_clear', element)[0], - searchFocused = false; - + var dialogsWrap = $('.im_dialogs_wrap', element)[0] + var scrollableWrap = $('.im_dialogs_scrollable_wrap', element)[0] + var searchField = $('.im_dialogs_search_field', element)[0] + var panelWrap = $('.im_dialogs_panel', element)[0] + var searchClear = $('.im_dialogs_search_clear', element)[0] + var searchFocused = false $(searchField).on('focus blur', function (e) { - searchFocused = e.type == 'focus'; + searchFocused = e.type == 'focus' if (!searchFocused) { - $(scrollableWrap).find('.im_dialog_selected').removeClass('im_dialog_selected'); + $(scrollableWrap).find('.im_dialog_selected').removeClass('im_dialog_selected') if (!searchField.value) { - $scope.$emit('ui_dialogs_search_clear'); + $scope.$emit('ui_dialogs_search_clear') } } - }); + }) $scope.$on('dialogs_search_toggle', function () { - $(panelWrap).addClass('im_dialogs_panel_search'); - $scope.$broadcast('ui_dialogs_search'); - $($window).scrollTop(0); + $(panelWrap).addClass('im_dialogs_panel_search') + $scope.$broadcast('ui_dialogs_search') + $($window).scrollTop(0) $timeout(function () { - setFieldSelection(searchField); + setFieldSelection(searchField) }) - }); + }) $scope.$on('search_clear', function () { - $(panelWrap).removeClass('im_dialogs_panel_search'); - $scope.$broadcast('ui_dialogs_search'); - }); + $(panelWrap).removeClass('im_dialogs_panel_search') + $scope.$broadcast('ui_dialogs_search') + }) - $(document).on('keydown', onKeyDown); + $(document).on('keydown', onKeyDown) $scope.$on('$destroy', function () { - $(document).off('keydown', onKeyDown); - }); + $(document).off('keydown', onKeyDown) + }) $scope.$on('ui_dialogs_change', function () { onContentLoaded(function () { - var selectedDialog = $(scrollableWrap).find('.active a.im_dialog')[0]; + var selectedDialog = $(scrollableWrap).find('.active a.im_dialog')[0] if (selectedDialog) { - scrollToNode(scrollableWrap, selectedDialog.parentNode, dialogsWrap); + scrollToNode(scrollableWrap, selectedDialog.parentNode, dialogsWrap) } - }); - }); + }) + }) - function onKeyDown(e) { + function onKeyDown (e) { if (!searchFocused && $modalStack.getTop()) { - return true; + return true } - if (e.keyCode == 36 && !e.shiftKey && !e.ctrlKey && e.altKey) { // Alt + Home - var currentSelected = $(scrollableWrap).find('.im_dialog_wrap a'); + if (e.keyCode == 36 && !e.shiftKey && !e.ctrlKey && e.altKey) { // Alt + Home + var currentSelected = $(scrollableWrap).find('.im_dialog_wrap a') if (currentSelected.length) { - $(currentSelected[0]).trigger('mousedown'); - scrollableWrap.scrollTop = 0; - $(dialogsWrap).nanoScroller({flash: true}); + $(currentSelected[0]).trigger('mousedown') + scrollableWrap.scrollTop = 0 + $(dialogsWrap).nanoScroller({flash: true}) } - return cancelEvent(e); + return cancelEvent(e) } if (e.keyCode == 27 || e.keyCode == 9 && e.shiftKey && !e.ctrlKey && !e.metaKey) { // ESC or Shift + Tab if (!searchFocused) { - setFieldSelection(searchField); + setFieldSelection(searchField) if (searchField.value) { - searchField.select(); + searchField.select() } } else if (searchField.value) { - $(searchClear).trigger('click'); - } - else { - $scope.$emit('esc_no_more'); + $(searchClear).trigger('click') + }else { + $scope.$emit('esc_no_more') // Strange Chrome bug, when field doesn't get blur, but becomes inactive after location change setTimeout(function () { - searchField.blur(); - searchField.focus(); - }, 100); + searchField.blur() + searchField.focus() + }, 100) } - return cancelEvent(e); + return cancelEvent(e) } if (searchFocused && e.keyCode == 13 && !Config.Navigator.mobile) { // Enter - var currentSelected = $(scrollableWrap).find('.im_dialog_selected')[0] || $(scrollableWrap).find('.im_dialog_wrap a')[0]; + var currentSelected = $(scrollableWrap).find('.im_dialog_selected')[0] || $(scrollableWrap).find('.im_dialog_wrap a')[0] if (currentSelected) { - $(currentSelected).trigger('mousedown'); + $(currentSelected).trigger('mousedown') } - return cancelEvent(e); + return cancelEvent(e) } - if ( e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && - e.keyCode >= 49 && e.keyCode <= 57 ) { // Alt + Shift + # , switch to conversation # where # is in [1..9] + if (e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && + e.keyCode >= 49 && e.keyCode <= 57) { // Alt + Shift + # , switch to conversation # where # is in [1..9] - var dialogNumber = e.keyCode - 49, - dialogWraps = $(scrollableWrap).find('.im_dialog_wrap'), - nextDialogWrap = dialogWraps[dialogNumber]; + var dialogNumber = e.keyCode - 49 + var dialogWraps = $(scrollableWrap).find('.im_dialog_wrap') + var nextDialogWrap = dialogWraps[dialogNumber] if (nextDialogWrap) { - $(nextDialogWrap).find('a').trigger('mousedown'); - scrollToNode(scrollableWrap, nextDialogWrap, dialogsWrap); + $(nextDialogWrap).find('a').trigger('mousedown') + scrollToNode(scrollableWrap, nextDialogWrap, dialogsWrap) } - return cancelEvent(e); + return cancelEvent(e) } - var next, prev, skip, ctrlTabSupported = Config.Modes.packed; + var next + var prev, skip + var ctrlTabSupported = Config.Modes.packed if (e.keyCode == 40 || e.keyCode == 38) { // UP, DOWN - next = e.keyCode == 40; - prev = !next; + next = e.keyCode == 40 + prev = !next skip = !e.shiftKey && e.altKey } else if (ctrlTabSupported && e.keyCode == 9 && e.ctrlKey && !e.metaKey) { // Ctrl + Tab, Shift + Ctrl + Tab - next = !e.shiftKey; - prev = !next; - skip = true; + next = !e.shiftKey + prev = !next + skip = true } if (next || prev) { if (!skip && (!searchFocused || e.metaKey)) { - return true; + return true } - var currentSelected = !skip && $(scrollableWrap).find('.im_dialog_selected')[0] || $(scrollableWrap).find('.active a.im_dialog')[0], - currentSelectedWrap = currentSelected && currentSelected.parentNode, - nextDialogWrap; + var currentSelected = !skip && $(scrollableWrap).find('.im_dialog_selected')[0] || $(scrollableWrap).find('.active a.im_dialog')[0] + var currentSelectedWrap = currentSelected && currentSelected.parentNode, + nextDialogWrap if (currentSelectedWrap) { - var nextDialogWrap = currentSelected[next ? 'nextSibling' : 'previousSibling']; + var nextDialogWrap = currentSelected[next ? 'nextSibling' : 'previousSibling'] if (!nextDialogWrap || !nextDialogWrap.className || nextDialogWrap.className.indexOf('im_dialog_wrap') == -1) { - var dialogWraps = $(scrollableWrap).find('.im_dialog_wrap'), - pos = dialogWraps.index(currentSelected.parentNode), - nextPos = pos + (next ? 1 : -1); + var dialogWraps = $(scrollableWrap).find('.im_dialog_wrap') + var pos = dialogWraps.index(currentSelected.parentNode) + var nextPos = pos + (next ? 1 : -1) - nextDialogWrap = dialogWraps[nextPos]; + nextDialogWrap = dialogWraps[nextPos] } } else { - var dialogWraps = $(scrollableWrap).find('.im_dialog_wrap'); + var dialogWraps = $(scrollableWrap).find('.im_dialog_wrap') if (next) { - nextDialogWrap = dialogWraps[0]; + nextDialogWrap = dialogWraps[0] } else { - nextDialogWrap = dialogWraps[dialogWraps.length - 1]; + nextDialogWrap = dialogWraps[dialogWraps.length - 1] } } if (skip) { if (nextDialogWrap) { - $(nextDialogWrap).find('a').trigger('mousedown'); + $(nextDialogWrap).find('a').trigger('mousedown') } } else { if (currentSelectedWrap && nextDialogWrap) { - $(currentSelectedWrap).find('a').removeClass('im_dialog_selected'); + $(currentSelectedWrap).find('a').removeClass('im_dialog_selected') } if (nextDialogWrap) { - $(nextDialogWrap).find('a').addClass('im_dialog_selected'); + $(nextDialogWrap).find('a').addClass('im_dialog_selected') } } if (nextDialogWrap) { - scrollToNode(scrollableWrap, nextDialogWrap, dialogsWrap); + scrollToNode(scrollableWrap, nextDialogWrap, dialogsWrap) } - return cancelEvent(e); + return cancelEvent(e) } } - } - - }) - .directive('myDialogsList', function($window, $timeout) { - + .directive('myDialogsList', function ($window, $timeout) { return { link: link - }; - + } function link ($scope, element, attrs) { - var dialogsWrap = $('.im_dialogs_wrap', element)[0], - dialogsColWrap = $('.im_dialogs_col_wrap')[0], - scrollableWrap = $('.im_dialogs_scrollable_wrap', element)[0], - headWrap = $('.tg_page_head')[0], - panelWrapSelector = Config.Mobile && attrs.modal - ? '.mobile_modal_body .im_dialogs_panel' - : '.im_dialogs_panel', - panelWrap = $(panelWrapSelector)[0], - footer = $('.footer_wrap')[0], - moreNotified = false; + var dialogsWrap = $('.im_dialogs_wrap', element)[0] + var dialogsColWrap = $('.im_dialogs_col_wrap')[0] + var scrollableWrap = $('.im_dialogs_scrollable_wrap', element)[0] + var headWrap = $('.tg_page_head')[0] + var panelWrapSelector = Config.Mobile && attrs.modal + ? '.mobile_modal_body .im_dialogs_panel' + : '.im_dialogs_panel' + var panelWrap = $(panelWrapSelector)[0] + var footer = $('.footer_wrap')[0] + var moreNotified = false onContentLoaded(function () { - $(dialogsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); - }); + $(dialogsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) + }) var updateScroller = function () { onContentLoaded(function () { - $(dialogsWrap).nanoScroller(); - }); + $(dialogsWrap).nanoScroller() + }) } - $scope.$on('ui_dialogs_prepend', updateScroller); - $scope.$on('ui_dialogs_search', updateSizes); - $scope.$on('ui_dialogs_update', updateSizes); - + $scope.$on('ui_dialogs_prepend', updateScroller) + $scope.$on('ui_dialogs_search', updateSizes) + $scope.$on('ui_dialogs_update', updateSizes) $scope.$on('ui_dialogs_append', function () { onContentLoaded(function () { - updateScroller(); - moreNotified = false; + updateScroller() + moreNotified = false $timeout(function () { - $(scrollableWrap).trigger('scroll'); - }); - }); - }); + $(scrollableWrap).trigger('scroll') + }) + }) + }) $scope.$on('ui_dialogs_change', function () { onContentLoaded(function () { - updateScroller(); - moreNotified = false; + updateScroller() + moreNotified = false $timeout(function () { - $(scrollableWrap).trigger('scroll'); - }); - }); - }); + $(scrollableWrap).trigger('scroll') + }) + }) + }) $(scrollableWrap).on('scroll', function (e) { - if (!element.is(':visible')) return; - // console.log('scroll', moreNotified); + if (!element.is(':visible')) return + // console.log('scroll', moreNotified) if (!moreNotified && scrollableWrap.scrollTop >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight - 300) { - // console.log('emit need more'); - $scope.$emit('dialogs_need_more'); - moreNotified = true; + // console.log('emit need more') + $scope.$emit('dialogs_need_more') + moreNotified = true } - }); - + }) function updateSizes () { if (!panelWrap || !panelWrap.offsetHeight) { - panelWrap = $(panelWrapSelector)[0]; + panelWrap = $(panelWrapSelector)[0] } if (attrs.modal) { var height = $($window).height() - - (panelWrap ? panelWrap.offsetHeight : 49) - - (Config.Mobile ? 46 : 100); - height = Math.min(Config.Mobile ? 350 : 450, height); - $(element).css({height: height}); - updateScroller(); - return; + (panelWrap ? panelWrap.offsetHeight : 49) - + (Config.Mobile ? 46 : 100) + height = Math.min(Config.Mobile ? 350 : 450, height) + $(element).css({height: height}) + updateScroller() + return } if (!headWrap || !headWrap.offsetHeight) { - headWrap = $('.tg_page_head')[0]; + headWrap = $('.tg_page_head')[0] } if (!footer || !footer.offsetHeight) { - footer = $('.footer_wrap')[0]; + footer = $('.footer_wrap')[0] } if (!dialogsColWrap || !dialogsColWrap.offsetHeight) { - dialogsColWrap = $('.im_dialogs_col_wrap')[0]; + dialogsColWrap = $('.im_dialogs_col_wrap')[0] } - var footerHeight = footer ? footer.offsetHeight : 0; + var footerHeight = footer ? footer.offsetHeight : 0 if (footerHeight) { - footerHeight++; // Border bottom + footerHeight++ // Border bottom } $(element).css({ height: $($window).height() - - footerHeight - - (headWrap ? headWrap.offsetHeight : 48) - - (panelWrap ? panelWrap.offsetHeight : 58) - - parseInt($(dialogsColWrap).css('paddingBottom') || 0) - }); + footerHeight - + (headWrap ? headWrap.offsetHeight : 48) - + (panelWrap ? panelWrap.offsetHeight : 58) - + parseInt($(dialogsColWrap).css('paddingBottom') || 0) + }) - updateScroller(); + updateScroller() } - $($window).on('resize', updateSizes); - - updateSizes(); - setTimeout(updateSizes, 1000); - }; + $($window).on('resize', updateSizes) + updateSizes() + setTimeout(updateSizes, 1000) + } }) - .directive('myContactsList', function($window, $timeout) { - + .directive('myContactsList', function ($window, $timeout) { return { link: link - }; + } function link ($scope, element, attrs) { - var searchWrap = $('.contacts_modal_search')[0], - panelWrap = $('.contacts_modal_panel')[0], - contactsWrap = $('.contacts_wrap', element)[0]; + var searchWrap = $('.contacts_modal_search')[0] + var panelWrap = $('.contacts_modal_panel')[0] + var contactsWrap = $('.contacts_wrap', element)[0] onContentLoaded(function () { - $(contactsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); - updateSizes(); - }); + $(contactsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) + updateSizes() + }) function updateSizes () { $(element).css({ height: $($window).height() - - (panelWrap && panelWrap.offsetHeight || 0) - - (searchWrap && searchWrap.offsetHeight || 0) - - (Config.Mobile ? 64 : 200) - }); - $(contactsWrap).nanoScroller(); + (panelWrap && panelWrap.offsetHeight || 0) - + (searchWrap && searchWrap.offsetHeight || 0) - + (Config.Mobile ? 64 : 200) + }) + $(contactsWrap).nanoScroller() } - $($window).on('resize', updateSizes); + $($window).on('resize', updateSizes) $scope.$on('contacts_change', function () { onContentLoaded(updateSizes) - }); - }; - + }) + } }) - .directive('myCountriesList', function($window, $timeout) { - + .directive('myCountriesList', function ($window, $timeout) { return { link: link - }; + } function link ($scope, element, attrs) { - var searchWrap = $('.countries_modal_search')[0], - panelWrap = $('.countries_modal_panel')[0], - countriesWrap = $('.countries_wrap', element)[0]; + var searchWrap = $('.countries_modal_search')[0] + var panelWrap = $('.countries_modal_panel')[0] + var countriesWrap = $('.countries_wrap', element)[0] onContentLoaded(function () { - $(countriesWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); - updateSizes(); - }); + $(countriesWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) + updateSizes() + }) function updateSizes () { $(element).css({ height: $($window).height() - - (panelWrap && panelWrap.offsetHeight || 0) - - (searchWrap && searchWrap.offsetHeight || 0) - - (Config.Mobile ? 46 + 18 : 200) - }); - $(countriesWrap).nanoScroller(); + - (panelWrap && panelWrap.offsetHeight || 0) + - (searchWrap && searchWrap.offsetHeight || 0) + - (Config.Mobile ? 46 + 18 : 200) + }) + $(countriesWrap).nanoScroller() } - $($window).on('resize', updateSizes); + $($window).on('resize', updateSizes) $scope.$on('contacts_change', function () { onContentLoaded(updateSizes) - }); - }; - + }) + } }) - .directive('mySessionsList', function($window, $timeout) { - + .directive('mySessionsList', function ($window, $timeout) { return { link: link - }; + } function link ($scope, element, attrs) { - var sessionsWrap = $('.sessions_wrap', element)[0]; + var sessionsWrap = $('.sessions_wrap', element)[0] onContentLoaded(function () { - $(sessionsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); - updateSizes(); - }); + $(sessionsWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) + updateSizes() + }) function updateSizes () { $(element).css({ height: Math.min(760, $($window).height() - - (Config.Mobile ? 46 + 18 : 200)) - }); - $(sessionsWrap).nanoScroller(); + - (Config.Mobile ? 46 + 18 : 200)) + }) + $(sessionsWrap).nanoScroller() } - $($window).on('resize', updateSizes); - }; - + $($window).on('resize', updateSizes) + } }) - .directive('myStickersList', function($window, $timeout) { - + .directive('myStickersList', function ($window, $timeout) { return { link: link - }; + } function link ($scope, element, attrs) { - var stickersWrap = $('.stickerset_wrap', element)[0]; + var stickersWrap = $('.stickerset_wrap', element)[0] onContentLoaded(function () { - $(stickersWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); - updateSizes(); - }); + $(stickersWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) + updateSizes() + }) function updateSizes () { $(element).css({ height: Math.min(600, $($window).height() - - (Config.Mobile ? 46 + 18 : 200)) - }); - $(stickersWrap).nanoScroller(); + - (Config.Mobile ? 46 + 18 : 200)) + }) + $(stickersWrap).nanoScroller() } - $($window).on('resize', updateSizes); - }; - + $($window).on('resize', updateSizes) + } }) .directive('myHistory', function ($window, $timeout, $rootScope, $transition) { - return { link: link - }; + } function link ($scope, element, attrs) { - var historyWrap = $('.im_history_wrap', element)[0], - historyMessagesEl = $('.im_history_messages', element)[0], - historyEl = $('.im_history', element)[0], - scrollableWrap = $('.im_history_scrollable_wrap', element)[0], - scrollable = $('.im_history_scrollable', element)[0], - emptyWrapEl = $('.im_history_empty_wrap', element)[0], - bottomPanelWrap = $('.im_bottom_panel_wrap', element)[0], - sendFormWrap = $('.im_send_form_wrap', element)[0], - headWrap = $('.tg_page_head')[0], - footer = $('.footer_wrap')[0], - sendForm = $('.im_send_form', element)[0], - moreNotified = false, - lessNotified = false; + var historyWrap = $('.im_history_wrap', element)[0] + var historyMessagesEl = $('.im_history_messages', element)[0] + var historyEl = $('.im_history', element)[0] + var scrollableWrap = $('.im_history_scrollable_wrap', element)[0] + var scrollable = $('.im_history_scrollable', element)[0] + var emptyWrapEl = $('.im_history_empty_wrap', element)[0] + var bottomPanelWrap = $('.im_bottom_panel_wrap', element)[0] + var sendFormWrap = $('.im_send_form_wrap', element)[0] + var headWrap = $('.tg_page_head')[0] + var footer = $('.footer_wrap')[0] + var sendForm = $('.im_send_form', element)[0] + var moreNotified = false + var lessNotified = false onContentLoaded(function () { - scrollableWrap.scrollTop = scrollableWrap.scrollHeight; - }); - $(historyWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}); + scrollableWrap.scrollTop = scrollableWrap.scrollHeight + }) + $(historyWrap).nanoScroller({preventPageScrolling: true, tabIndex: -1, iOSNativeScrolling: true}) var updateScroller = function (delay) { - // console.trace('scroller update', delay); + // console.trace('scroller update', delay) $timeout(function () { if (!$(scrollableWrap).hasClass('im_history_to_bottom')) { - $(historyWrap).nanoScroller(); + $(historyWrap).nanoScroller() } - }, delay || 0); + }, delay || 0) } - var transform = false, - trs = ['transform', 'webkitTransform', 'MozTransform', 'msTransform', 'OTransform'], - i; + var transform = false + var trs = ['transform', 'webkitTransform', 'MozTransform', 'msTransform', 'OTransform'], + i for (i = 0; i < trs.length; i++) { if (trs[i] in historyMessagesEl.style) { - transform = trs[i]; - break; + transform = trs[i] + break } } - var animated = transform && false ? true : false, - curAnimation = false; + var animated = transform && false ? true : false + var curAnimation = false $scope.$on('ui_history_append_new', function (e, options) { if (!atBottom && !options.my) { onContentLoaded(function () { - $(historyWrap).nanoScroller(); - }); - return; + $(historyWrap).nanoScroller() + }) + return } if (options.idleScroll) { onContentLoaded(function () { - $(historyWrap).nanoScroller(); - changeScroll(true); - }); - return; + $(historyWrap).nanoScroller() + changeScroll(true) + }) + return } var curAnimated = animated && - !$rootScope.idle.isIDLE && - historyMessagesEl.clientHeight > 0, - wasH; + !$rootScope.idle.isIDLE && + historyMessagesEl.clientHeight > 0, + wasH if (curAnimated) { - wasH = scrollableWrap.scrollHeight; + wasH = scrollableWrap.scrollHeight } else { var pr = parseInt($(scrollableWrap).css('paddingRight')) - $(scrollable).css({bottom: 0, paddingRight: pr}); - $(scrollableWrap).addClass('im_history_to_bottom'); + $(scrollable).css({bottom: 0, paddingRight: pr}) + $(scrollableWrap).addClass('im_history_to_bottom') } onContentLoaded(function () { if (curAnimated) { - curAnimation = true; - $(historyMessagesEl).removeClass('im_history_appending'); - scrollableWrap.scrollTop = scrollableWrap.scrollHeight; - $(historyMessagesEl).css(transform, 'translate(0px, ' + (scrollableWrap.scrollHeight - wasH) + 'px)'); - $(historyWrap).nanoScroller(); - var styles = {}; - styles[transform] = 'translate(0px, 0px)'; - $(historyMessagesEl).addClass('im_history_appending'); + curAnimation = true + $(historyMessagesEl).removeClass('im_history_appending') + scrollableWrap.scrollTop = scrollableWrap.scrollHeight + $(historyMessagesEl).css(transform, 'translate(0px, ' + (scrollableWrap.scrollHeight - wasH) + 'px)') + $(historyWrap).nanoScroller() + var styles = {} + styles[transform] = 'translate(0px, 0px)' + $(historyMessagesEl).addClass('im_history_appending') $transition($(historyMessagesEl), styles).then(function () { - curAnimation = false; - $(historyMessagesEl).removeClass('im_history_appending'); - updateBottomizer(); - }); + curAnimation = false + $(historyMessagesEl).removeClass('im_history_appending') + updateBottomizer() + }) } else { - $(scrollableWrap).removeClass('im_history_to_bottom'); - $(scrollable).css({bottom: '', paddingRight: 0}); - scrollableWrap.scrollTop = scrollableWrap.scrollHeight; - updateBottomizer(); + $(scrollableWrap).removeClass('im_history_to_bottom') + $(scrollable).css({bottom: '', paddingRight: 0}) + scrollableWrap.scrollTop = scrollableWrap.scrollHeight + updateBottomizer() } - }); - }); + }) + }) function changeScroll (noFocus, animated) { - var unreadSplit, focusMessage; + var unreadSplit + var focusMessage - var newScrollTop = false; - var afterScrollAdd; - // console.trace(dT(), 'change scroll', animated); + var newScrollTop = false + var afterScrollAdd + // console.trace(dT(), 'change scroll', animated) if (!noFocus && - (focusMessage = $('.im_message_focus:visible', scrollableWrap)[0])) { - // console.log(dT(), 'change scroll to focus', focusMessage); - var ch = scrollableWrap.clientHeight, - st = scrollableWrap.scrollTop, - ot = focusMessage.offsetTop, - h = focusMessage.clientHeight; + (focusMessage = $('.im_message_focus:visible', scrollableWrap)[0])) { + // console.log(dT(), 'change scroll to focus', focusMessage) + var ch = scrollableWrap.clientHeight + var st = scrollableWrap.scrollTop + var ot = focusMessage.offsetTop + var h = focusMessage.clientHeight if (!st || st + ch < ot || st > ot + h || animated) { - newScrollTop = Math.max(0, ot - Math.floor(ch / 2) + 26); + newScrollTop = Math.max(0, ot - Math.floor(ch / 2) + 26) } - atBottom = false; + atBottom = false afterScrollAdd = function () { - var unfocusMessagePromise = $(focusMessage).data('unfocus_promise'); + var unfocusMessagePromise = $(focusMessage).data('unfocus_promise') if (unfocusMessagePromise) { - $timeout.cancel(unfocusMessagePromise); - $(focusMessage).removeClass('im_message_focus_active'); + $timeout.cancel(unfocusMessagePromise) + $(focusMessage).removeClass('im_message_focus_active') } $timeout(function () { - $(focusMessage).addClass('im_message_focus_active'); + $(focusMessage).addClass('im_message_focus_active') unfocusMessagePromise = $timeout(function () { - $(focusMessage).removeClass('im_message_focus_active'); - $(focusMessage).data('unfocus_promise', false); - }, 2800); - $(focusMessage).data('unfocus_promise', unfocusMessagePromise); - }); + $(focusMessage).removeClass('im_message_focus_active') + $(focusMessage).data('unfocus_promise', false) + }, 2800) + $(focusMessage).data('unfocus_promise', unfocusMessagePromise) + }) } - } else if (unreadSplit = $('.im_message_unread_split:visible', scrollableWrap)[0]) { - // console.log(dT(), 'change scroll unread', unreadSplit.offsetTop); - newScrollTop = Math.max(0, unreadSplit.offsetTop - 52); - atBottom = false; + // console.log(dT(), 'change scroll unread', unreadSplit.offsetTop) + newScrollTop = Math.max(0, unreadSplit.offsetTop - 52) + atBottom = false } else { - // console.log(dT(), 'change scroll bottom'); - newScrollTop = scrollableWrap.scrollHeight; - atBottom = true; + // console.log(dT(), 'change scroll bottom') + newScrollTop = scrollableWrap.scrollHeight + atBottom = true } if (newScrollTop !== false) { var afterScroll = function () { - updateScroller(); + updateScroller() $timeout(function () { - $(scrollableWrap).trigger('scroll'); - scrollTopInitial = scrollableWrap.scrollTop; - }); + $(scrollableWrap).trigger('scroll') + scrollTopInitial = scrollableWrap.scrollTop + }) if (afterScrollAdd) { - afterScrollAdd(); + afterScrollAdd() } } if (animated) { - $(scrollableWrap).animate({scrollTop: newScrollTop}, 200, afterScroll); + $(scrollableWrap).animate({scrollTop: newScrollTop}, 200, afterScroll) } else { - scrollableWrap.scrollTop = newScrollTop; - afterScroll(); + scrollableWrap.scrollTop = newScrollTop + afterScroll() } } - }; + } $scope.$on('ui_history_change', function () { var pr = parseInt($(scrollableWrap).css('paddingRight')) - $(scrollableWrap).addClass('im_history_to_bottom'); - scrollableWrap.scrollHeight; // Some strange Chrome bug workaround - $(scrollable).css({bottom: 0, paddingRight: pr}); + $(scrollableWrap).addClass('im_history_to_bottom') + scrollableWrap.scrollHeight // Some strange Chrome bug workaround + $(scrollable).css({bottom: 0, paddingRight: pr}) onContentLoaded(function () { - $(scrollableWrap).removeClass('im_history_to_bottom'); - $(scrollable).css({bottom: '', paddingRight: ''}); - updateSizes(true); - moreNotified = false; - lessNotified = false; - changeScroll(); - }); - }); + $(scrollableWrap).removeClass('im_history_to_bottom') + $(scrollable).css({bottom: '', paddingRight: ''}) + updateSizes(true) + moreNotified = false + lessNotified = false + changeScroll() + }) + }) $scope.$on('ui_history_change_scroll', function (e, animated) { onContentLoaded(function () { - changeScroll(false, animated); + changeScroll(false, animated) }) - }); + }) $scope.$on('ui_history_focus', function () { if (!atBottom) { - // console.log(dT(), 'scroll history focus'); - scrollableWrap.scrollTop = scrollableWrap.scrollHeight; - updateScroller(); - atBottom = true; + // console.log(dT(), 'scroll history focus') + scrollableWrap.scrollTop = scrollableWrap.scrollHeight + updateScroller() + atBottom = true } - }); + }) $scope.$on('ui_history_prepend', function () { - var sh = scrollableWrap.scrollHeight, - st = scrollableWrap.scrollTop, - pr = parseInt($(scrollableWrap).css('paddingRight')), - ch = scrollableWrap.clientHeight; + var sh = scrollableWrap.scrollHeight + var st = scrollableWrap.scrollTop + var pr = parseInt($(scrollableWrap).css('paddingRight')) + var ch = scrollableWrap.clientHeight - $(scrollableWrap).addClass('im_history_to_bottom'); - scrollableWrap.scrollHeight; // Some strange Chrome bug workaround - $(scrollable).css({bottom: -(sh - st - ch), paddingRight: pr}); + $(scrollableWrap).addClass('im_history_to_bottom') + scrollableWrap.scrollHeight // Some strange Chrome bug workaround + $(scrollable).css({bottom: -(sh - st - ch), paddingRight: pr}) var upd = function () { - $(scrollableWrap).removeClass('im_history_to_bottom'); - $(scrollable).css({bottom: '', paddingRight: ''}); + $(scrollableWrap).removeClass('im_history_to_bottom') + $(scrollable).css({bottom: '', paddingRight: ''}) if (scrollTopInitial >= 0) { - changeScroll(); + changeScroll() } else { - // console.log('change scroll prepend'); - scrollableWrap.scrollTop = st + scrollableWrap.scrollHeight - sh; + // console.log('change scroll prepend') + scrollableWrap.scrollTop = st + scrollableWrap.scrollHeight - sh } - updateBottomizer(); - moreNotified = false; + updateBottomizer() + moreNotified = false $timeout(function () { if (scrollableWrap.scrollHeight != sh) { - $(scrollableWrap).trigger('scroll'); + $(scrollableWrap).trigger('scroll') } - }); + }) - clearTimeout(timer); - unreg(); + clearTimeout(timer) + unreg() }, timer = setTimeout(upd, 0), - unreg = $scope.$on('$viewContentLoaded', upd); - }); + unreg = $scope.$on('$viewContentLoaded', upd) + }) $scope.$on('ui_history_append', function () { - var sh = scrollableWrap.scrollHeight; + var sh = scrollableWrap.scrollHeight onContentLoaded(function () { - atBottom = false; - updateBottomizer(); - lessNotified = false; + atBottom = false + updateBottomizer() + lessNotified = false if (scrollTopInitial >= 0) { - changeScroll(); + changeScroll() } $timeout(function () { if (scrollableWrap.scrollHeight != sh) { - $(scrollableWrap).trigger('scroll'); + $(scrollableWrap).trigger('scroll') } - }); - }); - }); + }) + }) + }) $scope.$on('ui_panel_update', function (e, data) { - updateSizes(); + updateSizes() onContentLoaded(function () { - updateSizes(); + updateSizes() if (data && data.blur) { - $scope.$broadcast('ui_message_blur'); + $scope.$broadcast('ui_message_blur') } else if (!getSelectedText()) { - $scope.$broadcast('ui_message_send'); + $scope.$broadcast('ui_message_send') } $timeout(function () { - $(scrollableWrap).trigger('scroll'); - }); - }); - }); + $(scrollableWrap).trigger('scroll') + }) + }) + }) $scope.$on('ui_selection_clear', function () { if (window.getSelection) { - if (window.getSelection().empty) { // Chrome - window.getSelection().empty(); - } else if (window.getSelection().removeAllRanges) { // Firefox - window.getSelection().removeAllRanges(); + if (window.getSelection().empty) { // Chrome + window.getSelection().empty() + } else if (window.getSelection().removeAllRanges) { // Firefox + window.getSelection().removeAllRanges() } - } else if (document.selection) { // IE? - document.selection.empty(); + } else if (document.selection) { // IE? + document.selection.empty() } - }); + }) - $scope.$on('ui_editor_resize', updateSizes); + $scope.$on('ui_editor_resize', updateSizes) $scope.$on('ui_height', function () { - onContentLoaded(updateSizes); - // updateSizes(); - }); + onContentLoaded(updateSizes) + // updateSizes() + }) - var atBottom = true, - scrollTopInitial = -1; + var atBottom = true + var scrollTopInitial = -1 $(scrollableWrap).on('scroll', function (e) { if (!element.is(':visible') || - $(scrollableWrap).hasClass('im_history_to_bottom') || - curAnimation) { - return; + $(scrollableWrap).hasClass('im_history_to_bottom') || + curAnimation) { + return } - var st = scrollableWrap.scrollTop; - atBottom = st >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight; + var st = scrollableWrap.scrollTop + atBottom = st >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight if (scrollTopInitial >= 0 && scrollTopInitial != st) { - scrollTopInitial = -1; + scrollTopInitial = -1 } if (!moreNotified && st <= 300) { - moreNotified = true; - $scope.$emit('history_need_more'); + moreNotified = true + $scope.$emit('history_need_more') } else if (!lessNotified && st >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight - 300) { - lessNotified = true; - $scope.$emit('history_need_less'); + lessNotified = true + $scope.$emit('history_need_less') } - }); + }) function updateSizes (heightOnly) { if (!element.is(':visible') && !$(element[0].parentNode.parentNode).is(':visible')) { - return; + return } if ($(sendFormWrap).is(':visible')) { $(sendFormWrap).css({ height: $(sendForm).height() - }); + }) } if (!headWrap || !headWrap.offsetHeight) { - headWrap = $('.tg_page_head')[0]; + headWrap = $('.tg_page_head')[0] } if (!footer || !footer.offsetHeight) { - footer = $('.footer_wrap')[0]; + footer = $('.footer_wrap')[0] } - var footerHeight = footer ? footer.offsetHeight : 0; + var footerHeight = footer ? footer.offsetHeight : 0 if (footerHeight) { - footerHeight++; // Border bottom + footerHeight++ // Border bottom } - var historyH = $($window).height() - bottomPanelWrap.offsetHeight - (headWrap ? headWrap.offsetHeight : 48) - footerHeight; + var historyH = $($window).height() - bottomPanelWrap.offsetHeight - (headWrap ? headWrap.offsetHeight : 48) - footerHeight $(historyWrap).css({ height: historyH - }); - - updateBottomizer(); + }) + updateBottomizer() - if (heightOnly === true) return; + if (heightOnly === true) return if (atBottom) { onContentLoaded(function () { - // console.log('change scroll bottom'); - scrollableWrap.scrollTop = scrollableWrap.scrollHeight; - updateScroller(); - }); + // console.log('change scroll bottom') + scrollableWrap.scrollTop = scrollableWrap.scrollHeight + updateScroller() + }) } - updateScroller(100); + updateScroller(100) } function updateBottomizer () { - $(historyMessagesEl).css({marginTop: 0}); + $(historyMessagesEl).css({marginTop: 0}) var marginTop = scrollableWrap.offsetHeight - - historyMessagesEl.offsetHeight - - emptyWrapEl.offsetHeight - - (Config.Mobile ? 0 : 39); + - historyMessagesEl.offsetHeight + - emptyWrapEl.offsetHeight + - (Config.Mobile ? 0 : 39) if (historyMessagesEl.offsetHeight > 0 && marginTop > 0) { - $(historyMessagesEl).css({marginTop: marginTop}); + $(historyMessagesEl).css({marginTop: marginTop}) } - $(historyWrap).nanoScroller(); + $(historyWrap).nanoScroller() } - $($window).on('resize', updateSizes); + $($window).on('resize', updateSizes) - updateSizes(); - onContentLoaded(updateSizes); + updateSizes() + onContentLoaded(updateSizes) } - }) .directive('mySendForm', function (_, $q, $timeout, $compile, $modalStack, $http, $interpolate, Storage, AppStickersManager, AppDocsManager, ErrorService, AppInlineBotsManager, FileManager, shouldFocusOnInteraction) { @@ -1458,88 +1422,87 @@ angular.module('myApp.directives', ['myApp.filters']) mentions: '=', commands: '=' } - }; + } function link ($scope, element, attrs) { - - var messageField = $('textarea', element)[0]; - var emojiButton = $('.composer_emoji_insert_btn', element)[0]; - var emojiPanel = $('.composer_emoji_panel', element)[0]; - var fileSelects = $('input', element); - var dropbox = $('.im_send_dropbox_wrap', element)[0]; - var messageFieldWrap = $('.im_send_field_wrap', element)[0]; - var dragStarted, dragTimeout; - var submitBtn = $('.im_submit', element)[0]; - - var stickerImageCompiled = $compile(''); - var cachedStickerImages = {}; + var messageField = $('textarea', element)[0] + var emojiButton = $('.composer_emoji_insert_btn', element)[0] + var emojiPanel = $('.composer_emoji_panel', element)[0] + var fileSelects = $('input', element) + var dropbox = $('.im_send_dropbox_wrap', element)[0] + var messageFieldWrap = $('.im_send_field_wrap', element)[0] + var dragStarted + var dragTimeout + var submitBtn = $('.im_submit', element)[0] + + var stickerImageCompiled = $compile('') + var cachedStickerImages = {} var emojiTooltip = new EmojiTooltip(emojiButton, { getStickers: function (callback) { - AppStickersManager.getStickers().then(callback); + AppStickersManager.getStickers().then(callback) }, getStickerImage: function (element, docID) { - var category = element.attr('data-category'); - var cached = cachedStickerImages[docID]; + var category = element.attr('data-category') + var cached = cachedStickerImages[docID] if (cached && !isInDOM(cached[0])) { - cached.attr('data-category', category); - element.replaceWith(cached); - return; + cached.attr('data-category', category) + element.replaceWith(cached) + return } - var scope = $scope.$new(true); - scope.document = AppDocsManager.getDoc(docID); + var scope = $scope.$new(true) + scope.document = AppDocsManager.getDoc(docID) stickerImageCompiled(scope, function (clonedElement) { - cachedStickerImages[docID] = clonedElement; - clonedElement.attr('data-category', category); - element.replaceWith(clonedElement); - }); + cachedStickerImages[docID] = clonedElement + clonedElement.attr('data-category', category) + element.replaceWith(clonedElement) + }) }, onStickersetSelected: function (stickerset) { - AppStickersManager.openStickersetLink(stickerset); + AppStickersManager.openStickersetLink(stickerset) }, onEmojiSelected: function (code) { $scope.$apply(function () { - composer.onEmojiSelected(code); + composer.onEmojiSelected(code) }) }, onStickerSelected: function (docID) { $scope.$apply(function () { - $scope.draftMessage.sticker = docID; - }); + $scope.draftMessage.sticker = docID + }) }, langpack: { im_emoji_tab: _('im_emoji_tab'), im_stickers_tab: _('im_stickers_tab') } - }); + }) $scope.$on('stickers_changed', function () { - emojiTooltip.onStickersChanged(); - }); - + emojiTooltip.onStickersChanged() + }) - var composerEmojiPanel; + var composerEmojiPanel if (emojiPanel) { composerEmojiPanel = new EmojiPanel(emojiPanel, { onEmojiSelected: function (code) { - composer.onEmojiSelected(code); + composer.onEmojiSelected(code) } - }); + }) } var composer = new MessageComposer(messageField, { onTyping: function () { - $scope.$emit('ui_typing'); + $scope.$emit('ui_typing') }, getSendOnEnter: function () { - return sendOnEnter; + return sendOnEnter }, dropdownDirective: function (element, callback) { - var scope = $scope.$new(true); + var scope = $scope.$new(true) var clonedElement = $compile('
')(scope, function (clonedElement, scope) { - element.replaceWith(clonedElement); - callback(scope, clonedElement); - }); + element.replaceWith(clonedElement) + callback(scope, clonedElement) + }) }, mentions: $scope.mentions, commands: $scope.commands, @@ -1548,341 +1511,337 @@ angular.module('myApp.directives', ['myApp.filters']) onFilePaste: onFilePaste, onCommandSend: function (command) { $scope.$apply(function () { - $scope.draftMessage.command = command; - }); + $scope.draftMessage.command = command + }) } - }); + }) - var richTextarea = composer.richTextareaEl && composer.richTextareaEl[0]; + var richTextarea = composer.richTextareaEl && composer.richTextareaEl[0] if (richTextarea) { - $(richTextarea).on('keydown keyup', updateHeight); + $(richTextarea).on('keydown keyup', updateHeight) } $scope.$on('inline_results', function (e, inlineResults) { - var w = Config.Mobile ? $(window).width() : (messageFieldWrap.offsetWidth || 382) - 2; - var h = 80; + var w = Config.Mobile ? $(window).width() : (messageFieldWrap.offsetWidth || 382) - 2 + var h = 80 if (inlineResults) { - AppInlineBotsManager.regroupWrappedResults(inlineResults.results, w, h); + AppInlineBotsManager.regroupWrappedResults(inlineResults.results, w, h) } setZeroTimeout(function () { - composer.setInlineSuggestions(inlineResults); - }); - }); + composer.setInlineSuggestions(inlineResults) + }) + }) - $scope.$on('inline_placeholder', function(e, data) { - composer.setInlinePlaceholder(data.prefix, data.placeholder); - }); + $scope.$on('inline_placeholder', function (e, data) { + composer.setInlinePlaceholder(data.prefix, data.placeholder) + }) fileSelects.on('change', function () { - var self = this; + var self = this $scope.$apply(function () { - $scope.draftMessage.files = Array.prototype.slice.call(self.files); - $scope.draftMessage.isMedia = $(self).hasClass('im_media_attach_input') || Config.Mobile; + $scope.draftMessage.files = Array.prototype.slice.call(self.files) + $scope.draftMessage.isMedia = $(self).hasClass('im_media_attach_input') || Config.Mobile setTimeout(function () { try { - self.value = ''; - } catch (e) {}; - }, 1000); - }); - }); + self.value = '' + } catch (e) {} + }, 1000) + }) + }) - var sendOnEnter = true; + var sendOnEnter = true function updateSendSettings () { Storage.get('send_ctrlenter').then(function (sendOnCtrl) { - sendOnEnter = !sendOnCtrl; - }); - }; - $scope.$on('settings_changed', updateSendSettings); - updateSendSettings(); + sendOnEnter = !sendOnCtrl + }) + } + $scope.$on('settings_changed', updateSendSettings) + updateSendSettings() - $(submitBtn).on('mousedown touchstart', onMessageSubmit); + $(submitBtn).on('mousedown touchstart', onMessageSubmit) function onMessageSubmit (e) { $timeout(function () { - updateValue(); - $scope.draftMessage.send(); - composer.resetTyping(); + updateValue() + $scope.draftMessage.send() + composer.resetTyping() if (composerEmojiPanel) { - composerEmojiPanel.update(); + composerEmojiPanel.update() } - }, shouldFocusOnInteraction ? 0 : 100); - return cancelEvent(e); + }, shouldFocusOnInteraction ? 0 : 100) + return cancelEvent(e) } function onInlineResultSend (qID) { $scope.$apply(function () { - $scope.draftMessage.inlineResultID = qID; - }); + $scope.draftMessage.inlineResultID = qID + }) } function updateValue () { if (richTextarea) { - composer.onChange(); - updateHeight(); + composer.onChange() + updateHeight() } } - var height = richTextarea && richTextarea.offsetHeight; + var height = richTextarea && richTextarea.offsetHeight function updateHeight () { - var newHeight = richTextarea.offsetHeight; + var newHeight = richTextarea.offsetHeight if (height != newHeight) { - height = newHeight; - $scope.$emit('ui_editor_resize'); + height = newHeight + $scope.$emit('ui_editor_resize') } - }; + } - function onKeyDown(e) { + function onKeyDown (e) { if (e.keyCode == 9 && !e.shiftKey && !e.ctrlKey && !e.metaKey && !$modalStack.getTop()) { // TAB - composer.focus(); - return cancelEvent(e); + composer.focus() + return cancelEvent(e) } } - $(document).on('keydown', onKeyDown); + $(document).on('keydown', onKeyDown) - $('body').on('dragenter dragleave dragover drop', onDragDropEvent); - $(document).on('paste', onPasteEvent); + $('body').on('dragenter dragleave dragover drop', onDragDropEvent) + $(document).on('paste', onPasteEvent) if (shouldFocusOnInteraction) { - $scope.$on('ui_peer_change', focusField); - $scope.$on('ui_history_focus', focusField); - $scope.$on('ui_history_change', focusField); + $scope.$on('ui_peer_change', focusField) + $scope.$on('ui_history_focus', focusField) + $scope.$on('ui_history_change', focusField) } - $scope.$on('ui_peer_change', composer.resetTyping.bind(composer)); + $scope.$on('ui_peer_change', composer.resetTyping.bind(composer)) $scope.$on('ui_peer_draft', function (e, options) { - options = options || {}; - var isBroadcast = $scope.draftMessage.isBroadcast; - composer.setPlaceholder(_(isBroadcast ? 'im_broadcast_field_placeholder_raw' : 'im_message_field_placeholder_raw')); + options = options || {} + var isBroadcast = $scope.draftMessage.isBroadcast + composer.setPlaceholder(_(isBroadcast ? 'im_broadcast_field_placeholder_raw' : 'im_message_field_placeholder_raw')) if (options.customSelection) { - composer.setFocusedValue(options.customSelection); - updateHeight(); + composer.setFocusedValue(options.customSelection) + updateHeight() } else { if (richTextarea) { - composer.setValue($scope.draftMessage.text || ''); - updateHeight(); + composer.setValue($scope.draftMessage.text || '') + updateHeight() } if (shouldFocusOnInteraction || options && options.focus) { - composer.focus(); + composer.focus() } } onContentLoaded(function () { - composer.checkAutocomplete(true); - }); + composer.checkAutocomplete(true) + }) if (emojiTooltip && Config.Mobile) { - emojiTooltip.hide(); + emojiTooltip.hide() } - }); + }) $scope.$on('ui_peer_reply', function () { onContentLoaded(function () { - $scope.$emit('ui_editor_resize'); + $scope.$emit('ui_editor_resize') if (shouldFocusOnInteraction) { - composer.focus(); + composer.focus() } }) - }); + }) $scope.$on('mentions_update', function () { - composer.onMentionsUpdated(); - }); + composer.onMentionsUpdated() + }) $scope.$on('ui_message_before_send', function () { - updateValue(); - }); + updateValue() + }) $scope.$on('ui_message_send', function () { if (shouldFocusOnInteraction) { - focusField(); + focusField() } - }); + }) $scope.$on('ui_message_blur', function () { - composer.blur(); - }); + composer.blur() + }) function focusField () { onContentLoaded(function () { - composer.focus(); - }); + composer.focus() + }) } function onFilePaste (blob) { - var mimeType = blob.type || ''; - var fileUrlPromise = $q.when(false); + var mimeType = blob.type || '' + var fileUrlPromise = $q.when(false) if (['image/jpeg', 'image/gif', 'image/png', 'image/bmp'].indexOf(mimeType) >= 0) { - fileUrlPromise = FileManager.getFileCorrectUrl(blob, mimeType); + fileUrlPromise = FileManager.getFileCorrectUrl(blob, mimeType) } fileUrlPromise.then(function (fileUrl) { - fileUrl = fileUrl || false; + fileUrl = fileUrl || false ErrorService.confirm({type: 'FILE_CLIPBOARD_PASTE', fileUrl: fileUrl}).then(function () { - $scope.draftMessage.files = [blob]; - $scope.draftMessage.isMedia = true; - }); + $scope.draftMessage.files = [blob] + $scope.draftMessage.isMedia = true + }) }) - }; + } function onPasteEvent (e) { - var cData = (e.originalEvent || e).clipboardData, - items = cData && cData.items || [], - files = [], - file, i; + var cData = (e.originalEvent || e).clipboardData + var items = cData && cData.items || [] + var files = [], + file + var i for (i = 0; i < items.length; i++) { if (items[i].kind == 'file') { - file = items[i].getAsFile(); - files.push(file); + file = items[i].getAsFile() + files.push(file) } } if (files.length > 0) { if (files.length == 1) { - return onFilePaste(files[0]); + return onFilePaste(files[0]) } ErrorService.confirm({type: 'FILES_CLIPBOARD_PASTE', files: files}).then(function () { - $scope.draftMessage.files = files; - $scope.draftMessage.isMedia = true; - }); + $scope.draftMessage.files = files + $scope.draftMessage.isMedia = true + }) } } - function onDragDropEvent(e) { - var dragStateChanged = false; + function onDragDropEvent (e) { + var dragStateChanged = false if (!dragStarted || dragStarted == 1) { - dragStarted = checkDragEvent(e) ? 2 : 1; - dragStateChanged = true; + dragStarted = checkDragEvent(e) ? 2 : 1 + dragStateChanged = true } if (dragStarted == 2) { if (dragTimeout) { setTimeout(function () { - clearTimeout(dragTimeout); - dragTimeout = false; - }, 0); + clearTimeout(dragTimeout) + dragTimeout = false + }, 0) } if (e.type == 'dragenter' || e.type == 'dragover') { if (dragStateChanged) { if (!Config.Mobile) { - $(emojiButton).hide(); + $(emojiButton).hide() } $(dropbox) .css({height: messageFieldWrap.offsetHeight + 2, width: messageFieldWrap.offsetWidth}) - .show(); + .show() } } else { if (e.type == 'drop') { $scope.$apply(function () { - $scope.draftMessage.files = Array.prototype.slice.call(e.originalEvent.dataTransfer.files); - $scope.draftMessage.isMedia = true; - }); + $scope.draftMessage.files = Array.prototype.slice.call(e.originalEvent.dataTransfer.files) + $scope.draftMessage.isMedia = true + }) } dragTimeout = setTimeout(function () { - $(dropbox).hide(); + $(dropbox).hide() if (!Config.Mobile) { - $(emojiButton).show(); + $(emojiButton).show() } - dragStarted = false; - dragTimeout = false; - }, 300); + dragStarted = false + dragTimeout = false + }, 300) } } - return cancelEvent(e); - }; - + return cancelEvent(e) + } - $scope.$on('$destroy', function cleanup() { - $(document).off('paste', onPasteEvent); - $(document).off('keydown', onKeyDown); - $('body').off('dragenter dragleave dragover drop', onDragDropEvent); - $(submitBtn).off('mousedown touchstart'); - fileSelects.off('change'); - }); + $scope.$on('$destroy', function cleanup () { + $(document).off('paste', onPasteEvent) + $(document).off('keydown', onKeyDown) + $('body').off('dragenter dragleave dragover drop', onDragDropEvent) + $(submitBtn).off('mousedown touchstart') + fileSelects.off('change') + }) if (shouldFocusOnInteraction) { - focusField(); + focusField() } - } }) - .directive('myLoadThumb', function(MtpApiFileManager, FileManager) { - + .directive('myLoadThumb', function (MtpApiFileManager, FileManager) { return { link: link, scope: { thumb: '=' } - }; + } function link ($scope, element, attrs) { - var counter = 0; + var counter = 0 var cachedBlob = MtpApiFileManager.getCachedFile( $scope.thumb && $scope.thumb.location && !$scope.thumb.location.empty && $scope.thumb.location - ); + ) if (cachedBlob) { - element.attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')); + element.attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')) } if ($scope.thumb && $scope.thumb.width && $scope.thumb.height) { - element.attr('width', $scope.thumb.width); - element.attr('height', $scope.thumb.height); + element.attr('width', $scope.thumb.width) + element.attr('height', $scope.thumb.height) } var stopWatching = $scope.$watchCollection('thumb.location', function (newLocation) { if ($scope.thumb && $scope.thumb.width && $scope.thumb.height) { - element.attr('width', $scope.thumb.width); - element.attr('height', $scope.thumb.height); - $scope.$emit('ui_height'); + element.attr('width', $scope.thumb.width) + element.attr('height', $scope.thumb.height) + $scope.$emit('ui_height') } - // console.log('new loc', newLocation, arguments); - var counterSaved = ++counter; + // console.log('new loc', newLocation, arguments) + var counterSaved = ++counter if (!newLocation || newLocation.empty) { - element.attr('src', $scope.thumb && $scope.thumb.placeholder || 'img/blank.gif'); - cleanup(); - return; + element.attr('src', $scope.thumb && $scope.thumb.placeholder || 'img/blank.gif') + cleanup() + return } - var cachedBlob = MtpApiFileManager.getCachedFile(newLocation); + var cachedBlob = MtpApiFileManager.getCachedFile(newLocation) if (cachedBlob) { - element.attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')); - cleanup(); - return; + element.attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')) + cleanup() + return } if (!element.attr('src')) { - element.attr('src', $scope.thumb.placeholder || 'img/blank.gif'); + element.attr('src', $scope.thumb.placeholder || 'img/blank.gif') } MtpApiFileManager.downloadSmallFile($scope.thumb.location).then(function (blob) { if (counterSaved == counter) { - element.attr('src', FileManager.getUrl(blob, 'image/jpeg')); - cleanup(); + element.attr('src', FileManager.getUrl(blob, 'image/jpeg')) + cleanup() } }, function (e) { - console.log('Download image failed', e, $scope.thumb.location, element[0]); + console.log('Download image failed', e, $scope.thumb.location, element[0]) if (counterSaved == counter) { - element.attr('src', $scope.thumb.placeholder || 'img/blank.gif'); - cleanup(); + element.attr('src', $scope.thumb.placeholder || 'img/blank.gif') + cleanup() } - }); + }) }) var cleanup = attrs.watch - ? angular.noop - : function () { - setTimeout(function () { - $scope.$destroy() - stopWatching(); - }, 0); - }; + ? angular.noop + : function () { + setTimeout(function () { + $scope.$destroy() + stopWatching() + }, 0) + } } - }) - .directive('myLoadFullPhoto', function(MtpApiFileManager, FileManager, _) { - + .directive('myLoadFullPhoto', function (MtpApiFileManager, FileManager, _) { return { link: link, transclude: true, @@ -1891,81 +1850,78 @@ angular.module('myApp.directives', ['myApp.filters']) fullPhoto: '=', thumbLocation: '=' } - }; + } function link ($scope, element, attrs) { + var imgElement = $('img', element)[0] + var resizeElements = $('.img_fullsize_with_progress_wrap', element) + .add('.img_fullsize_progress_wrap', element) + .add($(imgElement)) + var resize = function () { + resizeElements.css({width: $scope.fullPhoto.width, height: $scope.fullPhoto.height}) + $scope.$emit('ui_height', true) + } - var imgElement = $('img', element)[0], - resizeElements = $('.img_fullsize_with_progress_wrap', element) - .add('.img_fullsize_progress_wrap', element) - .add($(imgElement)), - resize = function () { - resizeElements.css({width: $scope.fullPhoto.width, height: $scope.fullPhoto.height}); - $scope.$emit('ui_height', true); - }; - - var jump = 0; + var jump = 0 $scope.$watchCollection('fullPhoto.location', function () { - var cachedBlob = MtpApiFileManager.getCachedFile($scope.thumbLocation), - curJump = ++jump; + var cachedBlob = MtpApiFileManager.getCachedFile($scope.thumbLocation) + var curJump = ++jump if (cachedBlob) { - imgElement.src = FileManager.getUrl(cachedBlob, 'image/jpeg'); - resize(); + imgElement.src = FileManager.getUrl(cachedBlob, 'image/jpeg') + resize() } else { - imgElement.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; + imgElement.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' } if (!$scope.fullPhoto.location) { - return; + return } - var apiPromise; + var apiPromise if ($scope.fullPhoto.size) { var inputLocation = { _: 'inputFileLocation', volume_id: $scope.fullPhoto.location.volume_id, local_id: $scope.fullPhoto.location.local_id, secret: $scope.fullPhoto.location.secret - }; - apiPromise = MtpApiFileManager.downloadFile($scope.fullPhoto.location.dc_id, inputLocation, $scope.fullPhoto.size); + } + apiPromise = MtpApiFileManager.downloadFile($scope.fullPhoto.location.dc_id, inputLocation, $scope.fullPhoto.size) } else { - apiPromise = MtpApiFileManager.downloadSmallFile($scope.fullPhoto.location); + apiPromise = MtpApiFileManager.downloadSmallFile($scope.fullPhoto.location) } - $scope.progress = {enabled: true, percent: 0}; + $scope.progress = {enabled: true, percent: 0} apiPromise.then(function (blob) { if (curJump == jump) { - $scope.progress.enabled = false; - imgElement.src = FileManager.getUrl(blob, 'image/jpeg'); - resize(); + $scope.progress.enabled = false + imgElement.src = FileManager.getUrl(blob, 'image/jpeg') + resize() } }, function (e) { - console.log('Download image failed', e, $scope.fullPhoto.location); - $scope.progress.enabled = false; + console.log('Download image failed', e, $scope.fullPhoto.location) + $scope.progress.enabled = false if (e && e.type == 'FS_BROWSER_UNSUPPORTED') { $scope.error = {html: _('error_browser_no_local_file_system_image_md', { - 'moz-link': '{1}', - 'chrome-link': '{1}', - 'telegram-link': '{1}' - })}; + 'moz-link': '{1}', + 'chrome-link': '{1}', + 'telegram-link': '{1}' + })} } else { - $scope.error = {text: _('error_image_download_failed'), error: e}; + $scope.error = {text: _('error_image_download_failed'), error: e} } }, function (progress) { - $scope.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)); - }); + $scope.progress.percent = Math.max(1, Math.floor(100 * progress.done / progress.total)) + }) }) - resize(); + resize() } }) - - .directive('myLoadVideo', function($sce, AppDocsManager, ErrorService, _) { - + .directive('myLoadVideo', function ($sce, AppDocsManager, ErrorService, _) { return { link: link, transclude: true, @@ -1973,191 +1929,185 @@ angular.module('myApp.directives', ['myApp.filters']) scope: { video: '=' } - }; + } function link ($scope, element, attrs) { - - var downloadPromise = AppDocsManager.downloadDoc($scope.video.id); + var downloadPromise = AppDocsManager.downloadDoc($scope.video.id) downloadPromise.then(function () { - $scope.$emit('ui_height'); + $scope.$emit('ui_height') onContentLoaded(function () { - var videoEl = $('video', element)[0]; + var videoEl = $('video', element)[0] if (videoEl) { - var errorAlready = false; + var errorAlready = false var onVideoError = function (event) { if (errorAlready) { - return; + return } if (!event.target || - !event.target.error || - event.target.error.code == event.target.error.MEDIA_ERR_DECODE || - event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { - errorAlready = true; + !event.target.error || + event.target.error.code == event.target.error.MEDIA_ERR_DECODE || + event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { + errorAlready = true ErrorService.show({ error: { type: 'MEDIA_TYPE_NOT_SUPPORTED', originalError: event.target && event.target.error } - }); + }) } - }; + } - videoEl.addEventListener('error', onVideoError, true); + videoEl.addEventListener('error', onVideoError, true) $(videoEl).on('$destroy', function () { - errorAlready = true; - videoEl.removeEventListener('error', onVideoError); - }); + errorAlready = true + videoEl.removeEventListener('error', onVideoError) + }) } - }); + }) }, function (e) { - console.log('Download video failed', e, $scope.video); + console.log('Download video failed', e, $scope.video) if (e && e.type == 'FS_BROWSER_UNSUPPORTED') { $scope.error = {html: _('error_browser_no_local_file_system_video_md', { 'moz-link': '{1}', 'chrome-link': '{1}', 'telegram-link': '{1}' - })}; + })} } else { - $scope.error = {text: _('error_video_download_failed'), error: e}; + $scope.error = {text: _('error_video_download_failed'), error: e} } + }) - }); - - $scope.$emit('ui_height'); + $scope.$emit('ui_height') $scope.$on('$destroy', function () { - downloadPromise.cancel(); - }); + downloadPromise.cancel() + }) } - }) - .directive('myLoadGif', function(AppDocsManager, $timeout) { - + .directive('myLoadGif', function (AppDocsManager, $timeout) { return { link: link, templateUrl: templateUrl('full_gif'), scope: { document: '=' } - }; + } function link ($scope, element, attrs) { + var imgWrap = $('.img_gif_image_wrap', element) + imgWrap.css({width: $scope.document.thumb.width, height: $scope.document.thumb.height}) - var imgWrap = $('.img_gif_image_wrap', element); - imgWrap.css({width: $scope.document.thumb.width, height: $scope.document.thumb.height}); - - var downloadPromise = false; + var downloadPromise = false - $scope.isActive = false; + $scope.isActive = false // Demo - // $scope.document.progress = {enabled: true, percent: 30}; + // $scope.document.progress = {enabled: true, percent: 30} // $timeout(function () { - // $scope.document.progress.percent = 60; - // }, 3000); + // $scope.document.progress.percent = 60 + // }, 3000) // $timeout(function () { - // $scope.document.progress.percent = 100; - // }, 10000); + // $scope.document.progress.percent = 100 + // }, 10000) $scope.toggle = function (e) { if (e && checkClick(e, true)) { - AppDocsManager.saveDocFile($scope.document.id); - return false; + AppDocsManager.saveDocFile($scope.document.id) + return false } if ($scope.document.url) { onContentLoaded(function () { - $scope.isActive = !$scope.isActive; - $scope.$emit('ui_height'); + $scope.isActive = !$scope.isActive + $scope.$emit('ui_height') - var video = $('video', element)[0]; + var video = $('video', element)[0] if (video) { if (!$scope.isActive) { - video.pause(); - video.currentTime = 0; + video.pause() + video.currentTime = 0 } else { - video.play(); + video.play() } } }) - return; + return } if (downloadPromise) { - downloadPromise.cancel(); - downloadPromise = false; - return; + downloadPromise.cancel() + downloadPromise = false + return } - downloadPromise = AppDocsManager.downloadDoc($scope.document.id); + downloadPromise = AppDocsManager.downloadDoc($scope.document.id) downloadPromise.then(function () { $timeout(function () { - $scope.isActive = true; - }, 200); + $scope.isActive = true + }, 200) }) } - // Autoplay small GIFs - // if (!Config.Mobile && - // $scope.document.size && - // $scope.document.size < 1024 * 1024) { - // $scope.toggle(); - // } + // Autoplay small GIFs + // if (!Config.Mobile && + // $scope.document.size && + // $scope.document.size < 1024 * 1024) { + // $scope.toggle() + // } } }) - .directive('myLoadSticker', function(_, MtpApiFileManager, FileManager, AppStickersManager) { - - var emptySrc = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; + .directive('myLoadSticker', function (_, MtpApiFileManager, FileManager, AppStickersManager) { + var emptySrc = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' return { link: link, scope: { document: '=' } - }; + } function link ($scope, element, attrs) { - var imgElement = $('').addClass(attrs.imgClass); - var wasAdded = false; + var imgElement = $('').addClass(attrs.imgClass) + var wasAdded = false - imgElement.attr('alt', '['+ ($scope.document.stickerEmojiRaw || '') + ' ' + _('conversation_media_sticker') +']'); + imgElement.attr('alt', '[' + ($scope.document.stickerEmojiRaw || '') + ' ' + _('conversation_media_sticker') + ']') - var dim = attrs.dim && $scope.$parent.$eval(attrs.dim) || $scope.document.thumb; + var dim = attrs.dim && $scope.$parent.$eval(attrs.dim) || $scope.document.thumb if (attrs.open && $scope.document.stickerSetInput) { element .addClass('clickable') .on('click', function () { - AppStickersManager.openStickerset($scope.document.stickerSetInput); - }); + AppStickersManager.openStickerset($scope.document.stickerSetInput) + }) } var setSrc = function (blob) { - imgElement.attr('src', FileManager.getUrl(blob)); + imgElement.attr('src', FileManager.getUrl(blob)) if (!wasAdded) { - wasAdded = true; - imgElement.appendTo(element); + wasAdded = true + imgElement.appendTo(element) } - }; + } imgElement.css({ width: dim.width, height: dim.height - }); + }) element.css({ width: dim.width, height: dim.height - }); + }) - var smallLocation = false; + var smallLocation = false if ($scope.document.thumb.location) { - smallLocation = angular.copy($scope.document.thumb.location); - smallLocation.sticker = true; + smallLocation = angular.copy($scope.document.thumb.location) + smallLocation.sticker = true } var fullLocation = { @@ -2167,280 +2117,269 @@ angular.module('myApp.directives', ['myApp.filters']) dc_id: $scope.document.dc_id, file_name: $scope.document.file_name, sticker: true - }; - + } - var cachedBlob = MtpApiFileManager.getCachedFile(fullLocation); - var fullDone = false; + var cachedBlob = MtpApiFileManager.getCachedFile(fullLocation) + var fullDone = false if (!cachedBlob) { - cachedBlob = MtpApiFileManager.getCachedFile(smallLocation); + cachedBlob = MtpApiFileManager.getCachedFile(smallLocation) } else { - fullDone = true; + fullDone = true } if (cachedBlob) { - setSrc(cachedBlob); + setSrc(cachedBlob) if (fullDone) { - return; + return } } else { - wasAdded = true; - imgElement.attr('src', emptySrc).appendTo(element); + wasAdded = true + imgElement.attr('src', emptySrc).appendTo(element) } if (attrs.thumb && smallLocation) { MtpApiFileManager.downloadSmallFile(smallLocation).then(function (blob) { - setSrc(blob); + setSrc(blob) }, function (e) { - console.log('Download sticker failed', e, fullLocation); - }); + console.log('Download sticker failed', e, fullLocation) + }) } else { MtpApiFileManager.downloadFile($scope.document.dc_id, fullLocation, $scope.document.size).then(function (blob) { - setSrc(blob); + setSrc(blob) }, function (e) { - console.log('Download sticker failed', e, fullLocation); - }); + console.log('Download sticker failed', e, fullLocation) + }) } } }) - .directive('myLoadDocument', function(MtpApiFileManager, AppDocsManager, FileManager) { - + .directive('myLoadDocument', function (MtpApiFileManager, AppDocsManager, FileManager) { return { link: link, templateUrl: templateUrl('full_document'), scope: { document: '=myLoadDocument' } - }; + } - function updateModalWidth(element, width) { + function updateModalWidth (element, width) { while (element && !$(element).hasClass('modal-dialog')) { - element = element.parentNode; + element = element.parentNode } if (element) { - $(element).width(width + (Config.Mobile ? 0 : 32)); + $(element).width(width + (Config.Mobile ? 0 : 32)) } } function link ($scope, element, attrs) { - var loaderWrap = $('.document_fullsize_with_progress_wrap', element); - var fullSizeWrap = $('.document_fullsize_wrap', element); - var fullSizeImage = $('.document_fullsize_img', element); + var loaderWrap = $('.document_fullsize_with_progress_wrap', element) + var fullSizeWrap = $('.document_fullsize_wrap', element) + var fullSizeImage = $('.document_fullsize_img', element) - var fullWidth = $(window).width() - (Config.Mobile ? 20 : 32); - var fullHeight = $(window).height() - 150; + var fullWidth = $(window).width() - (Config.Mobile ? 20 : 32) + var fullHeight = $(window).height() - 150 if (fullWidth > 800) { - fullWidth -= 208; + fullWidth -= 208 } - $scope.imageWidth = fullWidth; - $scope.imageHeight = fullHeight; + $scope.imageWidth = fullWidth + $scope.imageHeight = fullHeight - var thumbPhotoSize = $scope.document.thumb; + var thumbPhotoSize = $scope.document.thumb if (thumbPhotoSize && thumbPhotoSize._ != 'photoSizeEmpty') { - var wh = calcImageInBox(thumbPhotoSize.width, thumbPhotoSize.height, fullWidth, fullHeight); - $scope.imageWidth = wh.w; - $scope.imageHeight = wh.h; + var wh = calcImageInBox(thumbPhotoSize.width, thumbPhotoSize.height, fullWidth, fullHeight) + $scope.imageWidth = wh.w + $scope.imageHeight = wh.h - var cachedBlob = MtpApiFileManager.getCachedFile(thumbPhotoSize.location); + var cachedBlob = MtpApiFileManager.getCachedFile(thumbPhotoSize.location) if (cachedBlob) { - $scope.thumbSrc = FileManager.getUrl(cachedBlob, 'image/jpeg'); + $scope.thumbSrc = FileManager.getUrl(cachedBlob, 'image/jpeg') } } $scope.frameWidth = Math.max($scope.imageWidth, Math.min(600, fullWidth)) - $scope.frameHeight = $scope.imageHeight; + $scope.frameHeight = $scope.imageHeight onContentLoaded(function () { - $scope.$emit('ui_height'); - }); + $scope.$emit('ui_height') + }) - updateModalWidth(element[0], $scope.frameWidth); + updateModalWidth(element[0], $scope.frameWidth) - var checkSizesInt; - var realImageWidth, realImageHeight; + var checkSizesInt + var realImageWidth + var realImageHeight AppDocsManager.downloadDoc($scope.document.id).then(function (blob) { - var url = FileManager.getUrl(blob, $scope.document.mime_type); - var image = new Image(); - var limit = 100; // 2 sec + var url = FileManager.getUrl(blob, $scope.document.mime_type) + var image = new Image() + var limit = 100 // 2 sec var checkSizes = function (e) { if ((!image.height || !image.width) && --limit) { - return; + return } - realImageWidth = image.width; - realImageHeight = image.height; - clearInterval(checkSizesInt); + realImageWidth = image.width + realImageHeight = image.height + clearInterval(checkSizesInt) - var defaultWh = calcImageInBox(image.width, image.height, fullWidth, fullHeight, true); - var zoomedWh = {w: realImageWidth, h: realImageHeight}; + var defaultWh = calcImageInBox(image.width, image.height, fullWidth, fullHeight, true) + var zoomedWh = {w: realImageWidth, h: realImageHeight} if (defaultWh.w >= zoomedWh.w && defaultWh.h >= zoomedWh.h) { - zoomedWh.w *= 4; - zoomedWh.h *= 4; + zoomedWh.w *= 4 + zoomedWh.h *= 4 } - var zoomed = true; + var zoomed = true $scope.toggleZoom = function () { - zoomed = !zoomed; - var imageWidth = (zoomed ? zoomedWh : defaultWh).w; - var imageHeight = (zoomed ? zoomedWh : defaultWh).h; + zoomed = !zoomed + var imageWidth = (zoomed ? zoomedWh : defaultWh).w + var imageHeight = (zoomed ? zoomedWh : defaultWh).h fullSizeImage.css({ width: imageWidth, height: imageHeight, marginTop: $scope.frameHeight > imageHeight ? Math.floor(($scope.frameHeight - imageHeight) / 2) : 0 - }); - fullSizeWrap.toggleClass('document_fullsize_zoomed', zoomed); - }; - - $scope.toggleZoom(false); + }) + fullSizeWrap.toggleClass('document_fullsize_zoomed', zoomed) + } - fullSizeImage.attr('src', url); - loaderWrap.hide(); - fullSizeWrap.css({width: $scope.frameWidth, height: $scope.frameHeight}).show(); + $scope.toggleZoom(false) - }; - checkSizesInt = setInterval(checkSizes, 20); - image.onload = checkSizes; - image.src = url; - setZeroTimeout(checkSizes); - }); + fullSizeImage.attr('src', url) + loaderWrap.hide() + fullSizeWrap.css({width: $scope.frameWidth, height: $scope.frameHeight}).show() + } + checkSizesInt = setInterval(checkSizes, 20) + image.onload = checkSizes + image.src = url + setZeroTimeout(checkSizes) + }) } }) - .directive('myGeoPointMap', function(ExternalResourcesManager) { + .directive('myGeoPointMap', function (ExternalResourcesManager) { return { link: link, scope: { point: '=myGeoPointMap' } - }; + } function link ($scope, element, attrs) { - var width = element.attr('width') || 200; - var height = element.attr('height') || 200; - var apiKey = Config.ExtCredentials.gmaps.api_key; - var zoom = width > 200 ? 15 : 13; + var width = element.attr('width') || 200 + var height = element.attr('height') || 200 + var apiKey = Config.ExtCredentials.gmaps.api_key + var zoom = width > 200 ? 15 : 13 - element.attr('src', 'img/blank.gif'); + element.attr('src', 'img/blank.gif') - var src = 'https://maps.googleapis.com/maps/api/staticmap?sensor=false¢er=' + $scope.point['lat'] + ',' + $scope.point['long'] + '&zoom=' + zoom + '&size='+width+'x'+height+'&scale=2&key=' + apiKey; + var src = 'https://maps.googleapis.com/maps/api/staticmap?sensor=false¢er=' + $scope.point['lat'] + ',' + $scope.point['long'] + '&zoom=' + zoom + '&size=' + width + 'x' + height + '&scale=2&key=' + apiKey ExternalResourcesManager.downloadByURL(src).then(function (url) { - element.attr('src', url.valueOf()); - }); + element.attr('src', url.valueOf()) + }) } - }) - - .directive('myLoadingDots', function($interval) { - + .directive('myLoadingDots', function ($interval) { return { - link: link, - }; + link: link + } function link ($scope, element, attrs) { element.html(isAnimationSupported(element[0]) ? '
' : '...' - ); + ) } - var animationSupported; + var animationSupported function isAnimationSupported (el) { if (animationSupported === undefined) { - animationSupported = el.style.animationName !== undefined; + animationSupported = el.style.animationName !== undefined if (animationSupported === false) { - var domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), i; + var domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), i for (i = 0; i < domPrefixes.length; i++) { if (el.style[domPrefixes[i] + 'AnimationName'] !== undefined) { - animationSupported = true; - break; + animationSupported = true + break } } } } - return animationSupported; + return animationSupported } }) - .directive('myFocused', function(shouldFocusOnInteraction) { + .directive('myFocused', function (shouldFocusOnInteraction) { return { - link: function($scope, element, attrs) { + link: function ($scope, element, attrs) { if (!shouldFocusOnInteraction) { - return false; + return false } setTimeout(function () { - setFieldSelection(element[0]); - }, 100); + setFieldSelection(element[0]) + }, 100) } - }; + } }) - .directive('myFocusOn', function(shouldFocusOnInteraction) { + .directive('myFocusOn', function (shouldFocusOnInteraction) { return { - link: function($scope, element, attrs) { + link: function ($scope, element, attrs) { $scope.$on(attrs.myFocusOn, function () { if (!shouldFocusOnInteraction) { - return false; + return false } onContentLoaded(function () { - setFieldSelection(element[0]); - }); - }); + setFieldSelection(element[0]) + }) + }) } - }; + } }) - .directive('myFileUpload', function(){ - + .directive('myFileUpload', function () { return { link: link - }; + } - function link($scope, element, attrs) { + function link ($scope, element, attrs) { element.on('change', function () { - var self = this; + var self = this $scope.$apply(function () { - $scope.photo.file = self.files[0]; + $scope.photo.file = self.files[0] setTimeout(function () { try { - self.value = ''; - } catch (e) {}; - }, 1000); - }); - }); - }; + self.value = '' + } catch (e) {} + }, 1000) + }) + }) + } }) - .directive('myModalWidth', function () { - return { link: link - }; + } - function link($scope, element, attrs) { + function link ($scope, element, attrs) { attrs.$observe('myModalWidth', function (newW) { - $(element[0].parentNode.parentNode).css({width: parseInt(newW) + (Config.Mobile ? 0 : 32)}); - }); - }; - + $(element[0].parentNode.parentNode).css({width: parseInt(newW) + (Config.Mobile ? 0 : 32)}) + }) + } }) .directive('myModalNav', function () { - return { link: link - }; - - function link($scope, element, attrs) { + } + function link ($scope, element, attrs) { var onKeyDown = function (event) { - var target = event.target; + var target = event.target if (target && (target.tagName == 'INPUT' || target.tagName == 'TEXTAREA')) { - return; + return } switch (event.keyCode) { @@ -2448,552 +2387,522 @@ angular.module('myApp.directives', ['myApp.filters']) case 32: // space case 34: // pg down case 40: // down - $scope.$eval(attrs.next); - break; + $scope.$eval(attrs.next) + break case 37: // left case 33: // pg up case 38: // up - $scope.$eval(attrs.prev); - break; + $scope.$eval(attrs.prev) + break } - }; + } - $(document).on('keydown', onKeyDown); + $(document).on('keydown', onKeyDown) $scope.$on('$destroy', function () { - $(document).off('keydown', onKeyDown); - }); - }; + $(document).off('keydown', onKeyDown) + }) + } }) .directive('myCustomBackground', function () { - return { link: link - }; - - function link($scope, element, attrs) { + } - $('html').css({background: attrs.myCustomBackground}); + function link ($scope, element, attrs) { + $('html').css({background: attrs.myCustomBackground}) $scope.$on('$destroy', function () { - $('html').css({background: ''}); - }); - }; + $('html').css({background: ''}) + }) + } }) .directive('myInfiniteScroller', function () { - return { link: link, scope: true - }; - - function link($scope, element, attrs) { + } - var scrollableWrap = $('.nano-content', element)[0], - moreNotified = false; + function link ($scope, element, attrs) { + var scrollableWrap = $('.nano-content', element)[0] + var moreNotified = false $(scrollableWrap).on('scroll', function (e) { - if (!element.is(':visible')) return; + if (!element.is(':visible')) return if (!moreNotified && - scrollableWrap.scrollTop >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight - 300) { - moreNotified = true; + scrollableWrap.scrollTop >= scrollableWrap.scrollHeight - scrollableWrap.clientHeight - 300) { + moreNotified = true $scope.$apply(function () { - $scope.slice.limit += ($scope.slice.limitDelta || 20); - }); + $scope.slice.limit += ($scope.slice.limitDelta || 20) + }) onContentLoaded(function () { - moreNotified = false; - $(element).nanoScroller(); - }); + moreNotified = false + $(element).nanoScroller() + }) } - }); - - }; + }) + } }) - - - .directive('myModalPosition', function ($window, $timeout) { - return { link: link - }; - - function link($scope, element, attrs) { + } + function link ($scope, element, attrs) { var updateMargin = function () { if (Config.Mobile && - $(element[0].parentNode.parentNode.parentNode).hasClass('mobile_modal')) { - return; + $(element[0].parentNode.parentNode.parentNode).hasClass('mobile_modal')) { + return } - var height = element[0].parentNode.offsetHeight, - modal = element[0].parentNode.parentNode.parentNode, - bottomPanel = $('.media_modal_bottom_panel_wrap', modal)[0], - contHeight = modal.offsetHeight - (bottomPanel && bottomPanel.offsetHeight || 0); + var height = element[0].parentNode.offsetHeight + var modal = element[0].parentNode.parentNode.parentNode + var bottomPanel = $('.media_modal_bottom_panel_wrap', modal)[0] + var contHeight = modal.offsetHeight - (bottomPanel && bottomPanel.offsetHeight || 0) if (height < contHeight) { - $(element[0].parentNode).css('marginTop', (contHeight - height) / 2); + $(element[0].parentNode).css('marginTop', (contHeight - height) / 2) } else { - $(element[0].parentNode).css('marginTop', ''); + $(element[0].parentNode).css('marginTop', '') } if (attrs.animation != 'no') { $timeout(function () { - $(element[0].parentNode).addClass('modal-content-animated'); - }, 300); + $(element[0].parentNode).addClass('modal-content-animated') + }, 300) } - }; + } - onContentLoaded(updateMargin); + onContentLoaded(updateMargin) - $($window).on('resize', updateMargin); + $($window).on('resize', updateMargin) $scope.$on('ui_height', function (e, sync) { if (sync) { - updateMargin(); + updateMargin() } else { - onContentLoaded(updateMargin); + onContentLoaded(updateMargin) } - }); - - }; - + }) + } }) - .directive('myVerticalPosition', function ($window, $timeout) { - return { link: link - }; - - function link($scope, element, attrs) { + } - var usePadding = attrs.padding === 'true', - prevMargin = 0; + function link ($scope, element, attrs) { + var usePadding = attrs.padding === 'true' + var prevMargin = 0 var updateMargin = function () { - var height = element[0].offsetHeight, - fullHeight = height - (height && usePadding ? 2 * prevMargin : 0), - ratio = attrs.myVerticalPosition && parseFloat(attrs.myVerticalPosition) || 0.5, - contHeight = attrs.contHeight ? $scope.$eval(attrs.contHeight) : $($window).height(), - margin = fullHeight < contHeight ? parseInt((contHeight - fullHeight) * ratio) : '', - styles = usePadding - ? {paddingTop: margin, paddingBottom: margin} - : {marginTop: margin, marginBottom: margin}; - - element.css(styles); - element.addClass('vertical-aligned'); + var height = element[0].offsetHeight + var fullHeight = height - (height && usePadding ? 2 * prevMargin : 0) + var ratio = attrs.myVerticalPosition && parseFloat(attrs.myVerticalPosition) || 0.5 + var contHeight = attrs.contHeight ? $scope.$eval(attrs.contHeight) : $($window).height() + var margin = fullHeight < contHeight ? parseInt((contHeight - fullHeight) * ratio) : '' + var styles = usePadding + ? {paddingTop: margin, paddingBottom: margin} + : {marginTop: margin, marginBottom: margin} + + element.css(styles) + element.addClass('vertical-aligned') if (prevMargin !== margin) { - $scope.$emit('ui_height'); + $scope.$emit('ui_height') } - prevMargin = margin; - }; - - $($window).on('resize', updateMargin); + prevMargin = margin + } - onContentLoaded(updateMargin); + $($window).on('resize', updateMargin) + onContentLoaded(updateMargin) $scope.$on('ui_height', function () { - onContentLoaded(updateMargin); - }); - - }; - + onContentLoaded(updateMargin) + }) + } }) .directive('myUserStatus', function ($filter, $rootScope, AppUsersManager) { + var statusFilter = $filter('userStatus') + var ind = 0 + var statuses = {} - var statusFilter = $filter('userStatus'), - ind = 0, - statuses = {}; - - setInterval(updateAll, 90000); + setInterval(updateAll, 90000) $rootScope.$on('stateSynchronized', function () { setTimeout(function () { - updateAll(); - }, 100); - }); - + updateAll() + }, 100) + }) return { link: link - }; + } function updateAll () { angular.forEach(statuses, function (update) { - update(); - }); + update() + }) } - function link($scope, element, attrs) { - var userID, - curInd = ind++, - update = function () { - var user = AppUsersManager.getUser(userID); - element - .html(statusFilter(user, attrs.botChatPrivacy)) - .toggleClass('status_online', user.status && user.status._ == 'userStatusOnline' || false); - // console.log(dT(), 'update status', element[0], user.status && user.status, tsNow(true), element.html()); - }; + function link ($scope, element, attrs) { + var userID + var curInd = ind++ + var update = function () { + var user = AppUsersManager.getUser(userID) + element + .html(statusFilter(user, attrs.botChatPrivacy)) + .toggleClass('status_online', user.status && user.status._ == 'userStatusOnline' || false) + // console.log(dT(), 'update status', element[0], user.status && user.status, tsNow(true), element.html()) + } $scope.$watch(attrs.myUserStatus, function (newUserID) { - userID = newUserID; - update(); - }); + userID = newUserID + update() + }) $scope.$on('user_update', function (e, updUserID) { if (userID == updUserID) { - update(); + update() } - }); - statuses[curInd] = update; + }) + statuses[curInd] = update $scope.$on('$destroy', function () { - delete statuses[curInd]; - }); + delete statuses[curInd] + }) } }) .directive('myChatStatus', function ($rootScope, _, MtpApiManager, AppChatsManager, AppUsersManager, AppProfileManager) { + var ind = 0 + var statuses = {} - var ind = 0; - var statuses = {}; + var allPluralize = _.pluralize('group_modal_pluralize_participants') + var onlinePluralize = _.pluralize('group_modal_pluralize_online_participants') - var allPluralize = _.pluralize('group_modal_pluralize_participants'); - var onlinePluralize = _.pluralize('group_modal_pluralize_online_participants'); - - var myID = 0; + var myID = 0 MtpApiManager.getUserID().then(function (newMyID) { - myID = newMyID; - }); + myID = newMyID + }) - setInterval(updateAll, 90000); + setInterval(updateAll, 90000) return { link: link - }; + } function updateAll () { angular.forEach(statuses, function (update) { - update(); - }); + update() + }) } - function link($scope, element, attrs) { - var chatID; - var curInd = ind++; - var jump = 0; - var participantsCount = 0; - var participants = {}; + function link ($scope, element, attrs) { + var chatID + var curInd = ind++ + var jump = 0 + var participantsCount = 0 + var participants = {} var updateParticipants = function () { - var curJump = ++jump; - participantsCount = 0; - participants = {}; + var curJump = ++jump + participantsCount = 0 + participants = {} if (!chatID) { - update(); - return; + update() + return } AppProfileManager.getChatFull(chatID).then(function (chatFull) { if (curJump != jump) { - return; + return } - var participantsVector = (chatFull.participants || {}).participants || []; - participantsCount = participantsVector.length; + var participantsVector = (chatFull.participants || {}).participants || [] + participantsCount = participantsVector.length angular.forEach(participantsVector, function (participant) { - participants[participant.user_id] = true; - }); + participants[participant.user_id] = true + }) if (chatFull.participants_count) { - participantsCount = chatFull.participants_count || 0; + participantsCount = chatFull.participants_count || 0 } - update(); - }); - }; + update() + }) + } var update = function () { - var html = allPluralize(participantsCount); - var onlineCount = 0; + var html = allPluralize(participantsCount) + var onlineCount = 0 if (!AppChatsManager.isChannel(chatID)) { - var wasMe = false; + var wasMe = false angular.forEach(participants, function (t, userID) { - var user = AppUsersManager.getUser(userID); + var user = AppUsersManager.getUser(userID) if (user.status && user.status._ == 'userStatusOnline') { if (user.id == myID) { - wasMe = true; + wasMe = true } - onlineCount++; + onlineCount++ } - }); + }) if (onlineCount > 1 || onlineCount == 1 && !wasMe) { - html = _('group_modal_participants', {total: html, online: onlinePluralize(onlineCount)}); + html = _('group_modal_participants', {total: html, online: onlinePluralize(onlineCount)}) } } if (!onlineCount && !participantsCount) { - html = ''; + html = '' } - element.html(html); - }; + element.html(html) + } $scope.$watch(attrs.myChatStatus, function (newChatID) { - chatID = newChatID; - updateParticipants(); - }); + chatID = newChatID + updateParticipants() + }) $rootScope.$on('chat_full_update', function (e, updChatID) { if (chatID == updChatID) { - updateParticipants(); + updateParticipants() } - }); + }) $rootScope.$on('user_update', function (e, updUserID) { if (participants[updUserID]) { - update(); + update() } - }); + }) - statuses[curInd] = update; + statuses[curInd] = update $scope.$on('$destroy', function () { - delete statuses[curInd]; - }); + delete statuses[curInd] + }) } }) .directive('myPeerMuted', function ($rootScope, NotificationsManager) { - return { link: link - }; + } function link ($scope, element, attrs) { - var peerID = $scope.$eval(attrs.myPeerMuted); - var className = attrs.mutedClass || 'muted'; + var peerID = $scope.$eval(attrs.myPeerMuted) + var className = attrs.mutedClass || 'muted' var unsubscribe = $rootScope.$on('notify_settings', function (e, data) { if (data.peerID == peerID) { - updateClass(peerID, element, className); + updateClass(peerID, element, className) } - }); - updateClass(peerID, element, className); + }) + updateClass(peerID, element, className) - $scope.$on('$destroy', unsubscribe); + $scope.$on('$destroy', unsubscribe) } function updateClass (peerID, element, className) { NotificationsManager.getPeerMuted(peerID).then(function (muted) { - element.toggleClass(className, muted); - }); + element.toggleClass(className, muted) + }) } }) - .directive('myPeerLink', function (AppChatsManager, AppUsersManager) { - return { link: link - }; - - function link($scope, element, attrs) { + } - var override = attrs.userOverride && $scope.$eval(attrs.userOverride) || {}; - var short = attrs.short && $scope.$eval(attrs.short); - var username = attrs.username && $scope.$eval(attrs.username); + function link ($scope, element, attrs) { + var override = attrs.userOverride && $scope.$eval(attrs.userOverride) || {} + var short = attrs.short && $scope.$eval(attrs.short) + var username = attrs.username && $scope.$eval(attrs.username) - var peerID; + var peerID var update = function () { if (element[0].className.indexOf('user_color_') != -1) { - element[0].className = element[0].className.replace(/user_color_\d+/g, ''); + element[0].className = element[0].className.replace(/user_color_\d+/g, '') } if (peerID > 0) { - var user = AppUsersManager.getUser(peerID); - var prefix = username ? '@' : ''; - var key = username ? 'username' : (short ? 'rFirstName' : 'rFullName'); + var user = AppUsersManager.getUser(peerID) + var prefix = username ? '@' : '' + var key = username ? 'username' : (short ? 'rFirstName' : 'rFullName') element.html( prefix + (override[key] || user[key] || '').valueOf() + (attrs.verified && user.pFlags && user.pFlags.verified ? ' ' : '') - ); + ) if (attrs.color && $scope.$eval(attrs.color)) { - element.addClass('user_color_' + user.num); + element.addClass('user_color_' + user.num) } } else { - var chat = AppChatsManager.getChat(-peerID); + var chat = AppChatsManager.getChat(-peerID) element.html( (chat.rTitle || '').valueOf() + (attrs.verified && chat.pFlags && chat.pFlags.verified ? ' ' : '') - ); + ) } - }; + } if (element[0].tagName == 'A' && !hasOnlick(element[0])) { element.on('click', function () { if (peerID > 0) { - AppUsersManager.openUser(peerID, override); + AppUsersManager.openUser(peerID, override) } else { - AppChatsManager.openChat(-peerID); + AppChatsManager.openChat(-peerID) } - }); + }) } if (attrs.peerWatch) { // userWatch, chatWatch $scope.$watch(attrs.myPeerLink, function (newPeerID) { - peerID = newPeerID; - update(); - }); + peerID = newPeerID + update() + }) } else { - peerID = $scope.$eval(attrs.myPeerLink); - update(); + peerID = $scope.$eval(attrs.myPeerLink) + update() } if (!attrs.noWatch) { $scope.$on('user_update', function (e, updUserID) { if (peerID == updUserID) { - update(); + update() } - }); + }) $scope.$on('chat_update', function (e, updChatID) { if (peerID == -updChatID) { - update(); + update() } - }); + }) } } }) .directive('myPeerPhotolink', function (AppPeersManager, AppUsersManager, AppChatsManager, MtpApiFileManager, FileManager) { - return { link: link - }; + } - function link($scope, element, attrs) { - element.addClass('peer_photo_init'); + function link ($scope, element, attrs) { + element.addClass('peer_photo_init') - var peerID, peer, peerPhoto; - var imgEl = $(''); - var initEl = $(''); - var jump = 0; - var prevClass = false; + var peerID, peer + var peerPhoto + var imgEl = $('') + var initEl = $('') + var jump = 0 + var prevClass = false var setPeerID = function (newPeerID) { if (peerID == newPeerID) { - return false; + return false } - peerID = newPeerID; - peer = AppPeersManager.getPeer(peerID); + peerID = newPeerID + peer = AppPeersManager.getPeer(peerID) - var newClass = 'user_bgcolor_' + (peer.num || 1); + var newClass = 'user_bgcolor_' + (peer.num || 1) if (newClass != prevClass) { if (prevClass) { - initEl.removeClass(prevClass); + initEl.removeClass(prevClass) } - initEl.addClass(newClass); - prevClass = newClass; + initEl.addClass(newClass) + prevClass = newClass } - updatePeerPhoto(); + updatePeerPhoto() - return true; + return true } var updatePeerPhoto = function () { - var curJump = ++jump; + var curJump = ++jump - peerPhoto = peer.photo && angular.copy(peer.photo.photo_small); + peerPhoto = peer.photo && angular.copy(peer.photo.photo_small) - var hasPhoto = peerPhoto !== undefined; + var hasPhoto = peerPhoto !== undefined if (hasPhoto) { - var cachedBlob = MtpApiFileManager.getCachedFile(peer.photo.photo_small); + var cachedBlob = MtpApiFileManager.getCachedFile(peer.photo.photo_small) if (cachedBlob) { - initEl.remove(); - imgEl.prependTo(element).attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')); - return; + initEl.remove() + imgEl.prependTo(element).attr('src', FileManager.getUrl(cachedBlob, 'image/jpeg')) + return } } - initEl.attr('data-content', peer.initials || '').prependTo(element); - imgEl.remove(); - + initEl.attr('data-content', peer.initials || '').prependTo(element) + imgEl.remove() if (hasPhoto) { - MtpApiFileManager.downloadSmallFile(peer.photo.photo_small).then(function (blob) { if (curJump != jump) { - return; + return } - initEl.remove(); - imgEl.prependTo(element).attr('src', FileManager.getUrl(blob, 'image/jpeg')); - + initEl.remove() + imgEl.prependTo(element).attr('src', FileManager.getUrl(blob, 'image/jpeg')) }, function (e) { - console.log('Download image failed', e, peer.photo.photo_small, element[0]); - }); + console.log('Download image failed', e, peer.photo.photo_small, element[0]) + }) } - }; + } if (element[0].tagName == 'A' && !attrs.noOpen) { element.on('click', function (e) { if (peerID > 0) { - AppUsersManager.openUser(peerID, attrs.userOverride && $scope.$eval(attrs.userOverride)); + AppUsersManager.openUser(peerID, attrs.userOverride && $scope.$eval(attrs.userOverride)) } else { - AppChatsManager.openChat(-peerID); + AppChatsManager.openChat(-peerID) } - }); + }) } - $scope.$watch(attrs.myPeerPhotolink, setPeerID); - setPeerID($scope.$eval(attrs.myPeerPhotolink)); + $scope.$watch(attrs.myPeerPhotolink, setPeerID) + setPeerID($scope.$eval(attrs.myPeerPhotolink)) if (attrs.watch) { $scope.$on('user_update', function (e, updUserID) { if (peerID == updUserID) { if (!angular.equals(peer.photo && peer.photo.photo_small, peerPhoto)) { - updatePeerPhoto(); + updatePeerPhoto() } } - }); + }) $scope.$on('chat_update', function (e, updChatID) { if (peerID == -updChatID) { if (!angular.equals(peer.photo && peer.photo.photo_small, peerPhoto)) { - updatePeerPhoto(); + updatePeerPhoto() } } - }); + }) } - } }) .directive('myAudioPlayer', function ($timeout, $q, Storage, AppDocsManager, AppMessagesManager, ErrorService) { - - var currentPlayer = false; - var audioVolume = 0.5; + var currentPlayer = false + var audioVolume = 0.5 Storage.get('audio_volume').then(function (newAudioVolume) { if (newAudioVolume > 0 && newAudioVolume <= 1.0) { - audioVolume = newAudioVolume; + audioVolume = newAudioVolume } - }); + }) var onAudioError = function (event) { if (!event.target || - !event.target.error || - event.target.error.code == event.target.error.MEDIA_ERR_DECODE || - event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { + !event.target.error || + event.target.error.code == event.target.error.MEDIA_ERR_DECODE || + event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { ErrorService.show({ error: { type: 'MEDIA_TYPE_NOT_SUPPORTED', originalError: event.target && event.target.error } - }); + }) } - }; + } return { link: link, @@ -3002,96 +2911,95 @@ angular.module('myApp.directives', ['myApp.filters']) message: '=' }, templateUrl: templateUrl('audio_player') - }; + } function checkPlayer (newPlayer) { if (newPlayer === currentPlayer) { - return false; + return false } if (currentPlayer) { - currentPlayer.pause(); + currentPlayer.pause() } - currentPlayer = newPlayer; + currentPlayer = newPlayer } - function link($scope, element, attrs) { - AppDocsManager.updateDocDownloaded($scope.audio.id); + function link ($scope, element, attrs) { + AppDocsManager.updateDocDownloaded($scope.audio.id) - $scope.volume = audioVolume; - $scope.mediaPlayer = {}; + $scope.volume = audioVolume + $scope.mediaPlayer = {} $scope.download = function () { - AppDocsManager.saveDocFile($scope.audio.id); - }; + AppDocsManager.saveDocFile($scope.audio.id) + } $scope.togglePlay = function () { if ($scope.audio.url) { - checkPlayer($scope.mediaPlayer.player); - $scope.mediaPlayer.player.playPause(); + checkPlayer($scope.mediaPlayer.player) + $scope.mediaPlayer.player.playPause() } else if ($scope.audio.progress && $scope.audio.progress.enabled) { - return; - } - else { + return + }else { AppDocsManager.downloadDoc($scope.audio.id).then(function () { onContentLoaded(function () { - var errorListenerEl = $('audio', element)[0] || element[0]; + var errorListenerEl = $('audio', element)[0] || element[0] if (errorListenerEl) { - var errorAlready = false; + var errorAlready = false var onAudioError = function (event) { if (errorAlready) { - return; + return } if (!event.target || - !event.target.error || - event.target.error.code == event.target.error.MEDIA_ERR_DECODE || - event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { - errorAlready = true; + !event.target.error || + event.target.error.code == event.target.error.MEDIA_ERR_DECODE || + event.target.error.code == event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) { + errorAlready = true ErrorService.show({ error: { type: 'MEDIA_TYPE_NOT_SUPPORTED', originalError: event.target && event.target.error } - }); + }) } - }; + } - errorListenerEl.addEventListener('error', onAudioError, true); + errorListenerEl.addEventListener('error', onAudioError, true) $scope.$on('$destroy', function () { - errorAlready = true; - errorListenerEl.removeEventListener('error', onAudioError); - }); + errorAlready = true + errorListenerEl.removeEventListener('error', onAudioError) + }) } setTimeout(function () { - checkPlayer($scope.mediaPlayer.player); - $scope.mediaPlayer.player.setVolume(audioVolume); - $scope.mediaPlayer.player.play(); + checkPlayer($scope.mediaPlayer.player) + $scope.mediaPlayer.player.setVolume(audioVolume) + $scope.mediaPlayer.player.play() if ($scope.message && - !$scope.message.pFlags.out && - $scope.message.pFlags.media_unread) { - AppMessagesManager.readMessages([$scope.message.mid]); + !$scope.message.pFlags.out && + $scope.message.pFlags.media_unread) { + AppMessagesManager.readMessages([$scope.message.mid]) } - }, 300); - }); + }, 300) + }) }) } - }; + } $scope.seek = function (position) { if ($scope.mediaPlayer && $scope.mediaPlayer.player) { - $scope.mediaPlayer.player.seek(position); + $scope.mediaPlayer.player.seek(position) } else { - $scope.togglePlay(); + $scope.togglePlay() } - }; + } $scope.setVolume = function (volume) { - audioVolume = volume; - Storage.set({audio_volume: volume}); + audioVolume = volume + Storage.set({audio_volume: volume}) if ($scope.mediaPlayer && $scope.mediaPlayer.player) { - $scope.mediaPlayer.player.setVolume(volume); + $scope.mediaPlayer.player.setVolume(volume) } - }; + } } }) @@ -3099,266 +3007,258 @@ angular.module('myApp.directives', ['myApp.filters']) return { link: link, templateUrl: templateUrl('slider') - }; + } function link ($scope, element, attrs) { - var wrap = $('.tg_slider_wrap', element); - var fill = $('.tg_slider_track_fill', element); - var thumb = $('.tg_slider_thumb', element); - var width = wrap.width(); - var thumbWidth = Math.ceil(thumb.width()); - var model = attrs.sliderModel; - var sliderCallback = attrs.sliderOnchange; - var minValue = 0.0; - var maxValue = 1.0; - var lastUpdValue = false; - var lastMinPageX = false; + var wrap = $('.tg_slider_wrap', element) + var fill = $('.tg_slider_track_fill', element) + var thumb = $('.tg_slider_thumb', element) + var width = wrap.width() + var thumbWidth = Math.ceil(thumb.width()) + var model = attrs.sliderModel + var sliderCallback = attrs.sliderOnchange + var minValue = 0.0 + var maxValue = 1.0 + var lastUpdValue = false + var lastMinPageX = false if (attrs.sliderMin) { $scope.$watch(attrs.sliderMin, function (newMinValue) { - minValue = newMinValue || 0.0; - }); + minValue = newMinValue || 0.0 + }) } if (attrs.sliderMax) { $scope.$watch(attrs.sliderMax, function (newMaxValue) { - maxValue = newMaxValue || 1.0; - }); + maxValue = newMaxValue || 1.0 + }) } var onSliderMove = function (e) { - e = e.originalEvent || e; + e = e.originalEvent || e - var offsetX = (e.touches && e.touches[0] ? e.touches[0].pageX : e.pageX) - lastMinPageX; - offsetX = Math.min(width, Math.max(0 , offsetX)); - // console.log(e.type, lastMinPageX, e.pageX, offsetX); - lastUpdValue = minValue + offsetX / width * (maxValue - minValue); + var offsetX = (e.touches && e.touches[0] ? e.touches[0].pageX : e.pageX) - lastMinPageX + offsetX = Math.min(width, Math.max(0 , offsetX)) + // console.log(e.type, lastMinPageX, e.pageX, offsetX) + lastUpdValue = minValue + offsetX / width * (maxValue - minValue) if (sliderCallback) { - $scope.$eval(sliderCallback, {value: lastUpdValue}); + $scope.$eval(sliderCallback, {value: lastUpdValue}) } else { - $scope.$eval(model + '=' + lastUpdValue); + $scope.$eval(model + '=' + lastUpdValue) } - thumb.css('left', Math.max(0, offsetX - thumbWidth)); - fill.css('width', offsetX); + thumb.css('left', Math.max(0, offsetX - thumbWidth)) + fill.css('width', offsetX) - return cancelEvent(e); - }; + return cancelEvent(e) + } var stopSliderTrack = function () { - $($window).off('mousemove touchmove', onSliderMove); - $($window).off('mouseup touchend touchcancel touchleave', stopSliderTrack); - }; + $($window).off('mousemove touchmove', onSliderMove) + $($window).off('mouseup touchend touchcancel touchleave', stopSliderTrack) + } $scope.$watch(model, function (newVal) { if (newVal != lastUpdValue && newVal !== undefined) { - var percent = Math.max(0, (newVal - minValue) / (maxValue - minValue)); + var percent = Math.max(0, (newVal - minValue) / (maxValue - minValue)) if (width) { - var offsetX = Math.ceil(width * percent); - offsetX = Math.min(width, Math.max(0 , offsetX)); - thumb.css('left', Math.max(0, offsetX - thumbWidth)); - fill.css('width', offsetX); + var offsetX = Math.ceil(width * percent) + offsetX = Math.min(width, Math.max(0 , offsetX)) + thumb.css('left', Math.max(0, offsetX - thumbWidth)) + fill.css('width', offsetX) } else { - thumb.css('left', percent * 100 + '%'); - fill.css('width', percent * 100 + '%'); + thumb.css('left', percent * 100 + '%') + fill.css('width', percent * 100 + '%') } - lastUpdValue = false; + lastUpdValue = false } - }); + }) - element.on('dragstart selectstart', cancelEvent); + element.on('dragstart selectstart', cancelEvent) element.on('mousedown touchstart', function (e) { if (!width) { - width = wrap.width(); + width = wrap.width() if (!width) { - console.error('empty width'); - return cancelEvent(e); + console.error('empty width') + return cancelEvent(e) } } - stopSliderTrack(); + stopSliderTrack() - e = e.originalEvent || e; + e = e.originalEvent || e - var offsetX; + var offsetX if (e.touches && e.touches[0]) { - lastMinPageX = element.position().left; - offsetX = e.touches[0].pageX - lastMinPageX; + lastMinPageX = element.position().left + offsetX = e.touches[0].pageX - lastMinPageX } else if (e.offsetX !== undefined) { - offsetX = e.offsetX; - lastMinPageX = e.pageX - offsetX; + offsetX = e.offsetX + lastMinPageX = e.pageX - offsetX } else if (e.layerX !== undefined) { - offsetX = e.layerX; - lastMinPageX = e.pageX - offsetX; - } - else { - return cancelEvent(e); + offsetX = e.layerX + lastMinPageX = e.pageX - offsetX + }else { + return cancelEvent(e) } - // console.log(e.type, e, lastMinPageX, e.pageX, offsetX); - lastUpdValue = minValue + offsetX / width * (maxValue - minValue); + // console.log(e.type, e, lastMinPageX, e.pageX, offsetX) + lastUpdValue = minValue + offsetX / width * (maxValue - minValue) if (sliderCallback) { - $scope.$eval(sliderCallback, {value: lastUpdValue}); + $scope.$eval(sliderCallback, {value: lastUpdValue}) } else { - $scope.$eval(model + '=' + lastUpdValue); + $scope.$eval(model + '=' + lastUpdValue) } - thumb.css('left', Math.max(0, offsetX - thumbWidth)); - fill.css('width', offsetX); + thumb.css('left', Math.max(0, offsetX - thumbWidth)) + fill.css('width', offsetX) - $($window).on('mousemove touchmove', onSliderMove); - $($window).on('mouseup touchend touchcancel touchleave', stopSliderTrack); + $($window).on('mousemove touchmove', onSliderMove) + $($window).on('mouseup touchend touchcancel touchleave', stopSliderTrack) - return cancelEvent(e); - }); + return cancelEvent(e) + }) } - }) .directive('myLabeledInput', function () { - return { link: link - }; + } - function link($scope, element, attrs) { - var input = $('.md-input:first', element); - var label = $('.md-input-label:first', element); - var isDisabled = input[0] && input[0].tagName == 'SPAN'; - var focused = false; + function link ($scope, element, attrs) { + var input = $('.md-input:first', element) + var label = $('.md-input-label:first', element) + var isDisabled = input[0] && input[0].tagName == 'SPAN' + var focused = false var updateHasValueClass = function () { if (isDisabled) { - element.toggleClass('md-input-has-value', input.html().length > 0); + element.toggleClass('md-input-has-value', input.html().length > 0) } else { - element.toggleClass('md-input-has-value', focused || input.val().length > 0); + element.toggleClass('md-input-has-value', focused || input.val().length > 0) } - }; + } - updateHasValueClass(); + updateHasValueClass() onContentLoaded(function () { - updateHasValueClass(); + updateHasValueClass() setZeroTimeout(function () { - element.addClass('md-input-animated'); - }); - }); + element.addClass('md-input-animated') + }) + }) if (!isDisabled) { input.on('blur focus change', function (e) { - focused = e.type == 'focus'; - element.toggleClass('md-input-focused', focused); - updateHasValueClass(); - }); + focused = e.type == 'focus' + element.toggleClass('md-input-focused', focused) + updateHasValueClass() + }) } $scope.$on('value_updated', function () { setZeroTimeout(function () { - updateHasValueClass(); - }); - }); - }; + updateHasValueClass() + }) + }) + } }) .directive('myCopyField', function (toaster, _) { - return { scope: { selectEvent: '=myCopyField' }, link: link - }; + } - function link($scope, element, attrs) { - element.attr('readonly', 'true'); - element[0].readonly = true; + function link ($scope, element, attrs) { + element.attr('readonly', 'true') + element[0].readonly = true element.on('click', function () { - this.select(); - }); + this.select() + }) if ($scope.selectEvent) { $scope.$on($scope.selectEvent, function () { setTimeout(function () { - element[0].focus(); - element[0].select(); - }, 100); - }); + element[0].focus() + element[0].select() + }, 100) + }) } - }; - + } }) .directive('myCopyLink', function ($compile, $timeout, _) { - return { restrict: 'A', replace: false, terminal: true, priority: 1000, link: link - }; + } function link ($scope, element, attrs) { - element.attr('tooltip', '{{ttLabel}}'); - element.removeAttr('my-copy-link'); - element.removeAttr('data-my-copy-link'); + element.attr('tooltip', '{{ttLabel}}') + element.removeAttr('my-copy-link') + element.removeAttr('data-my-copy-link') - var resetPromise = false; + var resetPromise = false var resetTooltip = function () { - $timeout.cancel(resetPromise); - resetPromise = false; - $scope.ttLabel = _('conversations_modal_share_url_copy_raw'); - }; + $timeout.cancel(resetPromise) + resetPromise = false + $scope.ttLabel = _('conversations_modal_share_url_copy_raw') + } - resetTooltip(); + resetTooltip() - $compile(element)($scope); + $compile(element)($scope) - var clipboard = new Clipboard(element[0]); + var clipboard = new Clipboard(element[0]) - clipboard.on('success', function(e) { - $timeout.cancel(resetPromise); + clipboard.on('success', function (e) { + $timeout.cancel(resetPromise) $scope.$apply(function () { - $scope.ttLabel = _('clipboard_copied_raw'); - }); - resetPromise = $timeout(resetTooltip, 2000); - }); + $scope.ttLabel = _('clipboard_copied_raw') + }) + resetPromise = $timeout(resetTooltip, 2000) + }) - clipboard.on('error', function(e) { - $timeout.cancel(resetPromise); + clipboard.on('error', function (e) { + $timeout.cancel(resetPromise) var langKey = Config.Navigator.osX ? 'clipboard_press_cmd_c' - : 'clipboard_press_ctrl_c'; + : 'clipboard_press_ctrl_c' $scope.$apply(function () { - $scope.ttLabel = _(langKey + '_raw'); - }); - resetPromise = $timeout(resetTooltip, 5000); - }); + $scope.ttLabel = _(langKey + '_raw') + }) + resetPromise = $timeout(resetTooltip, 5000) + }) $scope.$on('$destroy', function () { - clipboard.destroy(); - }); + clipboard.destroy() + }) } - }) .directive('mySubmitOnEnter', function () { - return { link: link - }; + } - function link($scope, element, attrs) { + function link ($scope, element, attrs) { element.on('keydown', function (event) { if (event.keyCode == 13) { - element.trigger('submit'); - return cancelEvent(event); + element.trigger('submit') + return cancelEvent(event) } - }); - }; + }) + } }) .directive('myArcProgress', function () { var html = -'\ + '\ \ \ \ @@ -3367,314 +3267,307 @@ angular.module('myApp.directives', ['myApp.filters']) \ \ \ -'; +' function updateProgress (bar, progress, fullLen) { - progress = Math.max(0.0, Math.min(progress, 1.0)); - var minProgress = 0.2; - progress = minProgress + (1 - minProgress) * progress; - bar.css({strokeDasharray: (progress * fullLen) + ', ' + ((1 - progress) * fullLen)}); + progress = Math.max(0.0, Math.min(progress, 1.0)) + var minProgress = 0.2 + progress = minProgress + (1 - minProgress) * progress + bar.css({strokeDasharray: (progress * fullLen) + ', ' + ((1 - progress) * fullLen)}) } - var num = 0; + var num = 0 return { scope: { progress: '=myArcProgress' }, - link: function ($scope, element, attrs) { - var intermediate = !attrs.myArcProgress; - var width = attrs.width || element.width() || 40; - var stroke = attrs.stroke || (width / 2 * 0.14); - var center = width / 2; - var radius = center - (stroke / 2); + link: function ($scope, element, attrs) { + var intermediate = !attrs.myArcProgress + var width = attrs.width || element.width() || 40 + var stroke = attrs.stroke || (width / 2 * 0.14) + var center = width / 2 + var radius = center - (stroke / 2) // Doesn't work without unique id for every gradient - var curNum = ++num; + var curNum = ++num element .html(html.replace('%id%', curNum)) .addClass('progress-arc-wrap') .addClass(intermediate ? 'progress-arc-intermediate' : 'progress-arc-percent') - .css({width: width, height: width}); + .css({width: width, height: width}) $(element[0].firstChild) .attr('width', width) - .attr('height', width); + .attr('height', width) - var bar = $('.progress-arc-bar', element); + var bar = $('.progress-arc-bar', element) bar .attr('cx', center) .attr('cy', center) .attr('r', radius) - .css({strokeWidth: stroke}); + .css({strokeWidth: stroke}) - var fullLen = 2 * Math.PI * radius; + var fullLen = 2 * Math.PI * radius if (intermediate) { - updateProgress(bar, 0.3, fullLen); - bar.css({stroke: 'url(#grad_intermediate' + curNum + ')'}); + updateProgress(bar, 0.3, fullLen) + bar.css({stroke: 'url(#grad_intermediate' + curNum + ')'}) } else { $scope.$watch('progress', function (newProgress) { - updateProgress(bar, newProgress / 100.0, fullLen); - }); + updateProgress(bar, newProgress / 100.0, fullLen) + }) } } } }) .directive('myScrollToOn', function () { - return { - link: function($scope, element, attrs) { - var ev = attrs.myScrollToOn; + link: function ($scope, element, attrs) { + var ev = attrs.myScrollToOn var doScroll = function () { onContentLoaded(function () { $('html, body').animate({ scrollTop: element.offset().top - }, 200); - }); - }; + }, 200) + }) + } if (ev == '$init') { - doScroll(); + doScroll() } else { - $scope.$on(ev, doScroll); + $scope.$on(ev, doScroll) } } - }; - + } }) .directive('myComposerDropdown', function () { - return { templateUrl: templateUrl('composer_dropdown') } }) .directive('myEmojiSuggestions', function () { - return { - link: function($scope, element, attrs) { + link: function ($scope, element, attrs) { $scope.$watchCollection('emojiCodes', function (codes) { - // var codes = $scope.$eval(attrs.myEmojiSuggestions); - var html = []; - var iconSize = Config.Mobile ? 26 : 20; + // var codes = $scope.$eval(attrs.myEmojiSuggestions) + var html = [] + var iconSize = Config.Mobile ? 26 : 20 - var emoticonCode, emoticonData, spritesheet, pos, categoryIndex; - var count = Math.min(5, codes.length); - var i, x, y; + var emoticonCode, emoticonData + var spritesheet, pos + var categoryIndex + var count = Math.min(5, codes.length) + var i, x + var y for (i = 0; i < count; i++) { - emoticonCode = codes[i]; + emoticonCode = codes[i] if (emoticonCode.code) { - emoticonCode = emoticonCode.code; + emoticonCode = emoticonCode.code } if (emoticonData = Config.Emoji[emoticonCode]) { - spritesheet = EmojiHelper.spritesheetPositions[emoticonCode]; - categoryIndex = spritesheet[0]; - pos = spritesheet[1]; - x = iconSize * spritesheet[3]; - y = iconSize * spritesheet[2]; - html.push('
  • :' + encodeEntities(emoticonData[1][0]) + ':
  • '); + spritesheet = EmojiHelper.spritesheetPositions[emoticonCode] + categoryIndex = spritesheet[0] + pos = spritesheet[1] + x = iconSize * spritesheet[3] + y = iconSize * spritesheet[2] + html.push('
  • :' + encodeEntities(emoticonData[1][0]) + ':
  • ') } } // onContentLoaded(function () { - element.html(html.join('')); - console.log(dT(), 'emoji done'); - // }); - }); + element.html(html.join('')) + console.log(dT(), 'emoji done') + // }) + }) } - }; - + } }) .directive('myInlineResults', function (AppPhotosManager, ExternalResourcesManager, AppDocsManager) { - return { templateUrl: templateUrl('inline_results'), scope: { botResults: '=myInlineResults' }, - link: function ($scope, element, attrs) { + link: function ($scope, element, attrs) { $scope.$watch('botResults.results', function (results) { angular.forEach(results, function (result) { if (result.thumb_url && !result.thumbUrl) { ExternalResourcesManager.downloadByURL(result.thumb_url).then(function (url) { - result.thumbUrl = url; - }); + result.thumbUrl = url + }) } if (result.type == 'gif' && result.content_url && !result.contentUrl) { ExternalResourcesManager.downloadByURL(result.content_url).then(function (url) { - result.contentUrl = url; - }); + result.contentUrl = url + }) } if ((result.type == 'gif' || result.type == 'sticker') && result.document) { - AppDocsManager.downloadDoc(result.document.id); + AppDocsManager.downloadDoc(result.document.id) } if (result.type == 'photo' && result.photo) { - var photoSize = AppPhotosManager.choosePhotoSize(result.photo, result.thumbW, result.thumbH), - dim = calcImageInBox(photoSize.w, photoSize.h, result.thumbW, result.thumbH); + var photoSize = AppPhotosManager.choosePhotoSize(result.photo, result.thumbW, result.thumbH) + var dim = calcImageInBox(photoSize.w, photoSize.h, result.thumbW, result.thumbH) result.thumb = { width: dim.w, height: dim.h, location: photoSize.location, size: photoSize.size - }; + } } }) - }); + }) } } }) - .directive('myExternalEmbed', function () { - - var twitterAttached = false; - var facebookAttached = false; - var gplusAttached = false; - var twitterPendingWidgets = []; - var facebookPendingWidgets = []; - var embedTag = Config.Modes.chrome_packed ? 'webview' : 'iframe'; + var twitterAttached = false + var facebookAttached = false + var gplusAttached = false + var twitterPendingWidgets = [] + var facebookPendingWidgets = [] + var embedTag = Config.Modes.chrome_packed ? 'webview' : 'iframe' function link ($scope, element, attrs) { - var embedData = $scope.$eval(attrs.myExternalEmbed); + var embedData = $scope.$eval(attrs.myExternalEmbed) if (!embedData) { - return; + return } - var html = ''; - var callback = false; - var needTwitter = false; + var html = '' + var callback = false + var needTwitter = false switch (embedData[0]) { case 'youtube': - var videoID = embedData[1]; + var videoID = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" ' + - 'src="https://www.youtube.com/embed/' + videoID + - '?autoplay=0&controls=2" webkitallowfullscreen mozallowfullscreen allowfullscreen>
    '; - break; + 'src="https://www.youtube.com/embed/' + videoID + + '?autoplay=0&controls=2" webkitallowfullscreen mozallowfullscreen allowfullscreen>' + break case 'vimeo': - var videoID = embedData[1]; + var videoID = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" ' + - 'src="https://player.vimeo.com/video/' + videoID + - '?title=0&byline=0&portrait=0" webkitallowfullscreen mozallowfullscreen allowfullscreen>
    '; - break; + 'src="https://player.vimeo.com/video/' + videoID + + '?title=0&byline=0&portrait=0" webkitallowfullscreen mozallowfullscreen allowfullscreen>' + break case 'instagram': - var instaID = embedData[1]; + var instaID = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" ' + - 'src="https://instagram.com/p/' + instaID + - '/embed/">
    '; - break; + 'src="https://instagram.com/p/' + instaID + + '/embed/">' + break case 'vine': - var vineID = embedData[1]; + var vineID = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" ' + - 'src="https://vine.co/v/' + vineID + '/embed/simple">
    '; - break; + 'src="https://vine.co/v/' + vineID + '/embed/simple">' + break case 'soundcloud': - var soundcloudUrl = embedData[1]; + var soundcloudUrl = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" ' + - 'src="https://w.soundcloud.com/player/?url=' + encodeEntities(encodeURIComponent(soundcloudUrl)) + - '&auto_play=false&hide_related=true&show_comments=false&show_user=true&show_reposts=false&visual=true">
    '; - break; + 'src="https://w.soundcloud.com/player/?url=' + encodeEntities(encodeURIComponent(soundcloudUrl)) + + '&auto_play=false&hide_related=true&show_comments=false&show_user=true&show_reposts=false&visual=true">' + break case 'spotify': - var spotifyUrl = embedData[1]; + var spotifyUrl = embedData[1] html = '
    <' + embedTag + ' type="text/html" frameborder="0" allowtransparency="true" ' + - 'src="https://embed.spotify.com/?uri=spotify:' + encodeEntities(encodeURIComponent(spotifyUrl)) + - '">
    '; - break; + 'src="https://embed.spotify.com/?uri=spotify:' + encodeEntities(encodeURIComponent(spotifyUrl)) + + '">' + break case 'twitter': - html = '
    '; + html = '
    ' callback = function () { if (!twitterAttached) { - twitterAttached = true; + twitterAttached = true $('