Browse Source

Fix default folder bugs

master
Eduard Kuzmenko 2 years ago
parent
commit
46dc5dccbd
  1. 3
      src/components/horizontalMenu.ts
  2. 28
      src/components/sidebarLeft/tabs/chatFolders.ts
  3. 3
      src/components/sidebarLeft/tabs/includedChats.ts
  4. 9
      src/lib/appManagers/apiUpdatesManager.ts
  5. 3
      src/lib/appManagers/appChatsManager.ts
  6. 61
      src/lib/appManagers/appDialogsManager.ts
  7. 3
      src/lib/appManagers/appDraftsManager.ts
  8. 4
      src/lib/appManagers/appGroupCallsManager.ts
  9. 41
      src/lib/appManagers/appMessagesManager.ts
  10. 5
      src/lib/appManagers/appNotificationsManager.ts
  11. 7
      src/lib/appManagers/appPeersManager.ts
  12. 7
      src/lib/appManagers/appProfileManager.ts
  13. 3
      src/lib/appManagers/appReactionsManager.ts
  14. 7
      src/lib/appManagers/appUsersManager.ts
  15. 8
      src/lib/mediaPlayer.ts
  16. 13
      src/lib/storages/dialogs.ts
  17. 25
      src/lib/storages/filters.ts

3
src/components/horizontalMenu.ts

@ -40,7 +40,8 @@ export function horizontalMenu(
const tabContent = content.children[id] as HTMLDivElement; const tabContent = content.children[id] as HTMLDivElement;
if(onClick) { if(onClick) {
const canChange = await onClick(id, tabContent, animate); const result1 = onClick(id, tabContent, animate);
const canChange = result1 instanceof Promise ? await result1 : result1;
if(canChange !== undefined && !canChange) { if(canChange !== undefined && !canChange) {
return; return;
} }

28
src/components/sidebarLeft/tabs/chatFolders.ts

@ -21,6 +21,7 @@ import { attachClickEvent } from "../../../helpers/dom/clickEvent";
import positionElementByIndex from "../../../helpers/dom/positionElementByIndex"; import positionElementByIndex from "../../../helpers/dom/positionElementByIndex";
import RLottiePlayer from "../../../lib/rlottie/rlottiePlayer"; import RLottiePlayer from "../../../lib/rlottie/rlottiePlayer";
import wrapEmojiText from "../../../lib/richTextProcessor/wrapEmojiText"; import wrapEmojiText from "../../../lib/richTextProcessor/wrapEmojiText";
import { FOLDER_ID_ALL, FOLDER_ID_ARCHIVE, REAL_FOLDERS } from "../../../lib/mtproto/mtproto_config";
export default class AppChatFoldersTab extends SliderSuperTab { export default class AppChatFoldersTab extends SliderSuperTab {
private createFolderBtn: HTMLElement; private createFolderBtn: HTMLElement;
@ -79,9 +80,9 @@ export default class AppChatFoldersTab extends SliderSuperTab {
let div: HTMLElement; let div: HTMLElement;
if(!row) { if(!row) {
row = new Row({ row = new Row({
title: wrapEmojiText(filter.title), title: filter.id === FOLDER_ID_ALL ? i18n('FilterAllChats') : wrapEmojiText(filter.title),
subtitle: description, subtitle: description,
clickable: true clickable: filter.id !== FOLDER_ID_ALL
}); });
if(d.length) { if(d.length) {
@ -92,7 +93,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
if(dialogFilter._ === 'dialogFilter') { if(dialogFilter._ === 'dialogFilter') {
const filterId = filter.id; const filterId = filter.id;
if(!this.filtersRendered.hasOwnProperty(filter.id)) { if(!this.filtersRendered.hasOwnProperty(filter.id) && filter.id !== FOLDER_ID_ALL) {
attachClickEvent(row.container, async() => { attachClickEvent(row.container, async() => {
this.slider.createTab(AppEditFolderTab).open(await this.managers.filtersStorage.getFilter(filterId)); this.slider.createTab(AppEditFolderTab).open(await this.managers.filtersStorage.getFilter(filterId));
}, {listenerSetter: this.listenerSetter}); }, {listenerSetter: this.listenerSetter});
@ -148,8 +149,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
this.scrollable.append(this.stickerContainer, caption, this.createFolderBtn, this.foldersSection.container, this.suggestedSection.container); this.scrollable.append(this.stickerContainer, caption, this.createFolderBtn, this.foldersSection.container, this.suggestedSection.container);
attachClickEvent(this.createFolderBtn, async() => { attachClickEvent(this.createFolderBtn, async() => {
const appConfig = await this.managers.apiManager.getAppConfig(); if(!(await this.canCreateFolder())) {
if(Object.keys(this.filtersRendered).length >= (rootScope.premium ? appConfig.dialog_filters_limit_premium : appConfig.dialog_filters_limit_default)) {
toast('Sorry, you can\'t create more folders.'); toast('Sorry, you can\'t create more folders.');
} else { } else {
this.slider.createTab(AppEditFolderTab).open(); this.slider.createTab(AppEditFolderTab).open();
@ -162,6 +162,10 @@ export default class AppChatFoldersTab extends SliderSuperTab {
this.managers.filtersStorage.getDialogFilters().then(async(filters) => { this.managers.filtersStorage.getDialogFilters().then(async(filters) => {
for(const filter of filters) { for(const filter of filters) {
if(filter.id === FOLDER_ID_ARCHIVE) {
continue;
}
await this.renderFolder(filter, this.foldersSection.content); await this.renderFolder(filter, this.foldersSection.content);
} }
@ -230,6 +234,16 @@ export default class AppChatFoldersTab extends SliderSuperTab {
}); });
} }
private async canCreateFolder() {
const [appConfig, filters] = await Promise.all([
this.managers.apiManager.getAppConfig(),
this.managers.filtersStorage.getDialogFilters()
]);
const filtersLength = filters.filter((filter) => !REAL_FOLDERS.has(filter.id)).length;
return filtersLength < (rootScope.premium ? appConfig.dialog_filters_limit_premium : appConfig.dialog_filters_limit_default);
}
private getSuggestedFilters() { private getSuggestedFilters() {
return this.managers.filtersStorage.getSuggestedDialogsFilters().then(async(suggestedFilters) => { return this.managers.filtersStorage.getSuggestedDialogsFilters().then(async(suggestedFilters) => {
this.suggestedSection.container.style.display = suggestedFilters.length ? '' : 'none'; this.suggestedSection.container.style.display = suggestedFilters.length ? '' : 'none';
@ -241,10 +255,10 @@ export default class AppChatFoldersTab extends SliderSuperTab {
div.append(button); div.append(button);
this.suggestedSection.content.append(div); this.suggestedSection.content.append(div);
attachClickEvent(button, (e) => { attachClickEvent(button, async(e) => {
cancelEvent(e); cancelEvent(e);
if(Object.keys(this.filtersRendered).length >= 10) { if(!(await this.canCreateFolder())) {
toast('Sorry, you can\'t create more folders.'); toast('Sorry, you can\'t create more folders.');
return; return;
} }

3
src/components/sidebarLeft/tabs/includedChats.ts

@ -19,6 +19,7 @@ import copy from "../../../helpers/object/copy";
import forEachReverse from "../../../helpers/array/forEachReverse"; import forEachReverse from "../../../helpers/array/forEachReverse";
import setInnerHTML from "../../../helpers/dom/setInnerHTML"; import setInnerHTML from "../../../helpers/dom/setInnerHTML";
import wrapEmojiText from "../../../lib/richTextProcessor/wrapEmojiText"; import wrapEmojiText from "../../../lib/richTextProcessor/wrapEmojiText";
import { REAL_FOLDERS } from "../../../lib/mtproto/mtproto_config";
export default class AppIncludedChatsTab extends SliderSuperTab { export default class AppIncludedChatsTab extends SliderSuperTab {
private editFolderTab: AppEditFolderTab; private editFolderTab: AppEditFolderTab;
@ -107,7 +108,7 @@ export default class AppIncludedChatsTab extends SliderSuperTab {
this.dialogsByFilters = new Map(); this.dialogsByFilters = new Map();
return this.managers.filtersStorage.getDialogFilters().then(async(filters) => { return this.managers.filtersStorage.getDialogFilters().then(async(filters) => {
await Promise.all(filters.map(async(filter) => { await Promise.all(filters.filter((filter) => !REAL_FOLDERS.has(filter.id)).map(async(filter) => {
const dialogs = await this.managers.dialogsStorage.getFolderDialogs(filter.id); const dialogs = await this.managers.dialogsStorage.getFolderDialogs(filter.id);
const peerIds = dialogs.map((d) => d.peerId); const peerIds = dialogs.map((d) => d.peerId);
this.dialogsByFilters.set(filter, new Set(peerIds)); this.dialogsByFilters.set(filter, new Set(peerIds));

9
src/lib/appManagers/apiUpdatesManager.ts

@ -17,7 +17,6 @@ import App from '../../config/app';
import filterUnique from '../../helpers/array/filterUnique'; import filterUnique from '../../helpers/array/filterUnique';
import { AppManager } from './manager'; import { AppManager } from './manager';
import parseMarkdown from '../richTextProcessor/parseMarkdown'; import parseMarkdown from '../richTextProcessor/parseMarkdown';
import getPeerId from './utils/peers/getPeerId';
import ctx from '../../environment/ctx'; import ctx from '../../environment/ctx';
import EventListenerBase from '../../helpers/eventListenerBase'; import EventListenerBase from '../../helpers/eventListenerBase';
import applyMixins from '../../helpers/applyMixins'; import applyMixins from '../../helpers/applyMixins';
@ -468,7 +467,7 @@ class ApiUpdatesManager {
switch(update._) { switch(update._) {
case 'updateNewChannelMessage': case 'updateNewChannelMessage':
case 'updateEditChannelMessage': case 'updateEditChannelMessage':
channelId = getPeerId(update.message.peer_id).toChatId(); channelId = this.appPeersManager.getPeerId(update.message.peer_id).toChatId();
break; break;
/* case 'updateDeleteChannelMessages': /* case 'updateDeleteChannelMessages':
channelId = update.channel_id; channelId = update.channel_id;
@ -509,11 +508,11 @@ class ApiUpdatesManager {
update._ === 'updateNewChannelMessage' || update._ === 'updateNewChannelMessage' ||
update._ === 'updateEditChannelMessage') { update._ === 'updateEditChannelMessage') {
const message = update.message as Message.message; const message = update.message as Message.message;
const toPeerId = getPeerId(message.peer_id); const toPeerId = this.appPeersManager.getPeerId(message.peer_id);
const fwdHeader: MessageFwdHeader.messageFwdHeader = message.fwd_from || {} as any; const fwdHeader: MessageFwdHeader.messageFwdHeader = message.fwd_from || {} as any;
let reason: string; let reason: string;
if(message.from_id && !this.appUsersManager.hasUser(getPeerId(message.from_id), message.pFlags.post/* || channelId*/) && (reason = 'author') || if(message.from_id && !this.appUsersManager.hasUser(this.appPeersManager.getPeerId(message.from_id), message.pFlags.post/* || channelId*/) && (reason = 'author') ||
fwdHeader.from_id && !this.appUsersManager.hasUser(getPeerId(fwdHeader.from_id), !!(fwdHeader.from_id as Peer.peerChannel).channel_id) && (reason = 'fwdAuthor') || fwdHeader.from_id && !this.appUsersManager.hasUser(this.appPeersManager.getPeerId(fwdHeader.from_id), !!(fwdHeader.from_id as Peer.peerChannel).channel_id) && (reason = 'fwdAuthor') ||
(fwdHeader.from_id as Peer.peerChannel)?.channel_id && !this.appChatsManager.hasChat((fwdHeader.from_id as Peer.peerChannel).channel_id, true) && (reason = 'fwdChannel') || (fwdHeader.from_id as Peer.peerChannel)?.channel_id && !this.appChatsManager.hasChat((fwdHeader.from_id as Peer.peerChannel).channel_id, true) && (reason = 'fwdChannel') ||
toPeerId.isUser() && !this.appUsersManager.hasUser(toPeerId) && (reason = 'toPeer User') || toPeerId.isUser() && !this.appUsersManager.hasUser(toPeerId) && (reason = 'toPeer User') ||
toPeerId.isAnyChat() && !this.appChatsManager.hasChat(toPeerId.toChatId()) && (reason = 'toPeer Chat')) { toPeerId.isAnyChat() && !this.appChatsManager.hasChat(toPeerId.toChatId()) && (reason = 'toPeer Chat')) {

3
src/lib/appManagers/appChatsManager.ts

@ -15,7 +15,6 @@ import safeReplaceObject from "../../helpers/object/safeReplaceObject";
import { ChannelParticipant, ChannelsCreateChannel, Chat, ChatAdminRights, ChatBannedRights, ChatInvite, ChatPhoto, InputChannel, InputChatPhoto, InputFile, InputPeer, SponsoredMessage, Update, Updates } from "../../layer"; import { ChannelParticipant, ChannelsCreateChannel, Chat, ChatAdminRights, ChatBannedRights, ChatInvite, ChatPhoto, InputChannel, InputChatPhoto, InputFile, InputPeer, SponsoredMessage, Update, Updates } from "../../layer";
import { isRestricted } from "../../helpers/restrictions"; import { isRestricted } from "../../helpers/restrictions";
import { AppManager } from "./manager"; import { AppManager } from "./manager";
import getPeerId from "./utils/peers/getPeerId";
import hasRights from "./utils/chats/hasRights"; import hasRights from "./utils/chats/hasRights";
import getParticipantPeerId from "./utils/chats/getParticipantPeerId"; import getParticipantPeerId from "./utils/chats/getParticipantPeerId";
import { AppStoragesManager } from "./appStoragesManager"; import { AppStoragesManager } from "./appStoragesManager";
@ -48,7 +47,7 @@ export class AppChatsManager extends AppManager {
}, },
updateChatDefaultBannedRights: (update) => { updateChatDefaultBannedRights: (update) => {
const chatId = getPeerId(update.peer).toChatId(); const chatId = this.appPeersManager.getPeerId(update.peer).toChatId();
const chat: Chat.chat = this.chats[chatId]; const chat: Chat.chat = this.chats[chatId];
if(chat) { if(chat) {
chat.default_banned_rights = update.default_banned_rights; chat.default_banned_rights = update.default_banned_rights;

61
src/lib/appManagers/appDialogsManager.ts

@ -82,6 +82,7 @@ import pause from "../../helpers/schedulers/pause";
import apiManagerProxy from "../mtproto/mtprotoworker"; import apiManagerProxy from "../mtproto/mtprotoworker";
import filterAsync from "../../helpers/array/filterAsync"; import filterAsync from "../../helpers/array/filterAsync";
import forEachReverse from "../../helpers/array/forEachReverse"; import forEachReverse from "../../helpers/array/forEachReverse";
import indexOfAndSplice from "../../helpers/array/indexOfAndSplice";
export const DIALOG_LIST_ELEMENT_TAG = 'A'; export const DIALOG_LIST_ELEMENT_TAG = 'A';
@ -168,7 +169,7 @@ class SortedDialogList extends SortedList<SortedDialog> {
} }
public clear() { public clear() {
this.list.innerHTML = ''; this.list.textContent = '';
super.clear(); super.clear();
} }
} }
@ -231,6 +232,7 @@ export class AppDialogsManager {
private filtersNavigationItem: NavigationItem; private filtersNavigationItem: NavigationItem;
private managers: AppManagers; private managers: AppManagers;
private selectTab: ReturnType<typeof horizontalMenu>;
constructor() { constructor() {
const managers = this.managers = getProxiedManagers(); const managers = this.managers = getProxiedManagers();
@ -298,6 +300,7 @@ export class AppDialogsManager {
} */ } */
rootScope.addEventListener('state_cleared', () => { rootScope.addEventListener('state_cleared', () => {
const clearCurrent = REAL_FOLDERS.has(this.filterId);
//setTimeout(() => //setTimeout(() =>
apiManagerProxy.getState().then(async(state) => { apiManagerProxy.getState().then(async(state) => {
this.loadedDialogsAtLeastOnce = false; this.loadedDialogsAtLeastOnce = false;
@ -310,8 +313,11 @@ export class AppDialogsManager {
clearPromises.push(storage.clear()); clearPromises.push(storage.clear());
} */ } */
if(clearCurrent) {
this.sortedList.clear(); this.sortedList.clear();
this.onTabChange(); this.onTabChange();
}
this.onStateLoaded(state); this.onStateLoaded(state);
})//, 5000); })//, 5000);
}); });
@ -325,13 +331,14 @@ export class AppDialogsManager {
const foldersScrollable = new ScrollableX(this.folders.menuScrollContainer); const foldersScrollable = new ScrollableX(this.folders.menuScrollContainer);
bottomPart.prepend(this.folders.menuScrollContainer); bottomPart.prepend(this.folders.menuScrollContainer);
const selectTab = horizontalMenu(this.folders.menu, this.folders.container, (id, tabContent) => { const selectTab = this.selectTab = horizontalMenu(this.folders.menu, this.folders.container, (id, tabContent, animate) => {
/* if(id !== 0) { /* if(id !== 0) {
id += 1; id += 1;
} */ } */
id = +tabContent.dataset.filterId || FOLDER_ID_ALL; id = +tabContent.dataset.filterId || FOLDER_ID_ALL;
const wasFilterId = this.filterId;
if(!IS_MOBILE_SAFARI) { if(!IS_MOBILE_SAFARI) {
if(id) { if(id) {
if(!this.filtersNavigationItem) { if(!this.filtersNavigationItem) {
@ -351,14 +358,18 @@ export class AppDialogsManager {
} }
} }
if(this.filterId === id) return; if(wasFilterId === id) return;
this.sortedLists[id].clear(); this.sortedLists[id].clear();
return this.setFilterIdAndChangeTab(id).then(({cached, renderPromise}) => { const promise = this.setFilterIdAndChangeTab(id).then(({cached, renderPromise}) => {
if(cached) { if(cached) {
return renderPromise; return renderPromise;
} }
}); });
if(wasFilterId !== -1) {
return promise;
}
}, () => { }, () => {
for(const folderId in this.sortedLists) { for(const folderId in this.sortedLists) {
if(+folderId !== this.filterId) { if(+folderId !== this.filterId) {
@ -420,8 +431,7 @@ export class AppDialogsManager {
this.sortedList = this.sortedLists[this.filterId]; this.sortedList = this.sortedLists[this.filterId];
this.scroll = this.scrollables[this.filterId]; this.scroll = this.scrollables[this.filterId];
//selectTab(0); // selectTab(0, false);
// (this.folders.menu.firstElementChild as HTMLElement).click();
} }
public get chatList() { public get chatList() {
@ -429,13 +439,13 @@ export class AppDialogsManager {
} }
public setFilterId(filterId: number, localId: MyDialogFilter['localId']) { public setFilterId(filterId: number, localId: MyDialogFilter['localId']) {
this.indexKey = getDialogIndexKey(localId);
this.filterId = filterId; this.filterId = filterId;
this.indexKey = getDialogIndexKey(REAL_FOLDERS.has(filterId) ? filterId as REAL_FOLDER_ID : localId);
} }
public async setFilterIdAndChangeTab(filterId: number) { public async setFilterIdAndChangeTab(filterId: number) {
this.indexKey = await this.managers.dialogsStorage.getDialogIndexKeyByFilterId(filterId);
this.filterId = filterId; this.filterId = filterId;
this.indexKey = await this.managers.dialogsStorage.getDialogIndexKeyByFilterId(filterId);
return this.onTabChange(); return this.onTabChange();
} }
@ -579,8 +589,6 @@ export class AppDialogsManager {
// set tab // set tab
//(this.folders.menu.firstElementChild.children[Math.max(0, filter.id - 2)] as HTMLElement).click(); //(this.folders.menu.firstElementChild.children[Math.max(0, filter.id - 2)] as HTMLElement).click();
(this.folders.menu.firstElementChild as HTMLElement).click();
elements.container.remove(); elements.container.remove();
elements.menu.remove(); elements.menu.remove();
@ -589,9 +597,16 @@ export class AppDialogsManager {
delete this.filtersRendered[filter.id]; delete this.filtersRendered[filter.id];
this.onFiltersLengthChange(); this.onFiltersLengthChange();
if(this.filterId === filter.id) {
this.selectTab(0, false);
}
}); });
rootScope.addEventListener('filter_order', async(order) => { rootScope.addEventListener('filter_order', async(order) => {
order = order.slice();
indexOfAndSplice(order, FOLDER_ID_ARCHIVE);
const containerToAppend = this.folders.menu as HTMLElement; const containerToAppend = this.folders.menu as HTMLElement;
const r = await Promise.all(order.map(async(filterId) => { const r = await Promise.all(order.map(async(filterId) => {
return { return {
@ -649,39 +664,41 @@ export class AppDialogsManager {
private async onStateLoaded(state: State) { private async onStateLoaded(state: State) {
const filtersArr = state.filtersArr; const filtersArr = state.filtersArr;
const haveFilters = filtersArr.length > REAL_FOLDERS.size; const haveFilters = filtersArr.length > REAL_FOLDERS.size;
const filter = filtersArr.find((filter) => filter.id !== FOLDER_ID_ARCHIVE); // const filter = filtersArr.find((filter) => filter.id !== FOLDER_ID_ARCHIVE);
const addFilters = (filters: MyDialogFilter[]) => { const addFilters = (filters: MyDialogFilter[]) => {
// forEachReverse(filters, (filter) => {
// this.addFilter(filter);
// });
for(const filter of filters) { for(const filter of filters) {
this.addFilter(filter); this.addFilter(filter);
} }
}; };
let addFiltersPromise: Promise<any>;
if(haveFilters) { if(haveFilters) {
addFilters(filtersArr); addFilters(filtersArr);
} else { } else {
this.managers.filtersStorage.getDialogFilters().then(addFilters); addFiltersPromise = this.managers.filtersStorage.getDialogFilters().then(addFilters);
} }
(this.folders.menu.firstElementChild as HTMLElement).click();
const loadDialogsPromise = this.onChatsScroll(); const loadDialogsPromise = this.onChatsScroll();
await loadDialogsPromise;
this.loadDialogsRenderPromise = undefined;
addFiltersPromise && await addFiltersPromise;
// this.folders.menu.children[0].classList.add('active');
this.filterId = -1;
this.selectTab(0, false);
if(!this.initedListeners) { if(!this.initedListeners) {
this.initListeners(); this.initListeners();
this.initedListeners = true; this.initedListeners = true;
} }
if(haveFilters && this.showFiltersPromise) { haveFilters && this.showFiltersPromise && await this.showFiltersPromise;
await this.showFiltersPromise;
}
this.managers.appNotificationsManager.getNotifyPeerTypeSettings(); this.managers.appNotificationsManager.getNotifyPeerTypeSettings();
await (await loadDialogsPromise).renderPromise; await (await loadDialogsPromise).renderPromise.catch(noop);
this.managers.appMessagesManager.fillConversations(); this.managers.appMessagesManager.fillConversations();
} }
@ -941,6 +958,8 @@ export class AppDialogsManager {
return; return;
} */ } */
this.log.warn('load', side);
if(this.loadDialogsPromise || this.loadDialogsRenderPromise/* || 1 === 1 */) return this.loadDialogsPromise; if(this.loadDialogsPromise || this.loadDialogsRenderPromise/* || 1 === 1 */) return this.loadDialogsPromise;
else if(this.scroll.loadedAll[side]) { else if(this.scroll.loadedAll[side]) {
return Promise.resolve({ return Promise.resolve({

3
src/lib/appManagers/appDraftsManager.ts

@ -16,7 +16,6 @@ import assumeType from "../../helpers/assumeType";
import isObject from "../../helpers/object/isObject"; import isObject from "../../helpers/object/isObject";
import deepEqual from "../../helpers/object/deepEqual"; import deepEqual from "../../helpers/object/deepEqual";
import { AppManager } from "./manager"; import { AppManager } from "./manager";
import getPeerId from "./utils/peers/getPeerId";
import generateMessageId from "./utils/messageId/generateMessageId"; import generateMessageId from "./utils/messageId/generateMessageId";
import getServerMessageId from "./utils/messageId/getServerMessageId"; import getServerMessageId from "./utils/messageId/getServerMessageId";
@ -29,7 +28,7 @@ export class AppDraftsManager extends AppManager {
protected after() { protected after() {
this.apiUpdatesManager.addMultipleEventsListeners({ this.apiUpdatesManager.addMultipleEventsListeners({
updateDraftMessage: (update) => { updateDraftMessage: (update) => {
const peerId = getPeerId(update.peer); const peerId = this.appPeersManager.getPeerId(update.peer);
this.saveDraft(peerId, update.threadId, update.draft, {notify: true}); this.saveDraft(peerId, update.threadId, update.draft, {notify: true});
} }
}); });

4
src/lib/appManagers/appGroupCallsManager.ts

@ -328,7 +328,7 @@ export class AppGroupCallsManager extends AppManager {
} else { } else {
promise = this.apiManager.invokeApi('phone.joinGroupCall', { promise = this.apiManager.invokeApi('phone.joinGroupCall', {
call: groupCallInput, call: groupCallInput,
join_as: {_: 'inputPeerSelf'}, join_as: this.appPeersManager.getInputPeerSelf(),
muted: true, muted: true,
video_stopped: true, video_stopped: true,
params: { params: {
@ -349,7 +349,7 @@ export class AppGroupCallsManager extends AppManager {
if(options.type === 'main') { if(options.type === 'main') {
const request: PhoneJoinGroupCall = { const request: PhoneJoinGroupCall = {
call: groupCallInput, call: groupCallInput,
join_as: {_: 'inputPeerSelf'}, join_as: this.appPeersManager.getInputPeerSelf(),
params, params,
muted: options.isMuted, muted: options.isMuted,
video_stopped: !options.joinVideo video_stopped: !options.joinVideo

41
src/lib/appManagers/appMessagesManager.ts

@ -45,7 +45,6 @@ import parseEntities from "../richTextProcessor/parseEntities";
import parseMarkdown from "../richTextProcessor/parseMarkdown"; import parseMarkdown from "../richTextProcessor/parseMarkdown";
import getServerMessageId from "./utils/messageId/getServerMessageId"; import getServerMessageId from "./utils/messageId/getServerMessageId";
import generateMessageId from "./utils/messageId/generateMessageId"; import generateMessageId from "./utils/messageId/generateMessageId";
import getPeerId from "./utils/peers/getPeerId";
import filterMessagesByInputFilter from "./utils/messages/filterMessagesByInputFilter"; import filterMessagesByInputFilter from "./utils/messages/filterMessagesByInputFilter";
import ctx from "../../environment/ctx"; import ctx from "../../environment/ctx";
import { getEnvironment } from "../../environment/utils"; import { getEnvironment } from "../../environment/utils";
@ -1925,7 +1924,7 @@ export class AppMessagesManager extends AppManager {
this.dialogsStorage.saveDialog(dialog, undefined, true, saveGlobalOffset); this.dialogsStorage.saveDialog(dialog, undefined, true, saveGlobalOffset);
if(!maxSeenIdIncremented && if(!maxSeenIdIncremented &&
!this.appPeersManager.isChannel(dialog.peerId || getPeerId(dialog.peer))) { !this.appPeersManager.isChannel(dialog.peerId || this.appPeersManager.getPeerId(dialog.peer))) {
this.incrementMaxSeenId(dialog.top_message); this.incrementMaxSeenId(dialog.top_message);
maxSeenIdIncremented = true; maxSeenIdIncremented = true;
} }
@ -2248,7 +2247,7 @@ export class AppMessagesManager extends AppManager {
} }
public getMessagePeer(message: any): PeerId { public getMessagePeer(message: any): PeerId {
const toId = message.peer_id && getPeerId(message.peer_id) || NULL_PEER_ID; const toId = message.peer_id && this.appPeersManager.getPeerId(message.peer_id) || NULL_PEER_ID;
return toId; return toId;
} }
@ -2284,7 +2283,7 @@ export class AppMessagesManager extends AppManager {
public reloadConversation(inputPeer: PeerId | InputPeer) { public reloadConversation(inputPeer: PeerId | InputPeer) {
let promise: CancellablePromise<Dialog>; let promise: CancellablePromise<Dialog>;
if(inputPeer !== undefined) { if(inputPeer !== undefined) {
const peerId = getPeerId(inputPeer); const peerId = this.appPeersManager.getPeerId(inputPeer);
let obj = this.reloadConversationsPeers.get(peerId); let obj = this.reloadConversationsPeers.get(peerId);
if(obj) { if(obj) {
promise = obj.promise; promise = obj.promise;
@ -2667,10 +2666,10 @@ export class AppMessagesManager extends AppManager {
message.peerId = peerId; message.peerId = peerId;
if(peerId === myId/* && !message.from_id && !message.fwd_from */) { if(peerId === myId/* && !message.from_id && !message.fwd_from */) {
message.fromId = fwdHeader ? (fwdHeader.from_id ? getPeerId(fwdHeader.from_id) : NULL_PEER_ID) : myId; message.fromId = fwdHeader ? (fwdHeader.from_id ? this.appPeersManager.getPeerId(fwdHeader.from_id) : NULL_PEER_ID) : myId;
} else { } else {
//message.fromId = message.pFlags.post || (!message.pFlags.out && !message.from_id) ? peerId : appPeersManager.getPeerId(message.from_id); //message.fromId = message.pFlags.post || (!message.pFlags.out && !message.from_id) ? peerId : appPeersManager.getPeerId(message.from_id);
message.fromId = message.pFlags.post || !message.from_id ? peerId : getPeerId(message.from_id); message.fromId = message.pFlags.post || !message.from_id ? peerId : this.appPeersManager.getPeerId(message.from_id);
} }
if(fwdHeader) { if(fwdHeader) {
@ -2681,7 +2680,7 @@ export class AppMessagesManager extends AppManager {
const peer = fwdHeader.saved_from_peer || fwdHeader.from_id; const peer = fwdHeader.saved_from_peer || fwdHeader.from_id;
const msgId = fwdHeader.saved_from_msg_id || fwdHeader.channel_post; const msgId = fwdHeader.saved_from_msg_id || fwdHeader.channel_post;
if(peer && msgId) { if(peer && msgId) {
const savedFromPeerId = getPeerId(peer); const savedFromPeerId = this.appPeersManager.getPeerId(peer);
const savedFromMid = generateMessageId(msgId); const savedFromMid = generateMessageId(msgId);
message.savedFrom = savedFromPeerId + '_' + savedFromMid; message.savedFrom = savedFromPeerId + '_' + savedFromMid;
} }
@ -2693,7 +2692,7 @@ export class AppMessagesManager extends AppManager {
apiMessage.fwdPostID = fwdHeader.channel_post; apiMessage.fwdPostID = fwdHeader.channel_post;
} */ } */
message.fwdFromId = getPeerId(fwdHeader.from_id); message.fwdFromId = this.appPeersManager.getPeerId(fwdHeader.from_id);
if(!overwriting) { if(!overwriting) {
fwdHeader.date -= this.timeManager.getServerTimeOffset(); fwdHeader.date -= this.timeManager.getServerTimeOffset();
@ -3241,7 +3240,7 @@ export class AppMessagesManager extends AppManager {
}, messageReplyMarkup); */ }, messageReplyMarkup); */
if(messageReplyMarkup._ !== 'replyKeyboardHide') { if(messageReplyMarkup._ !== 'replyKeyboardHide') {
messageReplyMarkup.fromId = getPeerId(message.from_id); messageReplyMarkup.fromId = this.appPeersManager.getPeerId(message.from_id);
} }
historyStorage.replyMarkup = messageReplyMarkup; historyStorage.replyMarkup = messageReplyMarkup;
@ -4029,7 +4028,7 @@ export class AppMessagesManager extends AppManager {
if(message._ === 'messageService' && message.action._ === 'messageActionPaymentSent' && message.reply_to) { if(message._ === 'messageService' && message.action._ === 'messageActionPaymentSent' && message.reply_to) {
this.rootScope.dispatchEvent('payment_sent', { this.rootScope.dispatchEvent('payment_sent', {
peerId: message.reply_to.reply_to_peer_id ? getPeerId(message.reply_to.reply_to_peer_id) : message.peerId, peerId: message.reply_to.reply_to_peer_id ? this.appPeersManager.getPeerId(message.reply_to.reply_to_peer_id) : message.peerId,
mid: message.reply_to_mid mid: message.reply_to_mid
}); });
} }
@ -4201,7 +4200,7 @@ export class AppMessagesManager extends AppManager {
private onUpdateMessageReactions = (update: Update.updateMessageReactions) => { private onUpdateMessageReactions = (update: Update.updateMessageReactions) => {
const {peer, msg_id, reactions} = update; const {peer, msg_id, reactions} = update;
const mid = generateMessageId(msg_id); const mid = generateMessageId(msg_id);
const peerId = getPeerId(peer); const peerId = this.appPeersManager.getPeerId(peer);
const message: MyMessage = this.getMessageByPeer(peerId, mid); const message: MyMessage = this.getMessageByPeer(peerId, mid);
if(message?._ !== 'message') { if(message?._ !== 'message') {
@ -4214,7 +4213,7 @@ export class AppMessagesManager extends AppManager {
const previousReactions = message.reactions; const previousReactions = message.reactions;
const previousRecentReactions = previousReactions?.recent_reactions; const previousRecentReactions = previousReactions?.recent_reactions;
if( if(
getPeerId(recentReaction.peer_id) !== this.appPeersManager.peerId && ( this.appPeersManager.getPeerId(recentReaction.peer_id) !== this.appPeersManager.peerId && (
!previousRecentReactions || !previousRecentReactions ||
previousRecentReactions.length <= recentReactions.length previousRecentReactions.length <= recentReactions.length
) && ( ) && (
@ -4244,7 +4243,7 @@ export class AppMessagesManager extends AppManager {
private onUpdateDialogUnreadMark = (update: Update.updateDialogUnreadMark) => { private onUpdateDialogUnreadMark = (update: Update.updateDialogUnreadMark) => {
//this.log('updateDialogUnreadMark', update); //this.log('updateDialogUnreadMark', update);
const peerId = getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = this.appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
if(!dialog) { if(!dialog) {
@ -4332,7 +4331,7 @@ export class AppMessagesManager extends AppManager {
const channelId = (update as Update.updateReadChannelInbox).channel_id; const channelId = (update as Update.updateReadChannelInbox).channel_id;
const maxId = generateMessageId((update as Update.updateReadChannelInbox).max_id || (update as Update.updateReadChannelDiscussionInbox).read_max_id); const maxId = generateMessageId((update as Update.updateReadChannelInbox).max_id || (update as Update.updateReadChannelDiscussionInbox).read_max_id);
const threadId = generateMessageId((update as Update.updateReadChannelDiscussionInbox).top_msg_id); const threadId = generateMessageId((update as Update.updateReadChannelDiscussionInbox).top_msg_id);
const peerId = channelId ? channelId.toPeerId(true) : getPeerId((update as Update.updateReadHistoryInbox).peer); const peerId = channelId ? channelId.toPeerId(true) : this.appPeersManager.getPeerId((update as Update.updateReadHistoryInbox).peer);
const isOut = update._ === 'updateReadHistoryOutbox' || update._ === 'updateReadChannelOutbox' || update._ === 'updateReadChannelDiscussionOutbox' ? true : undefined; const isOut = update._ === 'updateReadHistoryOutbox' || update._ === 'updateReadChannelOutbox' || update._ === 'updateReadChannelDiscussionOutbox' ? true : undefined;
@ -4503,7 +4502,7 @@ export class AppMessagesManager extends AppManager {
} }
this.apiManager.clearCache('messages.getSearchCounters', (params) => { this.apiManager.clearCache('messages.getSearchCounters', (params) => {
return getPeerId(params.peer) === peerId; return this.appPeersManager.getPeerId(params.peer) === peerId;
}); });
const threadKeys: Set<string> = new Set(); const threadKeys: Set<string> = new Set();
@ -4662,7 +4661,7 @@ export class AppMessagesManager extends AppManager {
private onUpdatePinnedMessages = (update: Update.updatePinnedMessages | Update.updatePinnedChannelMessages) => { private onUpdatePinnedMessages = (update: Update.updatePinnedMessages | Update.updatePinnedChannelMessages) => {
const channelId = update._ === 'updatePinnedChannelMessages' ? update.channel_id : undefined; const channelId = update._ === 'updatePinnedChannelMessages' ? update.channel_id : undefined;
const peerId = channelId ? channelId.toPeerId(true) : getPeerId((update as Update.updatePinnedMessages).peer); const peerId = channelId ? channelId.toPeerId(true) : this.appPeersManager.getPeerId((update as Update.updatePinnedMessages).peer);
/* const storage = this.getSearchStorage(peerId, 'inputMessagesFilterPinned'); /* const storage = this.getSearchStorage(peerId, 'inputMessagesFilterPinned');
if(storage.count !== storage.history.length) { if(storage.count !== storage.history.length) {
@ -4718,7 +4717,7 @@ export class AppMessagesManager extends AppManager {
private onUpdateNotifySettings = (update: Update.updateNotifySettings) => { private onUpdateNotifySettings = (update: Update.updateNotifySettings) => {
const {peer, notify_settings} = update; const {peer, notify_settings} = update;
if(peer._ === 'notifyPeer') { if(peer._ === 'notifyPeer') {
const peerId = getPeerId((peer as NotifyPeer.notifyPeer).peer); const peerId = this.appPeersManager.getPeerId((peer as NotifyPeer.notifyPeer).peer);
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
if(dialog) { if(dialog) {
@ -4756,7 +4755,7 @@ export class AppMessagesManager extends AppManager {
}; };
private onUpdateDeleteScheduledMessages = (update: Update.updateDeleteScheduledMessages) => { private onUpdateDeleteScheduledMessages = (update: Update.updateDeleteScheduledMessages) => {
const peerId = getPeerId(update.peer); const peerId = this.appPeersManager.getPeerId(update.peer);
const storage = this.scheduledMessagesStorage[peerId]; const storage = this.scheduledMessagesStorage[peerId];
if(storage) { if(storage) {
@ -5032,12 +5031,12 @@ export class AppMessagesManager extends AppManager {
const filteredReadParticipants = readParticipantsPeerIds.slice(); const filteredReadParticipants = readParticipantsPeerIds.slice();
forEachReverse(filteredReadParticipants, (peerId, idx, arr) => { forEachReverse(filteredReadParticipants, (peerId, idx, arr) => {
if(messageReactionsList.reactions.some((reaction) => getPeerId(reaction.peer_id) === peerId)) { if(messageReactionsList.reactions.some((reaction) => this.appPeersManager.getPeerId(reaction.peer_id) === peerId)) {
arr.splice(idx, 1); arr.splice(idx, 1);
} }
}); });
let combined: {peerId: PeerId, reaction?: string}[] = messageReactionsList.reactions.map((reaction) => ({peerId: getPeerId(reaction.peer_id), reaction: reaction.reaction})); let combined: {peerId: PeerId, reaction?: string}[] = messageReactionsList.reactions.map((reaction) => ({peerId: this.appPeersManager.getPeerId(reaction.peer_id), reaction: reaction.reaction}));
combined = combined.concat(filteredReadParticipants.map((readPeerId) => ({peerId: readPeerId}))); combined = combined.concat(filteredReadParticipants.map((readPeerId) => ({peerId: readPeerId})));
return { return {
@ -5631,7 +5630,7 @@ export class AppMessagesManager extends AppManager {
public fetchMessageReplyTo(message: MyMessage) { public fetchMessageReplyTo(message: MyMessage) {
if(!message.reply_to_mid) return Promise.resolve(this.generateEmptyMessage(0)); if(!message.reply_to_mid) return Promise.resolve(this.generateEmptyMessage(0));
const replyToPeerId = message.reply_to.reply_to_peer_id ? getPeerId(message.reply_to.reply_to_peer_id) : message.peerId; const replyToPeerId = message.reply_to.reply_to_peer_id ? this.appPeersManager.getPeerId(message.reply_to.reply_to_peer_id) : message.peerId;
return this.wrapSingleMessage(replyToPeerId, message.reply_to_mid).then((originalMessage) => { return this.wrapSingleMessage(replyToPeerId, message.reply_to_mid).then((originalMessage) => {
if(!originalMessage) { // ! break the infinite loop if(!originalMessage) { // ! break the infinite loop
message = this.getMessageByPeer(message.peerId, message.mid); // message can come from other thread message = this.getMessageByPeer(message.peerId, message.mid); // message can come from other thread

5
src/lib/appManagers/appNotificationsManager.ts

@ -15,7 +15,6 @@ import { MUTE_UNTIL } from "../mtproto/mtproto_config";
import throttle from "../../helpers/schedulers/throttle"; import throttle from "../../helpers/schedulers/throttle";
import convertInputKeyToKey from "../../helpers/string/convertInputKeyToKey"; import convertInputKeyToKey from "../../helpers/string/convertInputKeyToKey";
import { AppManager } from "./manager"; import { AppManager } from "./manager";
import getPeerId from "./utils/peers/getPeerId";
import ctx from "../../environment/ctx"; import ctx from "../../environment/ctx";
import assumeType from "../../helpers/assumeType"; import assumeType from "../../helpers/assumeType";
@ -41,7 +40,7 @@ export class AppNotificationsManager extends AppManager {
this.apiUpdatesManager.addMultipleEventsListeners({ this.apiUpdatesManager.addMultipleEventsListeners({
updateNotifySettings: (update) => { updateNotifySettings: (update) => {
const peerId = update.peer._ === 'notifyPeer' && getPeerId(update.peer.peer); const peerId = update.peer._ === 'notifyPeer' && this.appPeersManager.getPeerId(update.peer.peer);
const key = update.peer._ !== 'notifyPeer' ? update.peer._ : undefined; const key = update.peer._ !== 'notifyPeer' ? update.peer._ : undefined;
this.savePeerSettings({ this.savePeerSettings({
key, key,
@ -71,7 +70,7 @@ export class AppNotificationsManager extends AppManager {
let peerId: PeerId; let peerId: PeerId;
if(peer._ === 'inputNotifyPeer') { if(peer._ === 'inputNotifyPeer') {
peerId = key = getPeerId(peer.peer); peerId = key = this.appPeersManager.getPeerId(peer.peer);
obj = obj[key]; obj = obj[key];
} }

7
src/lib/appManagers/appPeersManager.ts

@ -87,6 +87,10 @@ export class AppPeersManager extends AppManager {
: this.appChatsManager.getChat(peerId.toChatId()); : this.appChatsManager.getChat(peerId.toChatId());
} }
public getPeerId(...args: Parameters<typeof getPeerId>) {
return getPeerId(...args) || this.peerId;
}
public getDialogPeer(peerId: PeerId): DialogPeer { public getDialogPeer(peerId: PeerId): DialogPeer {
return { return {
_: 'dialogPeer', _: 'dialogPeer',
@ -207,6 +211,9 @@ export class AppPeersManager extends AppManager {
return this.appUsersManager.getUserInputPeer(userId); return this.appUsersManager.getUserInputPeer(userId);
} }
/**
* ! use it only in safe places like requests
*/
public getInputPeerSelf(): InputPeer.inputPeerSelf { public getInputPeerSelf(): InputPeer.inputPeerSelf {
return {_: 'inputPeerSelf'}; return {_: 'inputPeerSelf'};
} }

7
src/lib/appManagers/appProfileManager.ts

@ -15,7 +15,6 @@ import { ChannelParticipantsFilter, ChannelsChannelParticipants, ChannelParticip
import SearchIndex from "../searchIndex"; import SearchIndex from "../searchIndex";
import { AppManager } from "./manager"; import { AppManager } from "./manager";
import getServerMessageId from "./utils/messageId/getServerMessageId"; import getServerMessageId from "./utils/messageId/getServerMessageId";
import getPeerId from "./utils/peers/getPeerId";
import getPhotoInput from "./utils/photos/getPhotoInput"; import getPhotoInput from "./utils/photos/getPhotoInput";
import getParticipantPeerId from "./utils/chats/getParticipantPeerId"; import getParticipantPeerId from "./utils/chats/getParticipantPeerId";
import ctx from "../../environment/ctx"; import ctx from "../../environment/ctx";
@ -632,12 +631,12 @@ export class AppProfileManager extends AppManager {
private onUpdateUserTyping = (update: Update.updateUserTyping | Update.updateChatUserTyping | Update.updateChannelUserTyping) => { private onUpdateUserTyping = (update: Update.updateUserTyping | Update.updateChatUserTyping | Update.updateChannelUserTyping) => {
const fromId = (update as Update.updateUserTyping).user_id ? const fromId = (update as Update.updateUserTyping).user_id ?
(update as Update.updateUserTyping).user_id.toPeerId() : (update as Update.updateUserTyping).user_id.toPeerId() :
getPeerId((update as Update.updateChatUserTyping).from_id); this.appPeersManager.getPeerId((update as Update.updateChatUserTyping).from_id);
if(this.appPeersManager.peerId === fromId || update.action._ === 'speakingInGroupCallAction') { if(this.appPeersManager.peerId === fromId || update.action._ === 'speakingInGroupCallAction') {
return; return;
} }
const peerId = getPeerId(update); const peerId = this.appPeersManager.getPeerId(update);
const typings = this.typingsInPeer[peerId] ?? (this.typingsInPeer[peerId] = []); const typings = this.typingsInPeer[peerId] ?? (this.typingsInPeer[peerId] = []);
let typing = typings.find((t) => t.userId === fromId); let typing = typings.find((t) => t.userId === fromId);
@ -706,7 +705,7 @@ export class AppProfileManager extends AppManager {
}; };
private onUpdatePeerBlocked = (update: Update.updatePeerBlocked) => { private onUpdatePeerBlocked = (update: Update.updatePeerBlocked) => {
const peerId = getPeerId(update.peer_id); const peerId = this.appPeersManager.getPeerId(update.peer_id);
if(this.appPeersManager.isUser(peerId)) { if(this.appPeersManager.isUser(peerId)) {
const userId = peerId.toUserId(); const userId = peerId.toUserId();
const userFull = this.usersFull[userId]; const userFull = this.usersFull[userId];

3
src/lib/appManagers/appReactionsManager.ts

@ -13,7 +13,6 @@ import { AvailableReaction, Message, MessagePeerReaction, MessagesAvailableReact
import { ReferenceContext } from "../mtproto/referenceDatabase"; import { ReferenceContext } from "../mtproto/referenceDatabase";
import { AppManager } from "./manager"; import { AppManager } from "./manager";
import getServerMessageId from "./utils/messageId/getServerMessageId"; import getServerMessageId from "./utils/messageId/getServerMessageId";
import getPeerId from "./utils/peers/getPeerId";
const SAVE_DOC_KEYS = [ const SAVE_DOC_KEYS = [
'static_icon' as const, 'static_icon' as const,
@ -243,7 +242,7 @@ export class AppReactionsManager extends AppManager {
} */ } */
if(reactions.recent_reactions) { if(reactions.recent_reactions) {
findAndSplice(reactions.recent_reactions, (recentReaction) => getPeerId(recentReaction.peer_id) === myPeerId); findAndSplice(reactions.recent_reactions, (recentReaction) => this.appPeersManager.getPeerId(recentReaction.peer_id) === myPeerId);
} }
if(!reactions.results.length) { if(!reactions.results.length) {

7
src/lib/appManagers/appUsersManager.ts

@ -650,9 +650,10 @@ export class AppUsersManager extends AppManager {
public getUserInputPeer(id: UserId): InputPeer.inputPeerSelf | InputPeer.inputPeerUser { public getUserInputPeer(id: UserId): InputPeer.inputPeerSelf | InputPeer.inputPeerUser {
const user = this.getUser(id); const user = this.getUser(id);
if(user.pFlags && user.pFlags.self) { // ! do not use it, there are places that don't support it. need explicit peer id
return {_: 'inputPeerSelf'}; // if(user.pFlags?.self) {
} // return {_: 'inputPeerSelf'};
// }
return { return {
_: 'inputPeerUser', _: 'inputPeerUser',

8
src/lib/mediaPlayer.ts

@ -118,7 +118,7 @@ export default class VideoPlayer extends ControlsHover {
const fullScreenButton = wrapper.querySelector('.fullscreen') as HTMLElement; const fullScreenButton = wrapper.querySelector('.fullscreen') as HTMLElement;
const timeElapsed = wrapper.querySelector('#time-elapsed'); const timeElapsed = wrapper.querySelector('#time-elapsed');
timeDuration = wrapper.querySelector('#time-duration') as HTMLElement; timeDuration = wrapper.querySelector('#time-duration') as HTMLElement;
timeDuration.innerHTML = toHHMMSS(video.duration | 0); timeDuration.textContent = toHHMMSS(video.duration | 0);
const volumeSelector = new VolumeSelector(listenerSetter); const volumeSelector = new VolumeSelector(listenerSetter);
@ -223,7 +223,7 @@ export default class VideoPlayer extends ControlsHover {
addFullScreenListener(wrapper, this.onFullScreen.bind(this, fullScreenButton), listenerSetter); addFullScreenListener(wrapper, this.onFullScreen.bind(this, fullScreenButton), listenerSetter);
listenerSetter.add(video)('timeupdate', () => { listenerSetter.add(video)('timeupdate', () => {
timeElapsed.innerHTML = toHHMMSS(video.currentTime | 0); timeElapsed.textContent = toHHMMSS(video.currentTime | 0);
}); });
listenerSetter.add(video)('play', () => { listenerSetter.add(video)('play', () => {
@ -254,10 +254,10 @@ export default class VideoPlayer extends ControlsHover {
}); });
if(video.duration || initDuration) { if(video.duration || initDuration) {
timeDuration.innerHTML = toHHMMSS(Math.round(video.duration || initDuration)); timeDuration.textContent = toHHMMSS(Math.round(video.duration || initDuration));
} else { } else {
onMediaLoad(video).then(() => { onMediaLoad(video).then(() => {
timeDuration.innerHTML = toHHMMSS(Math.round(video.duration)); timeDuration.textContent = toHHMMSS(Math.round(video.duration));
}); });
} }
} }

13
src/lib/storages/dialogs.ts

@ -25,7 +25,6 @@ import indexOfAndSplice from "../../helpers/array/indexOfAndSplice";
import insertInDescendSortedArray from "../../helpers/array/insertInDescendSortedArray"; import insertInDescendSortedArray from "../../helpers/array/insertInDescendSortedArray";
import safeReplaceObject from "../../helpers/object/safeReplaceObject"; import safeReplaceObject from "../../helpers/object/safeReplaceObject";
import getServerMessageId from "../appManagers/utils/messageId/getServerMessageId"; import getServerMessageId from "../appManagers/utils/messageId/getServerMessageId";
import getPeerId from "../appManagers/utils/peers/getPeerId";
import generateMessageId from "../appManagers/utils/messageId/generateMessageId"; import generateMessageId from "../appManagers/utils/messageId/generateMessageId";
import { AppManager } from "../appManagers/manager"; import { AppManager } from "../appManagers/manager";
import getDialogIndexKey from "../appManagers/utils/dialogs/getDialogIndexKey"; import getDialogIndexKey from "../appManagers/utils/dialogs/getDialogIndexKey";
@ -787,7 +786,7 @@ export default class DialogsStorage extends AppManager {
const updatedDialogs: {[peerId: PeerId]: Dialog} = {}; const updatedDialogs: {[peerId: PeerId]: Dialog} = {};
(dialogsResult.dialogs as Dialog[]).forEach((dialog) => { (dialogsResult.dialogs as Dialog[]).forEach((dialog) => {
const peerId = getPeerId(dialog.peer); const peerId = this.appPeersManager.getPeerId(dialog.peer);
let topMessage = dialog.top_message; let topMessage = dialog.top_message;
const topPendingMessage = this.appMessagesManager.pendingTopMsgs[peerId]; const topPendingMessage = this.appMessagesManager.pendingTopMsgs[peerId];
@ -838,7 +837,7 @@ export default class DialogsStorage extends AppManager {
* Won't save migrated from peer, forbidden peers, left and kicked * Won't save migrated from peer, forbidden peers, left and kicked
*/ */
public saveDialog(dialog: Dialog, folderId = dialog.folder_id ?? FOLDER_ID_ALL, ignoreOffsetDate?: boolean, saveGlobalOffset?: boolean) { public saveDialog(dialog: Dialog, folderId = dialog.folder_id ?? FOLDER_ID_ALL, ignoreOffsetDate?: boolean, saveGlobalOffset?: boolean) {
const peerId = getPeerId(dialog.peer); const peerId = this.appPeersManager.getPeerId(dialog.peer);
if(!peerId) { if(!peerId) {
console.error('saveConversation no peerId???', dialog, folderId); console.error('saveConversation no peerId???', dialog, folderId);
return; return;
@ -902,7 +901,7 @@ export default class DialogsStorage extends AppManager {
if(!channelId && peerId.isAnyChat()) { if(!channelId && peerId.isAnyChat()) {
const chat = this.appChatsManager.getChat(peerId.toChatId()); const chat = this.appChatsManager.getChat(peerId.toChatId());
if(chat && chat.migrated_to && chat.pFlags.deactivated) { if(chat && chat.migrated_to && chat.pFlags.deactivated) {
const migratedToPeer = getPeerId(chat.migrated_to); const migratedToPeer = this.appPeersManager.getPeerId(chat.migrated_to);
this.appMessagesManager.migratedFromTo[peerId] = migratedToPeer; this.appMessagesManager.migratedFromTo[peerId] = migratedToPeer;
this.appMessagesManager.migratedToFrom[migratedToPeer] = peerId; this.appMessagesManager.migratedToFrom[migratedToPeer] = peerId;
dialog.migratedTo = migratedToPeer; dialog.migratedTo = migratedToPeer;
@ -1109,7 +1108,7 @@ export default class DialogsStorage extends AppManager {
peers.forEach((folderPeer) => { peers.forEach((folderPeer) => {
const {folder_id, peer} = folderPeer; const {folder_id, peer} = folderPeer;
const peerId = getPeerId(peer); const peerId = this.appPeersManager.getPeerId(peer);
const dialog = this.dropDialog(peerId)[0]; const dialog = this.dropDialog(peerId)[0];
if(dialog) { if(dialog) {
if(dialog.pFlags?.pinned) { if(dialog.pFlags?.pinned) {
@ -1128,7 +1127,7 @@ export default class DialogsStorage extends AppManager {
private onUpdateDialogPinned = (update: Update.updateDialogPinned) => { private onUpdateDialogPinned = (update: Update.updateDialogPinned) => {
const folderId = update.folder_id ?? FOLDER_ID_ALL; const folderId = update.folder_id ?? FOLDER_ID_ALL;
//this.log('updateDialogPinned', update); //this.log('updateDialogPinned', update);
const peerId = getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = this.appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
// этот код внизу никогда не сработает, в папках за пиннед отвечает updateDialogFilter // этот код внизу никогда не сработает, в папках за пиннед отвечает updateDialogFilter
@ -1217,6 +1216,6 @@ export default class DialogsStorage extends AppManager {
//this.log('before order:', this.dialogsStorage[0].map((d) => d.peerId)); //this.log('before order:', this.dialogsStorage[0].map((d) => d.peerId));
handleOrder(update.order.map((peer) => getPeerId((peer as DialogPeer.dialogPeer).peer))); handleOrder(update.order.map((peer) => this.appPeersManager.getPeerId((peer as DialogPeer.dialogPeer).peer)));
}; };
} }

25
src/lib/storages/filters.ts

@ -8,7 +8,6 @@ import type { DialogFilter, Update } from "../../layer";
import type { Dialog } from '../appManagers/appMessagesManager'; import type { Dialog } from '../appManagers/appMessagesManager';
import forEachReverse from "../../helpers/array/forEachReverse"; import forEachReverse from "../../helpers/array/forEachReverse";
import copy from "../../helpers/object/copy"; import copy from "../../helpers/object/copy";
import getPeerId from "../appManagers/utils/peers/getPeerId";
import { AppManager } from "../appManagers/manager"; import { AppManager } from "../appManagers/manager";
import findAndSplice from "../../helpers/array/findAndSplice"; import findAndSplice from "../../helpers/array/findAndSplice";
import assumeType from "../../helpers/assumeType"; import assumeType from "../../helpers/assumeType";
@ -95,7 +94,6 @@ export default class FiltersStorage extends AppManager {
return this.appStateManager.getState().then((state) => { return this.appStateManager.getState().then((state) => {
const filtersArr = this.prependFilters(state.filtersArr); const filtersArr = this.prependFilters(state.filtersArr);
filtersArr.map((filter) => { filtersArr.map((filter) => {
delete filter.localId;
this.saveDialogFilter(filter, false, true); this.saveDialogFilter(filter, false, true);
}); });
}); });
@ -117,6 +115,11 @@ export default class FiltersStorage extends AppManager {
findAndSplice(filters, (filter) => (filter as MyDialogFilter).id === FOLDER_ID_ARCHIVE); findAndSplice(filters, (filter) => (filter as MyDialogFilter).id === FOLDER_ID_ARCHIVE);
filters.splice(/* 1 */filters[0] === allChatsFilter ? 1 : 0, 0, archiveFilter); filters.splice(/* 1 */filters[0] === allChatsFilter ? 1 : 0, 0, archiveFilter);
this.localId = START_LOCAL_ID;
filters.forEach((filter) => {
delete filter.localId;
});
return filters; return filters;
} }
@ -174,14 +177,19 @@ export default class FiltersStorage extends AppManager {
private onUpdateDialogFilterOrder = (update: Update.updateDialogFilterOrder) => { private onUpdateDialogFilterOrder = (update: Update.updateDialogFilterOrder) => {
//console.log('updateDialogFilterOrder', update); //console.log('updateDialogFilterOrder', update);
const order = update.order.slice();
if(!order.includes(FOLDER_ID_ARCHIVE)) {
order.splice(order[0] === FOLDER_ID_ALL ? 1 : 0, 0, FOLDER_ID_ARCHIVE);
}
this.localId = START_LOCAL_ID; this.localId = START_LOCAL_ID;
update.order.forEach((filterId, idx) => { order.forEach((filterId) => {
const filter = this.filters[filterId]; const filter = this.filters[filterId];
delete filter.localId; delete filter.localId;
this.setLocalId(filter); this.setLocalId(filter);
}); });
this.rootScope.dispatchEvent('filter_order', update.order); this.rootScope.dispatchEvent('filter_order', order);
this.pushToState(); this.pushToState();
}; };
@ -415,7 +423,7 @@ export default class FiltersStorage extends AppManager {
// const missingPeerIds: PeerId[] = []; // const missingPeerIds: PeerId[] = [];
const reloadDialogs = peers.filter((inputPeer) => { const reloadDialogs = peers.filter((inputPeer) => {
const peerId = getPeerId(inputPeer); const peerId = this.appPeersManager.getPeerId(inputPeer);
const isAlreadyReloaded = this.reloadedPeerIds.has(peerId); const isAlreadyReloaded = this.reloadedPeerIds.has(peerId);
const dialog = this.appMessagesManager.getDialogOnly(peerId); const dialog = this.appMessagesManager.getDialogOnly(peerId);
// if(isAlreadyReloaded && !dialog) { // if(isAlreadyReloaded && !dialog) {
@ -435,7 +443,7 @@ export default class FiltersStorage extends AppManager {
} }
const reloadPromises = reloadDialogs.map((inputPeer) => { const reloadPromises = reloadDialogs.map((inputPeer) => {
const peerId = getPeerId(inputPeer); const peerId = this.appPeersManager.getPeerId(inputPeer);
const promise = this.appMessagesManager.reloadConversation(inputPeer) const promise = this.appMessagesManager.reloadConversation(inputPeer)
.then((dialog) => { .then((dialog) => {
this.reloadedPeerIds.add(peerId); this.reloadedPeerIds.add(peerId);
@ -465,7 +473,8 @@ export default class FiltersStorage extends AppManager {
} }
const filters = await this.apiManager.invokeApiSingle('messages.getDialogFilters'); const filters = await this.apiManager.invokeApiSingle('messages.getDialogFilters');
return this.prependFilters(filters).map((filter) => this.saveDialogFilter(filter, overwrite)).filter(Boolean); const prepended = this.prependFilters(filters);
return prepended.map((filter) => this.saveDialogFilter(filter, overwrite)).filter(Boolean);
} }
public getSuggestedDialogsFilters() { public getSuggestedDialogsFilters() {
@ -483,7 +492,7 @@ export default class FiltersStorage extends AppManager {
if(!REAL_FOLDERS.has(filter.id)) { if(!REAL_FOLDERS.has(filter.id)) {
convertment.forEach(([from, to]) => { convertment.forEach(([from, to]) => {
assumeType<MyDialogFilter>(filter); assumeType<MyDialogFilter>(filter);
filter[to] = filter[from].map((peer) => getPeerId(peer)); filter[to] = filter[from].map((peer) => this.appPeersManager.getPeerId(peer));
}); });
this.filterIncludedPinnedPeers(filter); this.filterIncludedPinnedPeers(filter);

Loading…
Cancel
Save