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 @@ @@ -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() {

187
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,112 +42,105 @@ export class AppChatsManager { @@ -42,112 +42,105 @@ export class AppChatsManager {
public typingsInPeer: {[peerId: number]: UserTyping[]} = {};
constructor() {
rootScope.on('apiUpdate', (update) => {
// console.log('on apiUpdate', update)
switch(update._) {
case 'updateChannel': {
const channelId = update.channel_id;
//console.log('updateChannel:', update);
rootScope.broadcast('channel_settings', {channelId});
break;
rootScope.addMultipleEventsListeners({
updateChannel: (update) => {
const channelId = update.channel_id;
//console.log('updateChannel:', update);
rootScope.broadcast('channel_settings', {channelId});
},
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': {
apiManagerProxy.clearCache('channels.getParticipants', (params) => {
return (params.channel as InputChannel.inputChannel).channel_id === update.channel_id;
});
break;
}
updateUserTyping: this.onUpdateUserTyping,
updateChatUserTyping: this.onUpdateUserTyping,
updateChannelUserTyping: this.onUpdateUserTyping
});
case 'updateChatDefaultBannedRights': {
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);
}
appStateManager.getState().then((state) => {
this.chats = state.chats;
});
}
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':
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);
}
rootScope.broadcast('peer_typings', {peerId, typings});
if(update.action._ === 'sendMessageCancelAction') {
if(!typing) {
break;
}
cancelAction();
break;
} else {
if(!typing) {
typing = {
userId: fromId
};
typings.push(typing);
}
//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);
typing.timeout = window.setTimeout(cancelAction, 6000);
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(!typing) {
return;
}
cancelAction();
return;
} else {
if(!typing) {
typing = {
userId: fromId
};
typings.push(typing);
}
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) => {
this.chats = state.chats;
});
}
typing.timeout = window.setTimeout(cancelAction, 6000);
rootScope.broadcast('peer_typings', {peerId, typings});
}
};
public saveApiChats(apiChats: any[]) {
apiChats.forEach(chat => this.saveApiChat(chat));

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

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

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

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;
poll = this.savePoll(poll, update.results as any);
rootScope.broadcast('poll_update', {poll, results: update.results as any});
}
default:
break;
}
});
}
public savePoll(poll: Poll, results: PollResults) {

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

92
src/lib/appManagers/appProfileManager.ts

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

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

125
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,73 +51,63 @@ export class AppUsersManager { @@ -47,73 +51,63 @@ 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': {
const userId = update.user_id;
const user = this.users[userId];
if(user) {
user.status = update.status;
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;
}
rootScope.addMultipleEventsListeners({
updateUserStatus: (update) => {
const userId = update.user_id;
const user = this.users[userId];
if(user) {
user.status = update.status;
if(user.status) {
if('expires' in user.status) {
user.status.expires -= serverTimeManager.serverTimeOffset;
}
user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', userId);
} //////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);
if('was_online' in user.status) {
user.status.was_online -= serverTimeManager.serverTimeOffset;
}
}
rootScope.broadcast('user_update', userId);
rootScope.broadcast('avatar_update', userId);
} else console.warn('No user by id:', userId);
break;
}
case 'updateUserName': {
const userId = update.user_id;
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
}));
user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', userId);
} //////else console.warn('No user by id:', userId);
},
updateUserPhoto: (update) => {
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);
}
break;
}
rootScope.broadcast('user_update', userId);
rootScope.broadcast('avatar_update', userId);
} else console.warn('No user by id:', userId);
},
/* case 'updateContactLink':
this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact');
break; */
updateUserName: (update) => {
const userId = update.user_id;
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) => {
const userId = this.getSelf().id;
searchIndexManager.indexObject(userId, this.getUserSearchText(userId), this.contactsIndex);
@ -350,19 +344,14 @@ export class AppUsersManager { @@ -350,19 +344,14 @@ export class AppUsersManager {
}
safeReplaceObject(oldUser, user);
rootScope.broadcast('user_update', userId);
}
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)

10
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':
this.saveWebPage(update.webpage);
break;
rootScope.addMultipleEventsListeners({
updateWebPage: (update) => {
this.saveWebPage(update.webpage);
}
});
}

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]}> = {};

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