Browse Source

Refactor updates switch to map

master
Eduard Kuzmenko 4 years ago
parent
commit
06c6a84443
  1. 2
      src/config/database.ts
  2. 8
      src/helpers/eventListenerBase.ts
  3. 21
      src/lib/appManagers/apiUpdatesManager.ts
  4. 49
      src/lib/appManagers/appChatsManager.ts
  5. 17
      src/lib/appManagers/appDialogsManager.ts
  6. 8
      src/lib/appManagers/appDraftsManager.ts
  7. 212
      src/lib/appManagers/appMessagesManager.ts
  8. 10
      src/lib/appManagers/appNotificationsManager.ts
  9. 9
      src/lib/appManagers/appPeersManager.ts
  10. 24
      src/lib/appManagers/appPollsManager.ts
  11. 8
      src/lib/appManagers/appPrivacyManager.ts
  12. 20
      src/lib/appManagers/appProfileManager.ts
  13. 11
      src/lib/appManagers/appStickersManager.ts
  14. 45
      src/lib/appManagers/appUsersManager.ts
  15. 8
      src/lib/appManagers/appWebPagesManager.ts
  16. 10
      src/lib/cacheStorage.ts
  17. 9
      src/lib/rootScope.ts
  18. 2
      src/lib/storage.ts
  19. 57
      src/lib/storages/filters.ts

2
src/config/database.ts

@ -7,7 +7,7 @@
import { IDBStore } from "../lib/idb"; import { IDBStore } from "../lib/idb";
import Modes from "./modes"; import Modes from "./modes";
export type DatabaseStoreName = 'session' | 'stickerSets'; export type DatabaseStoreName = 'session' | 'stickerSets' | 'users' | 'chats' | 'messages' | 'dialogs';
export type DatabaseStore = Omit<IDBStore, 'name'> & {name: DatabaseStoreName}; export type DatabaseStore = Omit<IDBStore, 'name'> & {name: DatabaseStoreName};
const Database = { const Database = {
name: 'tweb' + (Modes.test ? '_test' : ''), name: 'tweb' + (Modes.test ? '_test' : ''),

8
src/helpers/eventListenerBase.ts

@ -86,6 +86,14 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi
//e.add(this, name, {callback, once}); //e.add(this, name, {callback, once});
} }
public addMultipleEventsListeners(obj: {
[name in keyof Listeners]?: Listeners[name]
}) {
for(const i in obj) {
this.addEventListener(i, obj[i]);
}
}
public removeEventListener(name: keyof Listeners, callback: Listeners[typeof name]) { public removeEventListener(name: keyof Listeners, callback: Listeners[typeof name]) {
if(this.listeners[name]) { if(this.listeners[name]) {
this.listeners[name].findAndSplice(l => l.callback === callback); this.listeners[name].findAndSplice(l => l.callback === callback);

21
src/lib/appManagers/apiUpdatesManager.ts

@ -12,6 +12,7 @@
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import DEBUG, { MOUNT_CLASS_TO } from '../../config/debug'; import DEBUG, { MOUNT_CLASS_TO } from '../../config/debug';
import { copy } from '../../helpers/object'; import { copy } from '../../helpers/object';
import { Update } from '../../layer';
import { logger, LogLevels } from '../logger'; import { logger, LogLevels } from '../logger';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import rootScope from '../rootScope'; import rootScope from '../rootScope';
@ -53,7 +54,7 @@ export class ApiUpdatesManager {
private log = logger('UPDATES', LogLevels.error | LogLevels.log | LogLevels.warn | LogLevels.debug); private log = logger('UPDATES', LogLevels.error | LogLevels.log | LogLevels.warn | LogLevels.debug);
private debug = DEBUG; private debug = DEBUG;
public popPendingSeqUpdate() { private popPendingSeqUpdate() {
const state = this.updatesState; const state = this.updatesState;
const nextSeq = state.seq + 1; const nextSeq = state.seq + 1;
const pendingUpdatesData = state.pendingSeqUpdates[nextSeq]; const pendingUpdatesData = state.pendingSeqUpdates[nextSeq];
@ -87,7 +88,7 @@ export class ApiUpdatesManager {
return true; return true;
} }
public popPendingPtsUpdate(channelId: number) { private popPendingPtsUpdate(channelId: number) {
const curState = channelId ? this.getChannelState(channelId) : this.updatesState; const curState = channelId ? this.getChannelState(channelId) : this.updatesState;
if(!curState.pendingPtsUpdates.length) { if(!curState.pendingPtsUpdates.length) {
return false; return false;
@ -119,6 +120,8 @@ export class ApiUpdatesManager {
curState.pts = goodPts; curState.pts = goodPts;
for(let i = 0; i <= goodIndex; ++i) { for(let i = 0; i <= goodIndex; ++i) {
const update = curState.pendingPtsUpdates[i]; const update = curState.pendingPtsUpdates[i];
// @ts-ignore
this.saveUpdate(update); this.saveUpdate(update);
} }
curState.pendingPtsUpdates.splice(0, goodIndex + 1); curState.pendingPtsUpdates.splice(0, goodIndex + 1);
@ -208,7 +211,7 @@ export class ApiUpdatesManager {
} }
}; };
public getDifference(first = false): Promise<void> { private getDifference(first = false): Promise<void> {
// this.trace('Get full diff') // this.trace('Get full diff')
const updatesState = this.updatesState; const updatesState = this.updatesState;
let wasSyncing = updatesState.syncLoading; let wasSyncing = updatesState.syncLoading;
@ -298,7 +301,7 @@ export class ApiUpdatesManager {
return promise; return promise;
} }
public getChannelDifference(channelId: number): Promise<void> { private getChannelDifference(channelId: number): Promise<void> {
const channelState = this.getChannelState(channelId); const channelState = this.getChannelState(channelId);
const wasSyncing = channelState.syncLoading; const wasSyncing = channelState.syncLoading;
if(!wasSyncing) { if(!wasSyncing) {
@ -328,6 +331,8 @@ export class ApiUpdatesManager {
if(differenceResult._ === 'updates.channelDifferenceTooLong') { if(differenceResult._ === 'updates.channelDifferenceTooLong') {
this.debug && this.log('channel diff too long', differenceResult); this.debug && this.log('channel diff too long', differenceResult);
delete this.channelStates[channelId]; delete this.channelStates[channelId];
// @ts-ignore
this.saveUpdate({_: 'updateChannelReload', channel_id: channelId}); this.saveUpdate({_: 'updateChannelReload', channel_id: channelId});
return; return;
} }
@ -399,7 +404,7 @@ export class ApiUpdatesManager {
return false; return false;
} }
public getChannelState(channelId: number, pts?: number) { private getChannelState(channelId: number, pts?: number) {
if(this.channelStates[channelId] === undefined) { if(this.channelStates[channelId] === undefined) {
this.addChannelState(channelId, pts); this.addChannelState(channelId, pts);
} }
@ -407,7 +412,7 @@ export class ApiUpdatesManager {
return this.channelStates[channelId]; return this.channelStates[channelId];
} }
public processUpdate(update: any, options: Partial<{ private processUpdate(update: any, options: Partial<{
date: number, date: number,
seq: number, seq: number,
seqStart: number/* , seqStart: number/* ,
@ -570,8 +575,8 @@ export class ApiUpdatesManager {
} }
} }
public saveUpdate(update: any) { public saveUpdate(update: Update) {
rootScope.broadcast('apiUpdate', update); rootScope.dispatchEvent(update._, update as any);
} }
public attach() { public attach() {

49
src/lib/appManagers/appChatsManager.ts

@ -12,7 +12,7 @@
import { MOUNT_CLASS_TO } from "../../config/debug"; import { MOUNT_CLASS_TO } from "../../config/debug";
import { numberThousandSplitter } from "../../helpers/number"; import { numberThousandSplitter } from "../../helpers/number";
import { isObject, safeReplaceObject, copy, deepEqual } from "../../helpers/object"; import { isObject, safeReplaceObject, copy, deepEqual } from "../../helpers/object";
import { ChannelParticipant, Chat, ChatAdminRights, ChatBannedRights, ChatFull, ChatParticipant, ChatParticipants, ChatPhoto, InputChannel, InputChatPhoto, InputFile, InputPeer, SendMessageAction, Update, Updates } from "../../layer"; import { ChannelParticipant, Chat, ChatAdminRights, ChatBannedRights, ChatFull, ChatParticipants, InputChannel, InputChatPhoto, InputFile, InputPeer, SendMessageAction, Update, Updates } from "../../layer";
import { i18n, LangPackKey } from "../langPack"; import { i18n, LangPackKey } from "../langPack";
import apiManagerProxy from "../mtproto/mtprotoworker"; import apiManagerProxy from "../mtproto/mtprotoworker";
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
@ -42,40 +42,42 @@ export class AppChatsManager {
public typingsInPeer: {[peerId: number]: UserTyping[]} = {}; public typingsInPeer: {[peerId: number]: UserTyping[]} = {};
constructor() { constructor() {
rootScope.on('apiUpdate', (update) => { rootScope.addMultipleEventsListeners({
// console.log('on apiUpdate', update) updateChannel: (update) => {
switch(update._) {
case 'updateChannel': {
const channelId = update.channel_id; const channelId = update.channel_id;
//console.log('updateChannel:', update); //console.log('updateChannel:', update);
rootScope.broadcast('channel_settings', {channelId}); rootScope.broadcast('channel_settings', {channelId});
break; },
}
case 'updateChannelParticipant': { updateChannelParticipant: (update) => {
apiManagerProxy.clearCache('channels.getParticipants', (params) => { apiManagerProxy.clearCache('channels.getParticipants', (params) => {
return (params.channel as InputChannel.inputChannel).channel_id === update.channel_id; return (params.channel as InputChannel.inputChannel).channel_id === update.channel_id;
}); });
break; },
}
case 'updateChatDefaultBannedRights': { updateChatDefaultBannedRights: (update) => {
const chatId = -appPeersManager.getPeerId(update.peer); const chatId = -appPeersManager.getPeerId(update.peer);
const chat: Chat = this.getChat(chatId); const chat: Chat = this.getChat(chatId);
if(chat._ !== 'chatEmpty') { if(chat._ !== 'chatEmpty') {
(chat as Chat.chat).default_banned_rights = update.default_banned_rights; (chat as Chat.chat).default_banned_rights = update.default_banned_rights;
rootScope.broadcast('chat_update', chatId); rootScope.broadcast('chat_update', chatId);
} }
},
break; updateUserTyping: this.onUpdateUserTyping,
updateChatUserTyping: this.onUpdateUserTyping,
updateChannelUserTyping: this.onUpdateUserTyping
});
appStateManager.getState().then((state) => {
this.chats = state.chats;
});
} }
case 'updateUserTyping': private onUpdateUserTyping = (update: Update.updateUserTyping | Update.updateChatUserTyping | Update.updateChannelUserTyping) => {
case 'updateChatUserTyping':
case 'updateChannelUserTyping': {
const fromId = (update as Update.updateUserTyping).user_id || appPeersManager.getPeerId((update as Update.updateChatUserTyping).from_id); const fromId = (update as Update.updateUserTyping).user_id || appPeersManager.getPeerId((update as Update.updateChatUserTyping).from_id);
if(rootScope.myId === fromId || update.action._ === 'speakingInGroupCallAction') { if(rootScope.myId === fromId || update.action._ === 'speakingInGroupCallAction') {
break; return;
} }
const peerId = update._ === 'updateUserTyping' ? const peerId = update._ === 'updateUserTyping' ?
@ -105,11 +107,11 @@ export class AppChatsManager {
if(update.action._ === 'sendMessageCancelAction') { if(update.action._ === 'sendMessageCancelAction') {
if(!typing) { if(!typing) {
break; return;
} }
cancelAction(); cancelAction();
break; return;
} else { } else {
if(!typing) { if(!typing) {
typing = { typing = {
@ -138,16 +140,7 @@ export class AppChatsManager {
typing.timeout = window.setTimeout(cancelAction, 6000); typing.timeout = window.setTimeout(cancelAction, 6000);
rootScope.broadcast('peer_typings', {peerId, typings}); rootScope.broadcast('peer_typings', {peerId, typings});
} }
};
break;
}
}
});
appStateManager.getState().then((state) => {
this.chats = state.chats;
});
}
public saveApiChats(apiChats: any[]) { public saveApiChats(apiChats: any[]) {
apiChats.forEach(chat => this.saveApiChat(chat)); apiChats.forEach(chat => this.saveApiChat(chat));

17
src/lib/appManagers/appDialogsManager.ts

@ -22,7 +22,7 @@ import appMessagesManager, { Dialog } from "./appMessagesManager";
import {MyDialogFilter as DialogFilter} from "../storages/filters"; import {MyDialogFilter as DialogFilter} from "../storages/filters";
import appPeersManager from './appPeersManager'; import appPeersManager from './appPeersManager';
import appStateManager from "./appStateManager"; import appStateManager from "./appStateManager";
import appUsersManager, { User } from "./appUsersManager"; import appUsersManager from "./appUsersManager";
import Button from "../../components/button"; import Button from "../../components/button";
import SetTransition from "../../components/singleTransition"; import SetTransition from "../../components/singleTransition";
import sessionStorage from '../sessionStorage'; import sessionStorage from '../sessionStorage';
@ -32,11 +32,9 @@ import ProgressivePreloader from "../../components/preloader";
import App from "../../config/app"; import App from "../../config/app";
import DEBUG, { MOUNT_CLASS_TO } from "../../config/debug"; import DEBUG, { MOUNT_CLASS_TO } from "../../config/debug";
import appNotificationsManager from "./appNotificationsManager"; import appNotificationsManager from "./appNotificationsManager";
import { InputNotifyPeer } from "../../layer";
import PeerTitle from "../../components/peerTitle"; import PeerTitle from "../../components/peerTitle";
import { i18n } from "../langPack"; import { i18n } from "../langPack";
import findUpTag from "../../helpers/dom/findUpTag"; import findUpTag from "../../helpers/dom/findUpTag";
import appChatsManager from "./appChatsManager";
export type DialogDom = { export type DialogDom = {
avatarEl: AvatarElement, avatarEl: AvatarElement,
@ -301,20 +299,15 @@ export class AppDialogsManager {
(window as any).addElement = add; (window as any).addElement = add;
} */ } */
rootScope.on('user_update', (e) => { rootScope.on('user_update', (userId) => {
const userId = e;
const user = appUsersManager.getUser(userId);
const dialog = appMessagesManager.getDialogByPeerId(user.id)[0];
//console.log('updating user:', user, dialog); //console.log('updating user:', user, dialog);
if(dialog && !appUsersManager.isBot(dialog.peerId) && dialog.peerId !== rootScope.myId) { const dom = this.getDialogDom(userId);
if(dom && !appUsersManager.isBot(userId) && userId !== rootScope.myId) {
const user = appUsersManager.getUser(userId);
const online = user.status?._ === 'userStatusOnline'; const online = user.status?._ === 'userStatusOnline';
const dom = this.getDialogDom(dialog.peerId);
if(dom) {
dom.avatarEl.classList.toggle('is-online', online); dom.avatarEl.classList.toggle('is-online', online);
} }
}
}); });
/* rootScope.$on('dialog_top', (e) => { /* rootScope.$on('dialog_top', (e) => {

8
src/lib/appManagers/appDraftsManager.ts

@ -38,13 +38,11 @@ export class AppDraftsManager {
}); });
}); });
rootScope.on('apiUpdate', (update) => { rootScope.addMultipleEventsListeners({
if(update._ !== 'updateDraftMessage') { updateDraftMessage: (update) => {
return
}
const peerID = appPeersManager.getPeerId(update.peer); const peerID = appPeersManager.getPeerId(update.peer);
this.saveDraft(peerID, (update as any).threadId, update.draft, {notify: true}); this.saveDraft(peerID, (update as any).threadId, update.draft, {notify: true});
}
}); });
} }

212
src/lib/appManagers/appMessagesManager.ts

@ -174,7 +174,7 @@ export class AppMessagesManager {
public newMessagesToHandle: {[peerId: string]: Set<number>} = {}; public newMessagesToHandle: {[peerId: string]: Set<number>} = {};
public newDialogsHandlePromise = 0; public newDialogsHandlePromise = 0;
public newDialogsToHandle: {[peerId: string]: {reload: true} | Dialog} = {}; public newDialogsToHandle: {[peerId: string]: {reload: true} | Dialog} = {};
public newUpdatesAfterReloadToHandle: {[peerId: string]: Set<any>} = {}; public newUpdatesAfterReloadToHandle: {[peerId: string]: Set<Update>} = {};
private notificationsHandlePromise = 0; private notificationsHandlePromise = 0;
private notificationsToHandle: {[peerId: string]: { private notificationsToHandle: {[peerId: string]: {
@ -207,10 +207,58 @@ export class AppMessagesManager {
constructor() { constructor() {
this.dialogsStorage = new DialogsStorage(this, appChatsManager, appPeersManager, serverTimeManager); this.dialogsStorage = new DialogsStorage(this, appChatsManager, appPeersManager, serverTimeManager);
this.filtersStorage = new FiltersStorage(this, appPeersManager, appUsersManager, appNotificationsManager, /* apiManager, */ rootScope); this.filtersStorage = new FiltersStorage(this, appPeersManager, appUsersManager, appNotificationsManager, apiUpdatesManager, /* apiManager, */ rootScope);
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
this.handleUpdate(e); updateMessageID: this.onUpdateMessageId,
updateNewDiscussionMessage: this.onUpdateNewMessage,
updateNewMessage: this.onUpdateNewMessage,
updateNewChannelMessage: this.onUpdateNewMessage,
updateDialogUnreadMark: this.onUpdateDialogUnreadMark,
updateFolderPeers: this.onUpdateFolderPeers,
updateDialogPinned: this.onUpdateDialogPinned,
updatePinnedDialogs: this.onUpdatePinnedDialogs,
updateEditMessage: this.onUpdateEditMessage,
updateEditChannelMessage: this.onUpdateEditMessage,
updateReadChannelDiscussionInbox: this.onUpdateReadHistory,
updateReadChannelDiscussionOutbox: this.onUpdateReadHistory,
updateReadHistoryInbox: this.onUpdateReadHistory,
updateReadHistoryOutbox: this.onUpdateReadHistory,
updateReadChannelInbox: this.onUpdateReadHistory,
updateReadChannelOutbox: this.onUpdateReadHistory,
updateChannelReadMessagesContents: this.onUpdateReadMessagesContents,
updateReadMessagesContents: this.onUpdateReadMessagesContents,
updateChannelAvailableMessages: this.onUpdateChannelAvailableMessages,
updateDeleteMessages: this.onUpdateDeleteMessages,
updateDeleteChannelMessages: this.onUpdateDeleteMessages,
updateChannel: this.onUpdateChannel,
// @ts-ignore
updateChannelReload: this.onUpdateChannelReload,
updateChannelMessageViews: this.onUpdateChannelMessageViews,
updateServiceNotification: this.onUpdateServiceNotification,
updatePinnedMessages: this.onUpdatePinnedMessages,
updatePinnedChannelMessages: this.onUpdatePinnedMessages,
updateNotifySettings: this.onUpdateNotifySettings,
updateNewScheduledMessage: this.onUpdateNewScheduledMessage,
updateDeleteScheduledMessages: this.onUpdateDeleteScheduledMessages
}); });
// ! Invalidate notify settings, can optimize though // ! Invalidate notify settings, can optimize though
@ -2900,7 +2948,7 @@ export class AppMessagesManager {
}).then(bool => { }).then(bool => {
if(bool) { if(bool) {
const pFlags: Update.updateDialogPinned['pFlags'] = pinned ? {pinned} : {}; const pFlags: Update.updateDialogPinned['pFlags'] = pinned ? {pinned} : {};
this.handleUpdate({ this.onUpdateDialogPinned({
_: 'updateDialogPinned', _: 'updateDialogPinned',
peer: appPeersManager.getDialogPeer(peerId), peer: appPeersManager.getDialogPeer(peerId),
folder_id: filterId, folder_id: filterId,
@ -2921,7 +2969,7 @@ export class AppMessagesManager {
}).then(bool => { }).then(bool => {
if(bool) { if(bool) {
const pFlags: Update.updateDialogUnreadMark['pFlags'] = unread ? {unread} : {}; const pFlags: Update.updateDialogUnreadMark['pFlags'] = unread ? {unread} : {};
this.handleUpdate({ this.onUpdateDialogUnreadMark({
_: 'updateDialogUnreadMark', _: 'updateDialogUnreadMark',
peer: appPeersManager.getDialogPeer(peerId), peer: appPeersManager.getDialogPeer(peerId),
pFlags pFlags
@ -3059,7 +3107,7 @@ export class AppMessagesManager {
if(this.newUpdatesAfterReloadToHandle[peerId] !== undefined) { if(this.newUpdatesAfterReloadToHandle[peerId] !== undefined) {
for(const update of this.newUpdatesAfterReloadToHandle[peerId]) { for(const update of this.newUpdatesAfterReloadToHandle[peerId]) {
this.handleUpdate(update); apiUpdatesManager.saveUpdate(update);
} }
delete this.newUpdatesAfterReloadToHandle[peerId]; delete this.newUpdatesAfterReloadToHandle[peerId];
@ -3927,13 +3975,7 @@ export class AppMessagesManager {
this.notificationsToHandle = {}; this.notificationsToHandle = {};
}; };
public handleUpdate(update: Update) { private onUpdateMessageId = (update: Update.updateMessageID) => {
/* if(DEBUG) {
this.log.debug('handleUpdate', update._, update);
} */
switch(update._) {
case 'updateMessageID': {
const randomId = update.random_id; const randomId = update.random_id;
const pendingData = this.pendingByRandomId[randomId]; const pendingData = this.pendingByRandomId[randomId];
//this.log('AMM updateMessageID:', update, pendingData); //this.log('AMM updateMessageID:', update, pendingData);
@ -3954,13 +3996,9 @@ export class AppMessagesManager {
this.pendingByMessageId[mid] = randomId; this.pendingByMessageId[mid] = randomId;
} }
} }
};
break; private onUpdateNewMessage = (update: Update.updateNewDiscussionMessage | Update.updateNewMessage | Update.updateNewChannelMessage) => {
}
case 'updateNewDiscussionMessage':
case 'updateNewMessage':
case 'updateNewChannelMessage': {
const message = update.message as MyMessage; const message = update.message as MyMessage;
const peerId = this.getMessagePeer(message); const peerId = this.getMessagePeer(message);
const storage = this.getMessagesStorage(peerId); const storage = this.getMessagesStorage(peerId);
@ -3980,7 +4018,7 @@ export class AppMessagesManager {
message message
} as Update.updateNewDiscussionMessage; } as Update.updateNewDiscussionMessage;
this.handleUpdate(update); this.onUpdateNewMessage(update);
} }
if(!foundDialog.length && !isLocalThreadUpdate) { if(!foundDialog.length && !isLocalThreadUpdate) {
@ -4000,7 +4038,7 @@ export class AppMessagesManager {
const set = this.newUpdatesAfterReloadToHandle[peerId] ?? (this.newUpdatesAfterReloadToHandle[peerId] = new Set()); const set = this.newUpdatesAfterReloadToHandle[peerId] ?? (this.newUpdatesAfterReloadToHandle[peerId] = new Set());
if(set.has(update)) { if(set.has(update)) {
this.log.error('here we go again', peerId); this.log.error('here we go again', peerId);
break; return;
} }
this.newDialogsToHandle[peerId] = {reload: true}; this.newDialogsToHandle[peerId] = {reload: true};
@ -4008,13 +4046,13 @@ export class AppMessagesManager {
this.newUpdatesAfterReloadToHandle[peerId].add(update); this.newUpdatesAfterReloadToHandle[peerId].add(update);
} }
break; return;
} }
/* if(update._ === 'updateNewChannelMessage') { /* if(update._ === 'updateNewChannelMessage') {
const chat = appChatsManager.getChat(-peerId); const chat = appChatsManager.getChat(-peerId);
if(chat.pFlags && (chat.pFlags.left || chat.pFlags.kicked)) { if(chat.pFlags && (chat.pFlags.left || chat.pFlags.kicked)) {
break; return;
} }
} */ } */
@ -4070,7 +4108,7 @@ export class AppMessagesManager {
} }
if(isLocalThreadUpdate) { if(isLocalThreadUpdate) {
break; return;
} }
const dialog = foundDialog[0]; const dialog = foundDialog[0];
@ -4107,11 +4145,9 @@ export class AppMessagesManager {
this.notificationsHandlePromise = window.setTimeout(this.handleNotifications, 0); this.notificationsHandlePromise = window.setTimeout(this.handleNotifications, 0);
} }
} }
};
break; private onUpdateDialogUnreadMark = (update: Update.updateDialogUnreadMark) => {
}
case 'updateDialogUnreadMark': {
//this.log('updateDialogUnreadMark', update); //this.log('updateDialogUnreadMark', update);
const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
const foundDialog = this.getDialogByPeerId(peerId); const foundDialog = this.getDialogByPeerId(peerId);
@ -4130,11 +4166,10 @@ export class AppMessagesManager {
rootScope.broadcast('dialogs_multiupdate', {peerId: dialog}); rootScope.broadcast('dialogs_multiupdate', {peerId: dialog});
} }
};
break; // only 0 and 1 folders
} private onUpdateFolderPeers = (update: Update.updateFolderPeers) => {
case 'updateFolderPeers': { // only 0 and 1 folders
//this.log('updateFolderPeers', update); //this.log('updateFolderPeers', update);
const peers = update.folder_peers; const peers = update.folder_peers;
@ -4161,10 +4196,9 @@ export class AppMessagesManager {
this.dialogsStorage.pushDialog(dialog); // need for simultaneously updatePinnedDialogs this.dialogsStorage.pushDialog(dialog); // need for simultaneously updatePinnedDialogs
} }
}); });
break; };
}
case 'updateDialogPinned': { private onUpdateDialogPinned = (update: Update.updateDialogPinned) => {
const folderId = update.folder_id ?? 0; const folderId = update.folder_id ?? 0;
//this.log('updateDialogPinned', update); //this.log('updateDialogPinned', update);
const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
@ -4196,11 +4230,9 @@ export class AppMessagesManager {
this.dialogsStorage.generateIndexForDialog(dialog); this.dialogsStorage.generateIndexForDialog(dialog);
} }
};
break; private onUpdatePinnedDialogs = (update: Update.updatePinnedDialogs) => {
}
case 'updatePinnedDialogs': {
const folderId = update.folder_id ?? 0; const folderId = update.folder_id ?? 0;
const handleOrder = (order: number[]) => { const handleOrder = (order: number[]) => {
@ -4264,24 +4296,21 @@ export class AppMessagesManager {
}); */ }); */
}); });
break; return;
} }
//this.log('before order:', this.dialogsStorage[0].map(d => d.peerId)); //this.log('before order:', this.dialogsStorage[0].map(d => d.peerId));
handleOrder(update.order.map(peer => appPeersManager.getPeerId((peer as DialogPeer.dialogPeer).peer))); handleOrder(update.order.map(peer => appPeersManager.getPeerId((peer as DialogPeer.dialogPeer).peer)));
};
break; private onUpdateEditMessage = (update: Update.updateEditMessage | Update.updateEditChannelMessage) => {
}
case 'updateEditMessage':
case 'updateEditChannelMessage': {
const message = update.message as MyMessage; const message = update.message as MyMessage;
const peerId = this.getMessagePeer(message); const peerId = this.getMessagePeer(message);
const mid = this.generateMessageId(message.id); const mid = this.generateMessageId(message.id);
const storage = this.getMessagesStorage(peerId); const storage = this.getMessagesStorage(peerId);
if(storage[mid] === undefined) { if(storage[mid] === undefined) {
break; return;
} }
// console.trace(dT(), 'edit message', message) // console.trace(dT(), 'edit message', message)
@ -4312,15 +4341,11 @@ export class AppMessagesManager {
rootScope.broadcast('dialogs_multiupdate', updatedDialogs); rootScope.broadcast('dialogs_multiupdate', updatedDialogs);
} }
} }
break; };
}
case 'updateReadChannelDiscussionInbox': private onUpdateReadHistory = (update: Update.updateReadChannelDiscussionInbox | Update.updateReadChannelDiscussionOutbox
case 'updateReadChannelDiscussionOutbox': | Update.updateReadHistoryInbox | Update.updateReadHistoryOutbox
case 'updateReadHistoryInbox': | Update.updateReadChannelInbox | Update.updateReadChannelOutbox) => {
case 'updateReadHistoryOutbox':
case 'updateReadChannelInbox':
case 'updateReadChannelOutbox': {
const channelId = (update as Update.updateReadChannelInbox).channel_id; const channelId = (update as Update.updateReadChannelInbox).channel_id;
const maxId = this.generateMessageId((update as Update.updateReadChannelInbox).max_id || (update as Update.updateReadChannelDiscussionInbox).read_max_id); const maxId = this.generateMessageId((update as Update.updateReadChannelInbox).max_id || (update as Update.updateReadChannelDiscussionInbox).read_max_id);
const threadId = this.generateMessageId((update as Update.updateReadChannelDiscussionInbox).top_msg_id); const threadId = this.generateMessageId((update as Update.updateReadChannelDiscussionInbox).top_msg_id);
@ -4420,12 +4445,9 @@ export class AppMessagesManager {
} }
} }
} }
};
break; private onUpdateReadMessagesContents = (update: Update.updateChannelReadMessagesContents | Update.updateReadMessagesContents) => {
}
case 'updateChannelReadMessagesContents':
case 'updateReadMessagesContents': {
const channelId = (update as Update.updateChannelReadMessagesContents).channel_id; const channelId = (update as Update.updateChannelReadMessagesContents).channel_id;
const mids = (update as Update.updateReadMessagesContents).messages.map(id => this.generateMessageId(id)); const mids = (update as Update.updateReadMessagesContents).messages.map(id => this.generateMessageId(id));
const peerId = channelId ? -channelId : this.getMessageById(mids[0]).peerId; const peerId = channelId ? -channelId : this.getMessageById(mids[0]).peerId;
@ -4437,10 +4459,9 @@ export class AppMessagesManager {
} }
rootScope.broadcast('messages_media_read', {peerId, mids}); rootScope.broadcast('messages_media_read', {peerId, mids});
break; };
}
case 'updateChannelAvailableMessages': { private onUpdateChannelAvailableMessages = (update: Update.updateChannelAvailableMessages) => {
const channelId: number = update.channel_id; const channelId: number = update.channel_id;
const messages: number[] = []; const messages: number[] = [];
const peerId: number = -channelId; const peerId: number = -channelId;
@ -4454,17 +4475,17 @@ export class AppMessagesManager {
} }
(update as any as Update.updateDeleteChannelMessages).messages = messages; (update as any as Update.updateDeleteChannelMessages).messages = messages;
} this.onUpdateDeleteMessages(update as any as Update.updateDeleteChannelMessages);
};
case 'updateDeleteMessages': private onUpdateDeleteMessages = (update: Update.updateDeleteMessages | Update.updateDeleteChannelMessages) => {
case 'updateDeleteChannelMessages': {
const channelId: number = (update as Update.updateDeleteChannelMessages).channel_id; const channelId: number = (update as Update.updateDeleteChannelMessages).channel_id;
//const messages = (update as any as Update.updateDeleteChannelMessages).messages; //const messages = (update as any as Update.updateDeleteChannelMessages).messages;
const messages = (update as any as Update.updateDeleteChannelMessages).messages.map(id => this.generateMessageId(id)); const messages = (update as any as Update.updateDeleteChannelMessages).messages.map(id => this.generateMessageId(id));
const peerId: number = channelId ? -channelId : this.getMessageById(messages[0]).peerId; const peerId: number = channelId ? -channelId : this.getMessageById(messages[0]).peerId;
if(!peerId) { if(!peerId) {
break; return;
} }
apiManager.clearCache('messages.getSearchCounters', (params) => { apiManager.clearCache('messages.getSearchCounters', (params) => {
@ -4515,10 +4536,9 @@ export class AppMessagesManager {
this.reloadConversation(peerId); this.reloadConversation(peerId);
} }
} }
break; };
}
case 'updateChannel': { private onUpdateChannel = (update: Update.updateChannel) => {
const channelId: number = update.channel_id; const channelId: number = update.channel_id;
const peerId = -channelId; const peerId = -channelId;
const channel = appChatsManager.getChat(channelId); const channel = appChatsManager.getChat(channelId);
@ -4545,12 +4565,9 @@ export class AppMessagesManager {
} }
} }
} }
};
break; private onUpdateChannelReload = (update: any) => {
}
// @ts-ignore
case 'updateChannelReload': {
// @ts-ignore // @ts-ignore
const channelId: number = update.channel_id; const channelId: number = update.channel_id;
const peerId = -channelId; const peerId = -channelId;
@ -4561,11 +4578,9 @@ export class AppMessagesManager {
this.reloadConversation(-channelId).then(() => { this.reloadConversation(-channelId).then(() => {
rootScope.broadcast('history_reload', peerId); rootScope.broadcast('history_reload', peerId);
}); });
};
break; private onUpdateChannelMessageViews = (update: Update.updateChannelMessageViews) => {
}
case 'updateChannelMessageViews': {
const views = update.views; const views = update.views;
//const mid = update.id; //const mid = update.id;
const mid = this.generateMessageId(update.id); const mid = this.generateMessageId(update.id);
@ -4574,10 +4589,9 @@ export class AppMessagesManager {
message.views = views; message.views = views;
rootScope.broadcast('message_views', {mid, views}); rootScope.broadcast('message_views', {mid, views});
} }
break; };
}
case 'updateServiceNotification': { private onUpdateServiceNotification = (update: Update.updateServiceNotification) => {
//this.log('updateServiceNotification', update); //this.log('updateServiceNotification', update);
const fromId = 777000; const fromId = 777000;
const peerId = fromId; const peerId = fromId;
@ -4607,17 +4621,14 @@ export class AppMessagesManager {
if(update.inbox_date) { if(update.inbox_date) {
this.pendingTopMsgs[peerId] = messageId; this.pendingTopMsgs[peerId] = messageId;
this.handleUpdate({ this.onUpdateNewMessage({
_: 'updateNewMessage', _: 'updateNewMessage',
message message
} as any); } as any);
} }
};
break; private onUpdatePinnedMessages = (update: Update.updatePinnedMessages | Update.updatePinnedChannelMessages) => {
}
case 'updatePinnedMessages':
case 'updatePinnedChannelMessages': {
const channelId = update._ === 'updatePinnedChannelMessages' ? update.channel_id : undefined; const channelId = update._ === 'updatePinnedChannelMessages' ? update.channel_id : undefined;
const peerId = channelId ? -channelId : appPeersManager.getPeerId((update as Update.updatePinnedMessages).peer); const peerId = channelId ? -channelId : appPeersManager.getPeerId((update as Update.updatePinnedMessages).peer);
@ -4670,11 +4681,9 @@ export class AppMessagesManager {
rootScope.broadcast('peer_pinned_messages', {peerId, mids: messages, pinned: werePinned}); rootScope.broadcast('peer_pinned_messages', {peerId, mids: messages, pinned: werePinned});
}); });
}); });
};
break; private onUpdateNotifySettings = (update: Update.updateNotifySettings) => {
}
case 'updateNotifySettings': {
const {peer, notify_settings} = update; const {peer, notify_settings} = update;
if(peer._ === 'notifyPeer') { if(peer._ === 'notifyPeer') {
const peerId = appPeersManager.getPeerId((peer as NotifyPeer.notifyPeer).peer); const peerId = appPeersManager.getPeerId((peer as NotifyPeer.notifyPeer).peer);
@ -4685,12 +4694,9 @@ export class AppMessagesManager {
rootScope.broadcast('dialog_notify_settings', dialog); rootScope.broadcast('dialog_notify_settings', dialog);
} }
} }
};
/////this.log('updateNotifySettings', peerId, notify_settings); private onUpdateNewScheduledMessage = (update: Update.updateNewScheduledMessage) => {
break;
}
case 'updateNewScheduledMessage': {
const message = update.message as MyMessage; const message = update.message as MyMessage;
const peerId = this.getMessagePeer(message); const peerId = this.getMessagePeer(message);
@ -4712,11 +4718,9 @@ export class AppMessagesManager {
} }
} }
} }
};
break; private onUpdateDeleteScheduledMessages = (update: Update.updateDeleteScheduledMessages) => {
}
case 'updateDeleteScheduledMessages': {
const peerId = appPeersManager.getPeerId(update.peer); const peerId = appPeersManager.getPeerId(update.peer);
const storage = this.scheduledMessagesStorage[peerId]; const storage = this.scheduledMessagesStorage[peerId];
@ -4726,11 +4730,7 @@ export class AppMessagesManager {
rootScope.broadcast('scheduled_delete', {peerId, mids}); rootScope.broadcast('scheduled_delete', {peerId, mids});
} }
};
break;
}
}
}
private updateMessageRepliesIfNeeded(threadMessage: MyMessage) { private updateMessageRepliesIfNeeded(threadMessage: MyMessage) {
try { // * на всякий случай, скорее всего это не понадобится try { // * на всякий случай, скорее всего это не понадобится

10
src/lib/appManagers/appNotificationsManager.ts

@ -13,7 +13,7 @@ import { fontFamily } from "../../components/middleEllipsis";
import { MOUNT_CLASS_TO } from "../../config/debug"; import { MOUNT_CLASS_TO } from "../../config/debug";
import { CancellablePromise, deferredPromise } from "../../helpers/cancellablePromise"; import { CancellablePromise, deferredPromise } from "../../helpers/cancellablePromise";
import { tsNow } from "../../helpers/date"; import { tsNow } from "../../helpers/date";
import { copy, deepEqual } from "../../helpers/object"; import { deepEqual } from "../../helpers/object";
import { convertInputKeyToKey } from "../../helpers/string"; import { convertInputKeyToKey } from "../../helpers/string";
import { isMobile } from "../../helpers/userAgent"; import { isMobile } from "../../helpers/userAgent";
import { InputNotifyPeer, InputPeerNotifySettings, NotifyPeer, PeerNotifySettings, Update } from "../../layer"; import { InputNotifyPeer, InputPeerNotifySettings, NotifyPeer, PeerNotifySettings, Update } from "../../layer";
@ -114,14 +114,10 @@ export class AppNotificationsManager {
this.toggleToggler(); this.toggleToggler();
}); });
rootScope.on('apiUpdate', (update) => { rootScope.addMultipleEventsListeners({
// console.log('on apiUpdate', update) updateNotifySettings: (update) => {
switch(update._) {
case 'updateNotifySettings': {
this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings); this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings);
rootScope.broadcast('notify_settings', update); rootScope.broadcast('notify_settings', update);
break;
}
} }
}); });

9
src/lib/appManagers/appPeersManager.ts

@ -37,14 +37,9 @@ const DialogColorsMap = [0, 7, 4, 1, 6, 3, 5];
export type PeerType = 'channel' | 'chat' | 'megagroup' | 'group' | 'saved'; export type PeerType = 'channel' | 'chat' | 'megagroup' | 'group' | 'saved';
export class AppPeersManager { export class AppPeersManager {
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e as Update; updatePeerBlocked: (update) => {
//console.log('on apiUpdate', update);
switch(update._) {
case 'updatePeerBlocked': {
rootScope.broadcast('peer_block', {peerId: this.getPeerId(update.peer_id), blocked: update.blocked}); rootScope.broadcast('peer_block', {peerId: this.getPeerId(update.peer_id), blocked: update.blocked});
break;
}
} }
}); });
} }

24
src/lib/appManagers/appPollsManager.ts

@ -83,31 +83,19 @@ export class AppPollsManager {
private log = logger('POLLS', LogLevels.error); private log = logger('POLLS', LogLevels.error);
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e; updateMessagePoll: (update) => {
this.handleUpdate(update);
});
}
public handleUpdate(update: any) {
switch(update._) {
case 'updateMessagePoll': { // when someone voted, we too
this.log('updateMessagePoll:', update); this.log('updateMessagePoll:', update);
let poll: Poll = update.poll || this.polls[update.poll_id]; let poll: Poll = update.poll || this.polls[update.poll_id];
if(!poll) { if(!poll) {
break; return;
} }
poll = this.savePoll(poll, update.results); poll = this.savePoll(poll, update.results as any);
rootScope.broadcast('poll_update', {poll, results: update.results}); rootScope.broadcast('poll_update', {poll, results: update.results as any});
break;
}
default:
break;
} }
});
} }
public savePoll(poll: Poll, results: PollResults) { public savePoll(poll: Poll, results: PollResults) {

8
src/lib/appManagers/appPrivacyManager.ts

@ -25,15 +25,11 @@ export class AppPrivacyManager {
}> = {}; }> = {};
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e as Update; updatePrivacy: (update) => {
switch(update._) {
case 'updatePrivacy':
const key = update.key._; const key = update.key._;
this.privacy[key] = update.rules; this.privacy[key] = update.rules;
rootScope.broadcast('privacy_update', update); rootScope.broadcast('privacy_update', update);
break;
} }
}); });
} }

20
src/lib/appManagers/appProfileManager.ts

@ -42,9 +42,8 @@ export class AppProfileManager {
} = {}; } = {};
constructor() { constructor() {
rootScope.on('apiUpdate', (update) => { rootScope.addMultipleEventsListeners({
switch(update._) { updateChatParticipants: (update) => {
case 'updateChatParticipants': {
const participants = update.participants; const participants = update.participants;
if(participants._ === 'chatParticipants') { if(participants._ === 'chatParticipants') {
const chatId = participants.chat_id; const chatId = participants.chat_id;
@ -54,11 +53,9 @@ export class AppProfileManager {
rootScope.broadcast('chat_full_update', chatId); rootScope.broadcast('chat_full_update', chatId);
} }
} }
},
break; updateChatParticipantAdd: (update) => {
}
case 'updateChatParticipantAdd': {
const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull; const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull;
if(chatFull !== undefined) { if(chatFull !== undefined) {
const _participants = chatFull.participants as ChatParticipants.chatParticipants; const _participants = chatFull.participants as ChatParticipants.chatParticipants;
@ -79,11 +76,9 @@ export class AppProfileManager {
_participants.version = update.version; _participants.version = update.version;
rootScope.broadcast('chat_full_update', update.chat_id); rootScope.broadcast('chat_full_update', update.chat_id);
} }
},
break; updateChatParticipantDelete: (update) => {
}
case 'updateChatParticipantDelete': {
const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull; const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull;
if(chatFull !== undefined) { if(chatFull !== undefined) {
const _participants = chatFull.participants as ChatParticipants.chatParticipants; const _participants = chatFull.participants as ChatParticipants.chatParticipants;
@ -97,9 +92,6 @@ export class AppProfileManager {
} }
} }
} }
break;
}
} }
}); });

11
src/lib/appManagers/appStickersManager.ts

@ -26,17 +26,12 @@ export class AppStickersManager {
constructor() { constructor() {
this.getStickerSet({id: 'emoji', access_hash: ''}, {overwrite: true}); this.getStickerSet({id: 'emoji', access_hash: ''}, {overwrite: true});
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e; updateNewStickerSet: (update) => {
switch(update._) {
case 'updateNewStickerSet': {
this.saveStickerSet(update.stickerset, update.stickerset.set.id); this.saveStickerSet(update.stickerset, update.stickerset.set.id);
rootScope.broadcast('stickers_installed', update.stickerset.set); rootScope.broadcast('stickers_installed', update.stickerset.set);
break;
}
} }
}); })
} }
public saveStickers(docs: Document[]) { public saveStickers(docs: Document[]) {

45
src/lib/appManagers/appUsersManager.ts

@ -13,7 +13,7 @@ import { formatPhoneNumber } from "../../components/misc";
import { MOUNT_CLASS_TO } from "../../config/debug"; import { MOUNT_CLASS_TO } from "../../config/debug";
import { tsNow } from "../../helpers/date"; import { tsNow } from "../../helpers/date";
import { safeReplaceObject, isObject } from "../../helpers/object"; import { safeReplaceObject, isObject } from "../../helpers/object";
import { InputUser, Update, User as MTUser, UserProfilePhoto, UserStatus } from "../../layer"; import { InputUser, Update, User as MTUser, UserStatus } from "../../layer";
import I18n, { i18n, LangPackKey } from "../langPack"; import I18n, { i18n, LangPackKey } from "../langPack";
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
@ -22,6 +22,7 @@ import serverTimeManager from "../mtproto/serverTimeManager";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
import rootScope from "../rootScope"; import rootScope from "../rootScope";
import searchIndexManager from "../searchIndexManager"; import searchIndexManager from "../searchIndexManager";
//import AppStorage from "../storage";
import apiUpdatesManager from "./apiUpdatesManager"; import apiUpdatesManager from "./apiUpdatesManager";
import appChatsManager from "./appChatsManager"; import appChatsManager from "./appChatsManager";
import appPeersManager from "./appPeersManager"; import appPeersManager from "./appPeersManager";
@ -32,12 +33,15 @@ import appStateManager from "./appStateManager";
export type User = MTUser.user; export type User = MTUser.user;
export class AppUsersManager { export class AppUsersManager {
/* private storage = new AppStorage<Record<number, User>>({
storeName: 'users'
}); */
private users: {[userId: number]: User} = {}; private users: {[userId: number]: User} = {};
private usernames: {[username: string]: number} = {}; private usernames: {[username: string]: number} = {};
//public userAccess: {[userId: number]: string} = {};
private contactsIndex = searchIndexManager.createIndex(); private contactsIndex = searchIndexManager.createIndex();
private contactsFillPromise: Promise<Set<number>>; private contactsFillPromise: Promise<Set<number>>;
public contactsList: Set<number> = new Set(); private contactsList: Set<number> = new Set();
private updatedContactsList = false; private updatedContactsList = false;
private getTopPeersPromise: Promise<number[]>; private getTopPeersPromise: Promise<number[]>;
@ -47,11 +51,8 @@ export class AppUsersManager {
rootScope.on('state_synchronized', this.updateUsersStatuses); rootScope.on('state_synchronized', this.updateUsersStatuses);
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e as Update; updateUserStatus: (update) => {
//console.log('on apiUpdate', update);
switch(update._) {
case 'updateUserStatus': {
const userId = update.user_id; const userId = update.user_id;
const user = this.users[userId]; const user = this.users[userId];
if(user) { if(user) {
@ -69,11 +70,9 @@ export class AppUsersManager {
user.sortStatus = this.getUserStatusForSort(user.status); user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', userId); rootScope.broadcast('user_update', userId);
} //////else console.warn('No user by id:', userId); } //////else console.warn('No user by id:', userId);
},
break; updateUserPhoto: (update) => {
}
case 'updateUserPhoto': {
const userId = update.user_id; const userId = update.user_id;
const user = this.users[userId]; const user = this.users[userId];
if(user) { if(user) {
@ -88,11 +87,9 @@ export class AppUsersManager {
rootScope.broadcast('user_update', userId); rootScope.broadcast('user_update', userId);
rootScope.broadcast('avatar_update', userId); rootScope.broadcast('avatar_update', userId);
} else console.warn('No user by id:', userId); } else console.warn('No user by id:', userId);
},
break; updateUserName: (update) => {
}
case 'updateUserName': {
const userId = update.user_id; const userId = update.user_id;
const user = this.users[userId]; const user = this.users[userId];
if(user) { if(user) {
@ -104,15 +101,12 @@ export class AppUsersManager {
username: update.username username: update.username
})); }));
} }
break;
} }
});
/* case 'updateContactLink': /* case 'updateContactLink':
this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact'); this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact');
break; */ break; */
}
});
rootScope.on('language_change', (e) => { rootScope.on('language_change', (e) => {
const userId = this.getSelf().id; const userId = this.getSelf().id;
@ -350,19 +344,14 @@ export class AppUsersManager {
} }
safeReplaceObject(oldUser, user); safeReplaceObject(oldUser, user);
}
rootScope.broadcast('user_update', userId); rootScope.broadcast('user_update', userId);
}
if(changedTitle) { if(changedTitle) {
rootScope.broadcast('peer_title_edit', user.id); rootScope.broadcast('peer_title_edit', user.id);
} }
} }
/* public saveUserAccess(id: number, accessHash: string) {
this.userAccess[id] = accessHash;
} */
public getUserStatusForSort(status: User['status'] | number) { public getUserStatusForSort(status: User['status'] | number) {
if(typeof(status) === 'number') { if(typeof(status) === 'number') {
status = this.getUser(status).status; status = this.getUser(status).status;
@ -401,7 +390,7 @@ export class AppUsersManager {
return id; return id;
} }
return this.users[id] || {id: id, pFlags: {deleted: true}, access_hash: ''/* this.userAccess[id] */} as User; return this.users[id] || {id: id, pFlags: {deleted: true}, access_hash: ''} as User;
} }
public getSelf() { public getSelf() {
@ -755,7 +744,7 @@ export class AppUsersManager {
} }
public onContactUpdated(userId: number, isContact: boolean) { public onContactUpdated(userId: number, isContact: boolean) {
const curIsContact = this.contactsList.has(userId); const curIsContact = this.isContact(userId);
if(isContact !== curIsContact) { if(isContact !== curIsContact) {
if(isContact) { if(isContact) {
this.contactsList.add(userId) this.contactsList.add(userId)

8
src/lib/appManagers/appWebPagesManager.ts

@ -26,13 +26,9 @@ export class AppWebPagesManager {
} = {}; } = {};
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.addMultipleEventsListeners({
const update = e; updateWebPage: (update) => {
switch(update._) {
case 'updateWebPage':
this.saveWebPage(update.webpage); this.saveWebPage(update.webpage);
break;
} }
}); });
} }

10
src/lib/cacheStorage.ts

@ -11,15 +11,15 @@ import FileManager from './filemanager';
//import { logger } from './polyfill'; //import { logger } from './polyfill';
export default class CacheStorageController { export default class CacheStorageController {
public static STORAGES: CacheStorageController[] = []; private static STORAGES: CacheStorageController[] = [];
//public dbName = 'cachedFiles'; //public dbName = 'cachedFiles';
public openDbPromise: Promise<Cache>; private openDbPromise: Promise<Cache>;
public useStorage = true; private useStorage = true;
//private log: ReturnType<typeof logger> = logger('CS'); //private log: ReturnType<typeof logger> = logger('CS');
constructor(public dbName: string) { constructor(private dbName: string) {
if(Modes.test) { if(Modes.test) {
this.dbName += '_test'; this.dbName += '_test';
} }
@ -28,7 +28,7 @@ export default class CacheStorageController {
CacheStorageController.STORAGES.push(this); CacheStorageController.STORAGES.push(this);
} }
public openDatabase(): Promise<Cache> { private openDatabase(): Promise<Cache> {
if(this.openDbPromise) { if(this.openDbPromise) {
return this.openDbPromise; return this.openDbPromise;
} }

9
src/lib/rootScope.ts

@ -4,7 +4,7 @@
* https://github.com/morethanwords/tweb/blob/master/LICENSE * https://github.com/morethanwords/tweb/blob/master/LICENSE
*/ */
import type { Message, StickerSet, Update, NotifyPeer, PeerNotifySettings } from "../layer"; import type { Message, StickerSet, Update, NotifyPeer, PeerNotifySettings, ConstructorDeclMap } from "../layer";
import type { MyDocument } from "./appManagers/appDocsManager"; import type { MyDocument } from "./appManagers/appDocsManager";
import type { AppMessagesManager, Dialog, MessagesStorage } from "./appManagers/appMessagesManager"; import type { AppMessagesManager, Dialog, MessagesStorage } from "./appManagers/appMessagesManager";
import type { Poll, PollResults } from "./appManagers/appPollsManager"; import type { Poll, PollResults } from "./appManagers/appPollsManager";
@ -86,7 +86,6 @@ export type BroadcastEvents = {
'channel_settings': {channelId: number}, 'channel_settings': {channelId: number},
'webpage_updated': {id: string, msgs: number[]}, 'webpage_updated': {id: string, msgs: number[]},
'apiUpdate': Update,
'download_progress': any, 'download_progress': any,
'connection_status_change': ConnectionStatusChange, 'connection_status_change': ConnectionStatusChange,
'settings_updated': {key: string, value: any}, 'settings_updated': {key: string, value: any},
@ -112,7 +111,11 @@ export type BroadcastEvents = {
'language_change': void, 'language_change': void,
}; };
export class RootScope extends EventListenerBase<any> { export class RootScope extends EventListenerBase<{
[name in Update['_']]: (update: ConstructorDeclMap[name]) => void
} & {
[name in keyof BroadcastEvents]: (e: BroadcastEvents[name]) => void
}> {
private _overlayIsActive: boolean = false; private _overlayIsActive: boolean = false;
public myId = 0; public myId = 0;
public idle = { public idle = {

2
src/lib/storage.ts

@ -13,7 +13,7 @@ import { DatabaseStore, DatabaseStoreName } from "../config/database";
import IDBStorage, { IDBOptions } from "./idb"; import IDBStorage, { IDBOptions } from "./idb";
export default class AppStorage<Storage extends Record<string, any>/* Storage extends {[name: string]: any} *//* Storage extends Record<string, any> */> { export default class AppStorage<Storage extends Record<string, any>/* Storage extends {[name: string]: any} *//* Storage extends Record<string, any> */> {
public static STORAGES: AppStorage<any>[] = []; private static STORAGES: AppStorage<any>[] = [];
private storage: IDBStorage;//new CacheStorageController('session'); private storage: IDBStorage;//new CacheStorageController('session');
//private cache: Partial<{[key: string]: Storage[typeof key]}> = {}; //private cache: Partial<{[key: string]: Storage[typeof key]}> = {};

57
src/lib/storages/filters.ts

@ -13,6 +13,7 @@ import type { AppUsersManager } from "../appManagers/appUsersManager";
import type _rootScope from "../rootScope"; import type _rootScope from "../rootScope";
import type {AppMessagesManager, Dialog} from '../appManagers/appMessagesManager'; import type {AppMessagesManager, Dialog} from '../appManagers/appMessagesManager';
import type {AppNotificationsManager} from "../appManagers/appNotificationsManager"; import type {AppNotificationsManager} from "../appManagers/appNotificationsManager";
import type { ApiUpdatesManager } from "../appManagers/apiUpdatesManager";
import apiManager from "../mtproto/mtprotoworker"; import apiManager from "../mtproto/mtprotoworker";
import { forEachReverse } from "../../helpers/array"; import { forEachReverse } from "../../helpers/array";
@ -34,30 +35,14 @@ export default class FiltersStorage {
private appPeersManager: AppPeersManager, private appPeersManager: AppPeersManager,
private appUsersManager: AppUsersManager, private appUsersManager: AppUsersManager,
private appNotificationsManager: AppNotificationsManager, private appNotificationsManager: AppNotificationsManager,
private apiUpdatesManager: ApiUpdatesManager,
/* private apiManager: ApiManagerProxy, */ /* private apiManager: ApiManagerProxy, */
private rootScope: typeof _rootScope) { private rootScope: typeof _rootScope) {
rootScope.on('apiUpdate', (e) => {
this.handleUpdate(e);
});
}
public handleUpdate(update: Update) { rootScope.addMultipleEventsListeners({
switch(update._) { updateDialogFilter: this.onUpdateDialogFilter,
case 'updateDialogFilter': {
//console.log('updateDialogFilter', update);
if(update.filter) { updateDialogFilters: (update) => {
this.saveDialogFilter(update.filter as any);
} else if(this.filters[update.id]) { // Папка удалена
//this.getDialogFilters(true);
this.rootScope.broadcast('filter_delete', this.filters[update.id]);
delete this.filters[update.id];
}
break;
}
case 'updateDialogFilters': {
//console.warn('updateDialogFilters', update); //console.warn('updateDialogFilters', update);
const oldFilters = copy(this.filters); const oldFilters = copy(this.filters);
@ -66,17 +51,29 @@ export default class FiltersStorage {
for(const _filterId in oldFilters) { for(const _filterId in oldFilters) {
const filterId = +_filterId; const filterId = +_filterId;
if(!filters.find(filter => filter.id === filterId)) { // * deleted if(!filters.find(filter => filter.id === filterId)) { // * deleted
this.handleUpdate({_: 'updateDialogFilter', id: filterId}); this.onUpdateDialogFilter({_: 'updateDialogFilter', id: filterId});
} }
} }
this.handleUpdate({_: 'updateDialogFilterOrder', order: filters.map(filter => filter.id)}); this.onUpdateDialogFilterOrder({_: 'updateDialogFilterOrder', order: filters.map(filter => filter.id)});
}); });
},
break; updateDialogFilterOrder: this.onUpdateDialogFilterOrder
});
} }
case 'updateDialogFilterOrder': { private onUpdateDialogFilter = (update: Update.updateDialogFilter) => {
if(update.filter) {
this.saveDialogFilter(update.filter as any);
} else if(this.filters[update.id]) { // Папка удалена
//this.getDialogFilters(true);
this.rootScope.broadcast('filter_delete', this.filters[update.id]);
delete this.filters[update.id];
}
};
private onUpdateDialogFilterOrder = (update: Update.updateDialogFilterOrder) => {
//console.log('updateDialogFilterOrder', update); //console.log('updateDialogFilterOrder', update);
this.orderIndex = START_ORDER_INDEX; this.orderIndex = START_ORDER_INDEX;
@ -87,11 +84,7 @@ export default class FiltersStorage {
}); });
this.rootScope.broadcast('filter_order', update.order); this.rootScope.broadcast('filter_order', update.order);
};
break;
}
}
}
public testDialogForFilter(dialog: Dialog, filter: MyDialogFilter) { public testDialogForFilter(dialog: Dialog, filter: MyDialogFilter) {
// exclude_peers // exclude_peers
@ -146,12 +139,12 @@ export default class FiltersStorage {
} }
// non_contacts // non_contacts
if(pFlags.non_contacts && !this.appUsersManager.contactsList.has(peerId)) { if(pFlags.non_contacts && !this.appUsersManager.isContact(peerId)) {
return true; return true;
} }
// contacts // contacts
if(pFlags.contacts && this.appUsersManager.contactsList.has(peerId)) { if(pFlags.contacts && this.appUsersManager.isContact(peerId)) {
return true; return true;
} }
} }
@ -194,7 +187,7 @@ export default class FiltersStorage {
rootScope.$broadcast('filter_update', filter); */ rootScope.$broadcast('filter_update', filter); */
this.handleUpdate({ this.onUpdateDialogFilter({
_: 'updateDialogFilter', _: 'updateDialogFilter',
id: filter.id, id: filter.id,
filter: remove ? undefined : filter as any filter: remove ? undefined : filter as any

Loading…
Cancel
Save