Telegram Web K with changes to work inside I2P https://web.telegram.i2p/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

687 lines
21 KiB

/*
* https://github.com/morethanwords/tweb
* Copyright (C) 2019-2021 Eduard Kuzmenko
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*
* Originally from:
* https://github.com/zhukov/webogram
* Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>
* https://github.com/zhukov/webogram/blob/master/LICENSE
*/
//import apiManager from '../mtproto/apiManager';
import DEBUG, { MOUNT_CLASS_TO } from '../../config/debug';
import { Message, MessageFwdHeader, Peer, Update, Updates } from '../../layer';
import { logger, LogTypes } from '../logger';
import apiManager from '../mtproto/mtprotoworker';
import rootScope from '../rootScope';
//import networkerFactory from '../mtproto/networkerFactory';
import appUsersManager from "./appUsersManager";
5 years ago
import appChatsManager from "./appChatsManager";
import appPeersManager from "./appPeersManager";
import appStateManager from './appStateManager';
import serverTimeManager from '../mtproto/serverTimeManager';
5 years ago
4 years ago
type UpdatesState = {
pendingPtsUpdates: (Update & {pts: number, pts_count: number})[],
pendingSeqUpdates?: {[seq: number]: {seq: number, date: number, updates: any[]}},
4 years ago
syncPending: {
seqAwaiting?: number,
ptsAwaiting?: true,
timeout: number
},
syncLoading: Promise<void>,
4 years ago
seq?: number,
pts?: number,
date?: number,
lastPtsUpdateTime?: number
};
4 years ago
const SYNC_DELAY = 6;
5 years ago
export class ApiUpdatesManager {
4 years ago
public updatesState: UpdatesState = {
5 years ago
pendingPtsUpdates: [],
pendingSeqUpdates: {},
4 years ago
syncPending: null,
syncLoading: null
5 years ago
};
3 years ago
private channelStates: {[channelId: number]: UpdatesState} = {};
private attached = false;
private log = logger('UPDATES', LogTypes.Error | LogTypes.Warn | LogTypes.Log/* | LogTypes.Debug */);
private debug = DEBUG;
4 years ago
private setProxy() {
const self = this;
this.updatesState = new Proxy(this.updatesState, {
set: function(target: ApiUpdatesManager['updatesState'], key: keyof ApiUpdatesManager['updatesState'], value: ApiUpdatesManager['updatesState'][typeof key]) {
// @ts-ignore
target[key] = value;
self.saveUpdatesState();
4 years ago
return true;
}
});
}
public saveUpdatesState() {
const us = this.updatesState;
appStateManager.pushToState('updates', {
seq: us.seq,
pts: us.pts,
date: us.date
});
}
private popPendingSeqUpdate() {
const state = this.updatesState;
const nextSeq = state.seq + 1;
const pendingUpdatesData = state.pendingSeqUpdates[nextSeq];
5 years ago
if(!pendingUpdatesData) {
return false;
}
4 years ago
const updates = pendingUpdatesData.updates;
for(let i = 0, length = updates.length; i < length; ++i) {
5 years ago
this.saveUpdate(updates[i]);
}
state.seq = pendingUpdatesData.seq;
if(pendingUpdatesData.date && state.date < pendingUpdatesData.date) {
state.date = pendingUpdatesData.date;
5 years ago
}
delete state.pendingSeqUpdates[nextSeq];
5 years ago
if(!this.popPendingSeqUpdate() &&
state.syncPending &&
state.syncPending.seqAwaiting &&
state.seq >= state.syncPending.seqAwaiting) {
if(!state.syncPending.ptsAwaiting) {
clearTimeout(state.syncPending.timeout);
state.syncPending = null;
5 years ago
} else {
delete state.syncPending.seqAwaiting;
5 years ago
}
}
return true;
}
private popPendingPtsUpdate(channelId: number) {
const curState = channelId ? this.getChannelState(channelId) : this.updatesState;
5 years ago
if(!curState.pendingPtsUpdates.length) {
return false;
}
curState.pendingPtsUpdates.sort((a, b) => {
5 years ago
return a.pts - b.pts;
});
// this.log('pop update', channelId, curState.pendingPtsUpdates)
5 years ago
4 years ago
let curPts = curState.pts;
let goodPts = 0;
let goodIndex = 0;
for(let i = 0, length = curState.pendingPtsUpdates.length; i < length; ++i) {
4 years ago
const update = curState.pendingPtsUpdates[i];
5 years ago
curPts += update.pts_count;
if(curPts >= update.pts) {
goodPts = update.pts;
goodIndex = i;
}
}
if(!goodPts) {
return false;
}
this.debug && this.log.debug('pop pending pts updates', goodPts, curState.pendingPtsUpdates.slice(0, goodIndex + 1));
5 years ago
curState.pts = goodPts;
for(let i = 0; i <= goodIndex; ++i) {
4 years ago
const update = curState.pendingPtsUpdates[i];
// @ts-ignore
5 years ago
this.saveUpdate(update);
}
curState.pendingPtsUpdates.splice(0, goodIndex + 1);
if(!curState.pendingPtsUpdates.length && curState.syncPending) {
if(!curState.syncPending.seqAwaiting) {
clearTimeout(curState.syncPending.timeout);
4 years ago
curState.syncPending = null;
5 years ago
} else {
delete curState.syncPending.ptsAwaiting;
}
}
return true;
}
public forceGetDifference() {
if(!this.updatesState.syncLoading) {
this.getDifference();
}
}
public processLocalUpdate(update: Update) {
this.processUpdateMessage({
_: 'updateShort',
update
} as Updates);
}
public processUpdateMessage = (updateMessage: any, options: Partial<{
override: boolean
}> = {}) => {
5 years ago
// return forceGetDifference()
4 years ago
const processOpts = {
5 years ago
date: updateMessage.date,
seq: updateMessage.seq,
4 years ago
seqStart: updateMessage.seq_start,
//ignoreSyncLoading: options.ignoreSyncLoading
5 years ago
};
4 years ago
this.debug && this.log.debug('processUpdateMessage', updateMessage);
5 years ago
switch(updateMessage._) {
case 'updatesTooLong':
case 'new_session_created':
this.forceGetDifference();
break;
case 'updateShort':
this.processUpdate(updateMessage.update, processOpts);
break;
case 'updateShortMessage':
case 'updateShortChatMessage': {
this.debug && this.log.debug('updateShortMessage | updateShortChatMessage', {...updateMessage});
const isOut = updateMessage.pFlags.out;
const fromId = updateMessage.from_id || (isOut ? rootScope.myId : updateMessage.user_id);
const toId = updateMessage.chat_id
5 years ago
? -updateMessage.chat_id
: (updateMessage.user_id || rootScope.myId);
5 years ago
this.processUpdate({
_: 'updateNewMessage',
message: {
_: 'message',
pFlags: updateMessage.pFlags,
id: updateMessage.id,
from_id: appPeersManager.getOutputPeer(fromId),
peer_id: appPeersManager.getOutputPeer(toId),
5 years ago
date: updateMessage.date,
message: updateMessage.message,
fwd_from: updateMessage.fwd_from,
reply_to: updateMessage.reply_to,
5 years ago
entities: updateMessage.entities
},
pts: updateMessage.pts,
pts_count: updateMessage.pts_count
}, processOpts);
break;
}
5 years ago
case 'updatesCombined':
case 'updates':
appUsersManager.saveApiUsers(updateMessage.users, options.override);
appChatsManager.saveApiChats(updateMessage.chats, options.override);
5 years ago
updateMessage.updates.forEach((update: Update) => {
5 years ago
this.processUpdate(update, processOpts);
});
break;
default:
this.log.warn('Unknown update message', updateMessage);
5 years ago
}
};
5 years ago
private getDifference(first = false): Promise<void> {
// this.trace('Get full diff')
const updatesState = this.updatesState;
let wasSyncing = updatesState.syncLoading;
if(!wasSyncing) {
5 years ago
updatesState.pendingSeqUpdates = {};
updatesState.pendingPtsUpdates = [];
}
if(updatesState.syncPending) {
clearTimeout(updatesState.syncPending.timeout);
4 years ago
updatesState.syncPending = null;
5 years ago
}
const promise = apiManager.invokeApi('updates.getDifference', {
5 years ago
pts: updatesState.pts,
pts_total_limit: first /* && false */? /* 50 */1200 : undefined,
5 years ago
date: updatesState.date,
qts: -1
}, {
timeout: 0x7fffffff
}).then((differenceResult) => {
this.debug && this.log.debug('Get diff result', differenceResult);
if(differenceResult._ === 'updates.differenceEmpty') {
this.debug && this.log.debug('apply empty diff', differenceResult.seq);
5 years ago
updatesState.date = differenceResult.date;
updatesState.seq = differenceResult.seq;
return;
5 years ago
}
4 years ago
// ! SORRY I'M SORRY I'M SORRY
if(first) {
rootScope.dispatchEvent('state_synchronizing');
4 years ago
}
if(differenceResult._ !== 'updates.differenceTooLong') {
appUsersManager.saveApiUsers(differenceResult.users);
appChatsManager.saveApiChats(differenceResult.chats);
// Should be first because of updateMessageID
// this.log('applying', differenceResult.other_updates.length, 'other updates')
differenceResult.other_updates.forEach((update) => {
switch(update._) {
case 'updateChannelTooLong':
case 'updateNewChannelMessage':
case 'updateEditChannelMessage':
this.processUpdate(update);
return;
}
this.saveUpdate(update);
5 years ago
});
// this.log('applying', differenceResult.new_messages.length, 'new messages')
differenceResult.new_messages.forEach((apiMessage) => {
this.saveUpdate({
_: 'updateNewMessage',
message: apiMessage,
pts: updatesState.pts,
pts_count: 0
});
});
const nextState = differenceResult._ === 'updates.difference' ? differenceResult.state : differenceResult.intermediate_state;
updatesState.seq = nextState.seq;
updatesState.pts = nextState.pts;
updatesState.date = nextState.date;
} else {
updatesState.pts = differenceResult.pts;
updatesState.date = (Date.now() / 1000 | 0) + serverTimeManager.serverTimeOffset;
delete updatesState.seq;
3 years ago
this.channelStates = {};
this.log.warn('getDifference:', differenceResult._);
rootScope.dispatchEvent('state_cleared');
}
5 years ago
// this.log('apply diff', updatesState.seq, updatesState.pts)
5 years ago
if(differenceResult._ === 'updates.differenceSlice') {
return this.getDifference();
5 years ago
} else {
this.debug && this.log.debug('finished get diff');
5 years ago
}
});
if(!wasSyncing) {
this.justAName(updatesState, promise);
}
return promise;
5 years ago
}
private getChannelDifference(channelId: number): Promise<void> {
const channelState = this.getChannelState(channelId);
const wasSyncing = channelState.syncLoading;
if(!wasSyncing) {
5 years ago
channelState.pendingPtsUpdates = [];
}
5 years ago
if(channelState.syncPending) {
clearTimeout(channelState.syncPending.timeout);
4 years ago
channelState.syncPending = null;
5 years ago
}
//this.log.trace('Get channel diff', appChatsManager.getChat(channelId), channelState.pts);
const promise = apiManager.invokeApi('updates.getChannelDifference', {
channel: appChatsManager.getChannelInput(channelId),
5 years ago
filter: {_: 'channelMessagesFilterEmpty'},
pts: channelState.pts,
limit: 30
}, {timeout: 0x7fffffff}).then((differenceResult) => {
this.debug && this.log.debug('Get channel diff result', differenceResult)
channelState.pts = 'pts' in differenceResult ? differenceResult.pts : undefined;
5 years ago
if(differenceResult._ === 'updates.channelDifferenceEmpty') {
this.debug && this.log.debug('apply channel empty diff', differenceResult);
return;
5 years ago
}
if(differenceResult._ === 'updates.channelDifferenceTooLong') {
this.debug && this.log.debug('channel diff too long', differenceResult);
delete this.channelStates[channelId];
this.saveUpdate({_: 'updateChannelReload', channel_id: channelId});
return;
5 years ago
}
appUsersManager.saveApiUsers(differenceResult.users);
appChatsManager.saveApiChats(differenceResult.chats);
// Should be first because of updateMessageID
this.debug && this.log.debug('applying', differenceResult.other_updates.length, 'channel other updates');
differenceResult.other_updates.forEach((update) => {
5 years ago
this.saveUpdate(update);
});
this.debug && this.log.debug('applying', differenceResult.new_messages.length, 'channel new messages');
differenceResult.new_messages.forEach((apiMessage) => {
5 years ago
this.saveUpdate({
_: 'updateNewChannelMessage',
message: apiMessage,
pts: channelState.pts,
pts_count: 0
});
});
this.debug && this.log.debug('apply channel diff', channelState.pts);
5 years ago
if(differenceResult._ === 'updates.channelDifference' &&
5 years ago
!differenceResult.pFlags['final']) {
return this.getChannelDifference(channelId);
5 years ago
} else {
this.debug && this.log.debug('finished channel get diff');
5 years ago
}
});
if(!wasSyncing) {
this.justAName(channelState, promise, channelId);
}
return promise;
}
private justAName(state: UpdatesState, promise: UpdatesState['syncLoading'], channelId?: number) {
state.syncLoading = promise;
rootScope.dispatchEvent('state_synchronizing', channelId);
promise.then(() => {
state.syncLoading = null;
rootScope.dispatchEvent('state_synchronized', channelId);
5 years ago
}, () => {
state.syncLoading = null;
5 years ago
});
}
public addChannelState(channelId: number, pts: number) {
5 years ago
if(!pts) {
throw new Error('Add channel state without pts ' + channelId);
5 years ago
}
if(!(channelId in this.channelStates)) {
this.channelStates[channelId] = {
4 years ago
pts,
5 years ago
pendingPtsUpdates: [],
4 years ago
syncPending: null,
syncLoading: null
5 years ago
};
5 years ago
return true;
}
5 years ago
return false;
}
3 years ago
public getChannelState(channelId: number, pts?: number) {
if(this.channelStates[channelId] === undefined) {
this.addChannelState(channelId, pts);
5 years ago
}
return this.channelStates[channelId];
5 years ago
}
private processUpdate(update: Update, options: Partial<{
4 years ago
date: number,
seq: number,
seqStart: number/* ,
ignoreSyncLoading: boolean */
4 years ago
}> = {}) {
let channelId = 0;
5 years ago
switch(update._) {
case 'updateNewChannelMessage':
case 'updateEditChannelMessage':
channelId = -appPeersManager.getPeerId(update.message.peer_id);
5 years ago
break;
/* case 'updateDeleteChannelMessages':
channelId = update.channel_id;
break; */
5 years ago
case 'updateChannelTooLong':
channelId = update.channel_id;
if(!(channelId in this.channelStates)) {
5 years ago
return false;
}
break;
default:
if('channel_id' in update) {
channelId = update.channel_id;
}
break;
5 years ago
}
const {pts, pts_count} = update as Update.updateNewMessage;
const curState = channelId ? this.getChannelState(channelId, pts) : this.updatesState;
5 years ago
// this.log.log('process', channelId, curState.pts, update)
5 years ago
if(curState.syncLoading/* && !options.ignoreSyncLoading */) {
5 years ago
return false;
}
if(update._ === 'updateChannelTooLong') {
5 years ago
if(!curState.lastPtsUpdateTime ||
4 years ago
curState.lastPtsUpdateTime < (Date.now() - SYNC_DELAY)) {
// this.log.trace('channel too long, get diff', channelId, update)
this.getChannelDifference(channelId);
5 years ago
}
return false;
}
if(update._ === 'updateNewMessage' ||
update._ === 'updateEditMessage' ||
update._ === 'updateNewChannelMessage' ||
update._ === 'updateEditChannelMessage') {
const message = update.message as Message.message;
const toPeerId = appPeersManager.getPeerId(message.peer_id);
const fwdHeader: MessageFwdHeader.messageFwdHeader = message.fwd_from || {} as any;
let reason: string;
if(message.from_id && !appUsersManager.hasUser(appPeersManager.getPeerId(message.from_id), message.pFlags.post/* || channelId*/) && (reason = 'author') ||
fwdHeader.from_id && !appUsersManager.hasUser(appPeersManager.getPeerId(fwdHeader.from_id), !!(fwdHeader.from_id as Peer.peerChannel).channel_id) && (reason = 'fwdAuthor') ||
(fwdHeader.from_id as Peer.peerChannel)?.channel_id && !appChatsManager.hasChat((fwdHeader.from_id as Peer.peerChannel).channel_id, true) && (reason = 'fwdChannel') ||
toPeerId > 0 && !appUsersManager.hasUser(toPeerId) && (reason = 'toPeer User') ||
toPeerId < 0 && !appChatsManager.hasChat(-toPeerId) && (reason = 'toPeer Chat')) {
this.log.warn('Not enough data for message update', toPeerId, reason, message);
if(channelId && appChatsManager.hasChat(channelId)) {
this.getChannelDifference(channelId);
5 years ago
} else {
this.forceGetDifference();
}
return false;
}
} else if(channelId && !appChatsManager.hasChat(channelId)) {
// this.log.log('skip update, missing channel', channelId, update)
5 years ago
return false;
}
4 years ago
let popPts: boolean;
let popSeq: boolean;
5 years ago
if(pts) {
const newPts = curState.pts + (pts_count || 0);
if(newPts < pts) {
this.debug && this.log.warn('Pts hole', curState, update, channelId && appChatsManager.getChat(channelId));
curState.pendingPtsUpdates.push(update as Update.updateNewMessage);
if(!curState.syncPending && !curState.syncLoading) {
5 years ago
curState.syncPending = {
4 years ago
timeout: window.setTimeout(() => {
curState.syncPending = null;
if(curState.syncLoading) {
return;
}
if(channelId) {
this.getChannelDifference(channelId);
5 years ago
} else {
this.getDifference();
}
}, SYNC_DELAY)
};
5 years ago
}
curState.syncPending.ptsAwaiting = true;
return false;
}
if(pts > curState.pts) {
curState.pts = pts;
5 years ago
popPts = true;
curState.lastPtsUpdateTime = Date.now();
} else if(pts_count) {
// this.log.warn('Duplicate update', update)
5 years ago
return false;
}
if(channelId && options.date && this.updatesState.date < options.date) {
5 years ago
this.updatesState.date = options.date;
}
} else if(!channelId && options.seq > 0) {
4 years ago
const seq = options.seq;
const seqStart = options.seqStart || seq;
5 years ago
if(seqStart !== curState.seq + 1) {
5 years ago
if(seqStart > curState.seq) {
this.debug && this.log.warn('Seq hole', curState, curState.syncPending && curState.syncPending.seqAwaiting);
5 years ago
if(curState.pendingSeqUpdates[seqStart] === undefined) {
4 years ago
curState.pendingSeqUpdates[seqStart] = {seq, date: options.date, updates: []};
5 years ago
}
curState.pendingSeqUpdates[seqStart].updates.push(update);
if(!curState.syncPending) {
curState.syncPending = {
4 years ago
timeout: window.setTimeout(() => {
curState.syncPending = null;
if(curState.syncLoading) {
return;
}
5 years ago
this.getDifference();
}, SYNC_DELAY)
};
5 years ago
}
if(!curState.syncPending.seqAwaiting ||
curState.syncPending.seqAwaiting < seqStart) {
curState.syncPending.seqAwaiting = seqStart;
}
return false;
}
}
if(curState.seq !== seq) {
5 years ago
curState.seq = seq;
if(options.date && curState.date < options.date) {
curState.date = options.date;
}
popSeq = true;
}
}
this.saveUpdate(update);
if(popPts) {
this.popPendingPtsUpdate(channelId);
5 years ago
} else if(popSeq) {
this.popPendingSeqUpdate();
}
}
public saveUpdate(update: Update) {
//this.debug && this.log('saveUpdate', update);
rootScope.dispatchEvent(update._, update as any);
5 years ago
}
public attach() {
if(this.attached) return;
//return;
4 years ago
this.log('attach');
this.attached = true;
appStateManager.getState().then(_state => {
const state = _state.updates;
4 years ago
//rootScope.broadcast('state_synchronizing');
if(!state || !state.pts || !state.date || !state.seq) {
4 years ago
this.log('will get new state');
this.updatesState.syncLoading = new Promise((resolve) => {
apiManager.invokeApi('updates.getState', {}, {noErrorBox: true}).then((stateResult) => {
this.updatesState.seq = stateResult.seq;
this.updatesState.pts = stateResult.pts;
this.updatesState.date = stateResult.date;
this.saveUpdatesState();
//setTimeout(() => {
this.updatesState.syncLoading = null;
resolve();
//rootScope.broadcast('state_synchronized');
//}, 1000);
// ! for testing
// updatesState.seq = 1
// updatesState.pts = stateResult.pts - 5000
// updatesState.date = 1
// getDifference()
});
});
} else {
4 years ago
// ! for testing
/* state.seq = 1;
4 years ago
state.pts = state.pts - 15;
4 years ago
state.date = 1; */
// state.pts -= 100;
4 years ago
Object.assign(this.updatesState, state);
4 years ago
this.log('will get difference', Object.assign({}, state));
4 years ago
4 years ago
this.getDifference(true)/* .finally(() => {
if(this.updatesState.syncLoading) {
rootScope.broadcast('state_synchronizing');
}
}) */;
}
4 years ago
apiManager.setUpdatesProcessor(this.processUpdateMessage);
// this.updatesState.syncLoading.then(() => {
4 years ago
this.setProxy();
// });
});
5 years ago
}
}
const apiUpdatesManager = new ApiUpdatesManager();
MOUNT_CLASS_TO.apiUpdatesManager = apiUpdatesManager;
export default apiUpdatesManager