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 @@ @@ -7,7 +7,7 @@
import { IDBStore } from "../lib/idb";
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};
const Database = {
name: 'tweb' + (Modes.test ? '_test' : ''),

8
src/helpers/eventListenerBase.ts

@ -86,6 +86,14 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi @@ -86,6 +86,14 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi
//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]) {
if(this.listeners[name]) {
this.listeners[name].findAndSplice(l => l.callback === callback);

21
src/lib/appManagers/apiUpdatesManager.ts

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

49
src/lib/appManagers/appChatsManager.ts

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

17
src/lib/appManagers/appDialogsManager.ts

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

8
src/lib/appManagers/appDraftsManager.ts

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

212
src/lib/appManagers/appMessagesManager.ts

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

10
src/lib/appManagers/appNotificationsManager.ts

@ -13,7 +13,7 @@ import { fontFamily } from "../../components/middleEllipsis"; @@ -13,7 +13,7 @@ import { fontFamily } from "../../components/middleEllipsis";
import { MOUNT_CLASS_TO } from "../../config/debug";
import { CancellablePromise, deferredPromise } from "../../helpers/cancellablePromise";
import { tsNow } from "../../helpers/date";
import { copy, deepEqual } from "../../helpers/object";
import { deepEqual } from "../../helpers/object";
import { convertInputKeyToKey } from "../../helpers/string";
import { isMobile } from "../../helpers/userAgent";
import { InputNotifyPeer, InputPeerNotifySettings, NotifyPeer, PeerNotifySettings, Update } from "../../layer";
@ -114,14 +114,10 @@ export class AppNotificationsManager { @@ -114,14 +114,10 @@ export class AppNotificationsManager {
this.toggleToggler();
});
rootScope.on('apiUpdate', (update) => {
// console.log('on apiUpdate', update)
switch(update._) {
case 'updateNotifySettings': {
rootScope.addMultipleEventsListeners({
updateNotifySettings: (update) => {
this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings);
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]; @@ -37,14 +37,9 @@ const DialogColorsMap = [0, 7, 4, 1, 6, 3, 5];
export type PeerType = 'channel' | 'chat' | 'megagroup' | 'group' | 'saved';
export class AppPeersManager {
constructor() {
rootScope.on('apiUpdate', (e) => {
const update = e as Update;
//console.log('on apiUpdate', update);
switch(update._) {
case 'updatePeerBlocked': {
rootScope.addMultipleEventsListeners({
updatePeerBlocked: (update) => {
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 { @@ -83,31 +83,19 @@ export class AppPollsManager {
private log = logger('POLLS', LogLevels.error);
constructor() {
rootScope.on('apiUpdate', (e) => {
const update = e;
this.handleUpdate(update);
});
}
public handleUpdate(update: any) {
switch(update._) {
case 'updateMessagePoll': { // when someone voted, we too
rootScope.addMultipleEventsListeners({
updateMessagePoll: (update) => {
this.log('updateMessagePoll:', update);
let poll: Poll = update.poll || this.polls[update.poll_id];
if(!poll) {
break;
return;
}
poll = this.savePoll(poll, update.results);
rootScope.broadcast('poll_update', {poll, results: update.results});
break;
}
default:
break;
poll = this.savePoll(poll, update.results as any);
rootScope.broadcast('poll_update', {poll, results: update.results as any});
}
});
}
public savePoll(poll: Poll, results: PollResults) {

8
src/lib/appManagers/appPrivacyManager.ts

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

20
src/lib/appManagers/appProfileManager.ts

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

11
src/lib/appManagers/appStickersManager.ts

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

45
src/lib/appManagers/appUsersManager.ts

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

8
src/lib/appManagers/appWebPagesManager.ts

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

10
src/lib/cacheStorage.ts

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

9
src/lib/rootScope.ts

@ -4,7 +4,7 @@ @@ -4,7 +4,7 @@
* 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 { AppMessagesManager, Dialog, MessagesStorage } from "./appManagers/appMessagesManager";
import type { Poll, PollResults } from "./appManagers/appPollsManager";
@ -86,7 +86,6 @@ export type BroadcastEvents = { @@ -86,7 +86,6 @@ export type BroadcastEvents = {
'channel_settings': {channelId: number},
'webpage_updated': {id: string, msgs: number[]},
'apiUpdate': Update,
'download_progress': any,
'connection_status_change': ConnectionStatusChange,
'settings_updated': {key: string, value: any},
@ -112,7 +111,11 @@ export type BroadcastEvents = { @@ -112,7 +111,11 @@ export type BroadcastEvents = {
'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;
public myId = 0;
public idle = {

2
src/lib/storage.ts

@ -13,7 +13,7 @@ import { DatabaseStore, DatabaseStoreName } from "../config/database"; @@ -13,7 +13,7 @@ import { DatabaseStore, DatabaseStoreName } from "../config/database";
import IDBStorage, { IDBOptions } from "./idb";
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 cache: Partial<{[key: string]: Storage[typeof key]}> = {};

57
src/lib/storages/filters.ts

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

Loading…
Cancel
Save