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. 187
      src/lib/appManagers/appChatsManager.ts
  5. 21
      src/lib/appManagers/appDialogsManager.ts
  6. 10
      src/lib/appManagers/appDraftsManager.ts
  7. 1356
      src/lib/appManagers/appMessagesManager.ts
  8. 14
      src/lib/appManagers/appNotificationsManager.ts
  9. 11
      src/lib/appManagers/appPeersManager.ts
  10. 24
      src/lib/appManagers/appPollsManager.ts
  11. 14
      src/lib/appManagers/appPrivacyManager.ts
  12. 92
      src/lib/appManagers/appProfileManager.ts
  13. 15
      src/lib/appManagers/appStickersManager.ts
  14. 125
      src/lib/appManagers/appUsersManager.ts
  15. 10
      src/lib/appManagers/appWebPagesManager.ts
  16. 10
      src/lib/cacheStorage.ts
  17. 9
      src/lib/rootScope.ts
  18. 2
      src/lib/storage.ts
  19. 75
      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() {

187
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,112 +42,105 @@ 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._) { const channelId = update.channel_id;
case 'updateChannel': { //console.log('updateChannel:', update);
const channelId = update.channel_id; rootScope.broadcast('channel_settings', {channelId});
//console.log('updateChannel:', update); },
rootScope.broadcast('channel_settings', {channelId});
break; updateChannelParticipant: (update) => {
apiManagerProxy.clearCache('channels.getParticipants', (params) => {
return (params.channel as InputChannel.inputChannel).channel_id === update.channel_id;
});
},
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);
} }
},
case 'updateChannelParticipant': { updateUserTyping: this.onUpdateUserTyping,
apiManagerProxy.clearCache('channels.getParticipants', (params) => { updateChatUserTyping: this.onUpdateUserTyping,
return (params.channel as InputChannel.inputChannel).channel_id === update.channel_id; updateChannelUserTyping: this.onUpdateUserTyping
}); });
break;
}
case 'updateChatDefaultBannedRights': { appStateManager.getState().then((state) => {
const chatId = -appPeersManager.getPeerId(update.peer); this.chats = state.chats;
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; 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') {
return;
}
const peerId = update._ === 'updateUserTyping' ?
fromId :
-((update as Update.updateChatUserTyping).chat_id || (update as Update.updateChannelUserTyping).channel_id);
const typings = this.typingsInPeer[peerId] ?? (this.typingsInPeer[peerId] = []);
let typing = typings.find(t => t.userId === fromId);
const cancelAction = () => {
delete typing.timeout;
//typings.findAndSplice(t => t === typing);
const idx = typings.indexOf(typing);
if(idx !== -1) {
typings.splice(idx, 1);
}
case 'updateUserTyping': rootScope.broadcast('peer_typings', {peerId, typings});
case 'updateChatUserTyping':
case '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;
}
const peerId = update._ === 'updateUserTyping' ?
fromId :
-((update as Update.updateChatUserTyping).chat_id || (update as Update.updateChannelUserTyping).channel_id);
const typings = this.typingsInPeer[peerId] ?? (this.typingsInPeer[peerId] = []);
let typing = typings.find(t => t.userId === fromId);
const cancelAction = () => {
delete typing.timeout;
//typings.findAndSplice(t => t === typing);
const idx = typings.indexOf(typing);
if(idx !== -1) {
typings.splice(idx, 1);
}
rootScope.broadcast('peer_typings', {peerId, typings});
if(!typings.length) {
delete this.typingsInPeer[peerId];
}
};
if(typing && typing.timeout !== undefined) {
clearTimeout(typing.timeout);
}
if(update.action._ === 'sendMessageCancelAction') { if(!typings.length) {
if(!typing) { delete this.typingsInPeer[peerId];
break; }
} };
cancelAction(); if(typing && typing.timeout !== undefined) {
break; clearTimeout(typing.timeout);
} else { }
if(!typing) {
typing = { if(update.action._ === 'sendMessageCancelAction') {
userId: fromId if(!typing) {
}; return;
}
typings.push(typing);
} cancelAction();
return;
//console.log('updateChatUserTyping', update, typings); } else {
if(!typing) {
typing.action = update.action; typing = {
userId: fromId
if(!appUsersManager.hasUser(fromId)) { };
if(update._ === 'updateChatUserTyping') {
if(update.chat_id && appChatsManager.hasChat(update.chat_id) && !appChatsManager.isChannel(update.chat_id)) { typings.push(typing);
appProfileManager.getChatFull(update.chat_id); }
}
}
//return;
}
appUsersManager.forceUserOnline(fromId);
typing.timeout = window.setTimeout(cancelAction, 6000);
rootScope.broadcast('peer_typings', {peerId, typings});
}
break; //console.log('updateChatUserTyping', update, typings);
typing.action = update.action;
if(!appUsersManager.hasUser(fromId)) {
if(update._ === 'updateChatUserTyping') {
if(update.chat_id && appChatsManager.hasChat(update.chat_id) && !appChatsManager.isChannel(update.chat_id)) {
appProfileManager.getChatFull(update.chat_id);
}
} }
//return;
} }
});
appUsersManager.forceUserOnline(fromId);
appStateManager.getState().then((state) => { typing.timeout = window.setTimeout(cancelAction, 6000);
this.chats = state.chats; rootScope.broadcast('peer_typings', {peerId, typings});
}); }
} };
public saveApiChats(apiChats: any[]) { public saveApiChats(apiChats: any[]) {
apiChats.forEach(chat => this.saveApiChat(chat)); apiChats.forEach(chat => this.saveApiChat(chat));

21
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,19 +299,14 @@ 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); dom.avatarEl.classList.toggle('is-online', online);
if(dom) {
dom.avatarEl.classList.toggle('is-online', online);
}
} }
}); });

10
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);
this.saveDraft(peerID, (update as any).threadId, update.draft, {notify: true});
} }
const peerID = appPeersManager.getPeerId(update.peer);
this.saveDraft(peerID, (update as any).threadId, update.draft, {notify: true});
}); });
} }

1356
src/lib/appManagers/appMessagesManager.ts

File diff suppressed because it is too large Load Diff

14
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._) { this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings);
case 'updateNotifySettings': { rootScope.broadcast('notify_settings', update);
this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings);
rootScope.broadcast('notify_settings', update);
break;
}
} }
}); });

11
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); rootScope.broadcast('peer_block', {peerId: this.getPeerId(update.peer_id), blocked: update.blocked});
switch(update._) {
case 'updatePeerBlocked': {
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) {

14
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) => {
const key = update.key._;
switch(update._) { this.privacy[key] = update.rules;
case 'updatePrivacy': rootScope.broadcast('privacy_update', update);
const key = update.key._;
this.privacy[key] = update.rules;
rootScope.broadcast('privacy_update', update);
break;
} }
}); });
} }

92
src/lib/appManagers/appProfileManager.ts

@ -42,67 +42,59 @@ 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; const chatFull = this.chatsFull[chatId] as ChatFull.chatFull;
const chatFull = this.chatsFull[chatId] as ChatFull.chatFull; if(chatFull !== undefined) {
if(chatFull !== undefined) { chatFull.participants = participants;
chatFull.participants = participants; rootScope.broadcast('chat_full_update', chatId);
rootScope.broadcast('chat_full_update', chatId);
}
} }
break;
} }
},
case 'updateChatParticipantAdd': {
const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull; updateChatParticipantAdd: (update) => {
if(chatFull !== undefined) { const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull;
const _participants = chatFull.participants as ChatParticipants.chatParticipants; if(chatFull !== undefined) {
const participants = _participants.participants || []; const _participants = chatFull.participants as ChatParticipants.chatParticipants;
for(let i = 0, length = participants.length; i < length; i++) { const participants = _participants.participants || [];
if(participants[i].user_id === update.user_id) { for(let i = 0, length = participants.length; i < length; i++) {
return; if(participants[i].user_id === update.user_id) {
} return;
} }
participants.push({
_: 'chatParticipant',
user_id: update.user_id,
inviter_id: update.inviter_id,
date: tsNow(true)
});
_participants.version = update.version;
rootScope.broadcast('chat_full_update', update.chat_id);
} }
break; participants.push({
_: 'chatParticipant',
user_id: update.user_id,
inviter_id: update.inviter_id,
date: tsNow(true)
});
_participants.version = update.version;
rootScope.broadcast('chat_full_update', update.chat_id);
} }
},
case 'updateChatParticipantDelete': {
const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull; updateChatParticipantDelete: (update) => {
if(chatFull !== undefined) { const chatFull = this.chatsFull[update.chat_id] as ChatFull.chatFull;
const _participants = chatFull.participants as ChatParticipants.chatParticipants; if(chatFull !== undefined) {
const participants = _participants.participants || []; const _participants = chatFull.participants as ChatParticipants.chatParticipants;
for(let i = 0, length = participants.length; i < length; i++) { const participants = _participants.participants || [];
if(participants[i].user_id === update.user_id) { for(let i = 0, length = participants.length; i < length; i++) {
participants.splice(i, 1); if(participants[i].user_id === update.user_id) {
_participants.version = update.version; participants.splice(i, 1);
rootScope.broadcast('chat_full_update', update.chat_id); _participants.version = update.version;
return; rootScope.broadcast('chat_full_update', update.chat_id);
} return;
} }
} }
break;
} }
} }
}); });
rootScope.on('chat_update', (chatId) => { rootScope.on('chat_update', (chatId) => {
const fullChat = this.chatsFull[chatId]; const fullChat = this.chatsFull[chatId];
const chat = appChatsManager.getChat(chatId); const chat = appChatsManager.getChat(chatId);

15
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) => {
this.saveStickerSet(update.stickerset, update.stickerset.set.id);
switch(update._) { rootScope.broadcast('stickers_installed', update.stickerset.set);
case 'updateNewStickerSet': {
this.saveStickerSet(update.stickerset, update.stickerset.set.id);
rootScope.broadcast('stickers_installed', update.stickerset.set);
break;
}
} }
}); })
} }
public saveStickers(docs: Document[]) { public saveStickers(docs: Document[]) {

125
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,73 +51,63 @@ 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); const userId = update.user_id;
switch(update._) { const user = this.users[userId];
case 'updateUserStatus': { if(user) {
const userId = update.user_id; user.status = update.status;
const user = this.users[userId]; if(user.status) {
if(user) { if('expires' in user.status) {
user.status = update.status; user.status.expires -= serverTimeManager.serverTimeOffset;
if(user.status) {
if('expires' in user.status) {
user.status.expires -= serverTimeManager.serverTimeOffset;
}
if('was_online' in user.status) {
user.status.was_online -= serverTimeManager.serverTimeOffset;
}
} }
user.sortStatus = this.getUserStatusForSort(user.status); if('was_online' in user.status) {
rootScope.broadcast('user_update', userId); user.status.was_online -= serverTimeManager.serverTimeOffset;
} //////else console.warn('No user by id:', userId);
break;
}
case 'updateUserPhoto': {
const userId = update.user_id;
const user = this.users[userId];
if(user) {
this.forceUserOnline(userId);
if(update.photo._ === 'userProfilePhotoEmpty') {
delete user.photo;
} else {
user.photo = safeReplaceObject(user.photo, update.photo);
} }
}
rootScope.broadcast('user_update', userId); user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('avatar_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) => {
const userId = update.user_id;
case 'updateUserName': { const user = this.users[userId];
const userId = update.user_id; if(user) {
const user = this.users[userId]; this.forceUserOnline(userId);
if(user) {
this.forceUserOnline(userId); if(update.photo._ === 'userProfilePhotoEmpty') {
delete user.photo;
this.saveApiUser(Object.assign({}, user, { } else {
first_name: update.first_name, user.photo = safeReplaceObject(user.photo, update.photo);
last_name: update.last_name,
username: update.username
}));
} }
break; rootScope.broadcast('user_update', userId);
} rootScope.broadcast('avatar_update', userId);
} else console.warn('No user by id:', userId);
},
/* case 'updateContactLink': updateUserName: (update) => {
this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact'); const userId = update.user_id;
break; */ const user = this.users[userId];
if(user) {
this.forceUserOnline(userId);
this.saveApiUser(Object.assign({}, user, {
first_name: update.first_name,
last_name: update.last_name,
username: update.username
}));
}
} }
}); });
/* case 'updateContactLink':
this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact');
break; */
rootScope.on('language_change', (e) => { rootScope.on('language_change', (e) => {
const userId = this.getSelf().id; const userId = this.getSelf().id;
searchIndexManager.indexObject(userId, this.getUserSearchText(userId), this.contactsIndex); searchIndexManager.indexObject(userId, this.getUserSearchText(userId), this.contactsIndex);
@ -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)

10
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) => {
this.saveWebPage(update.webpage);
switch(update._) {
case 'updateWebPage':
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]}> = {};

75
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) {
switch(update._) {
case 'updateDialogFilter': {
//console.log('updateDialogFilter', update);
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; rootScope.addMultipleEventsListeners({
} updateDialogFilter: this.onUpdateDialogFilter,
case 'updateDialogFilters': { updateDialogFilters: (update) => {
//console.warn('updateDialogFilters', update); //console.warn('updateDialogFilters', update);
const oldFilters = copy(this.filters); const oldFilters = copy(this.filters);
@ -66,32 +51,40 @@ 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) => {
//console.log('updateDialogFilterOrder', update); 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];
}
};
this.orderIndex = START_ORDER_INDEX; private onUpdateDialogFilterOrder = (update: Update.updateDialogFilterOrder) => {
update.order.forEach((filterId, idx) => { //console.log('updateDialogFilterOrder', update);
const filter = this.filters[filterId];
delete filter.orderIndex;
this.setOrderIndex(filter);
});
this.rootScope.broadcast('filter_order', update.order); this.orderIndex = START_ORDER_INDEX;
update.order.forEach((filterId, idx) => {
break; const filter = this.filters[filterId];
} delete filter.orderIndex;
} this.setOrderIndex(filter);
} });
this.rootScope.broadcast('filter_order', update.order);
};
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