Browse Source

Refactor socket

master
Eduard Kuzmenko 4 years ago
parent
commit
641c50ae82
  1. 2
      src/components/animationIntersector.ts
  2. 2
      src/components/appMediaPlaybackController.ts
  3. 2
      src/components/appMediaViewer.ts
  4. 1
      src/components/appMediaViewerNew.ts
  5. 3
      src/components/chat/bubbles.ts
  6. 2
      src/components/emoticonsDropdown/index.ts
  7. 1
      src/components/lazyLoadQueue.ts
  8. 3
      src/components/misc.ts
  9. 2
      src/components/sidebarLeft/index.ts
  10. 2
      src/components/sidebarRight/index.ts
  11. 9
      src/config/app.ts
  12. 16
      src/config/database.ts
  13. 35
      src/config/debug.ts
  14. 9
      src/config/modes.ts
  15. 2
      src/countries.ts
  16. 2
      src/helpers/blur.ts
  17. 2
      src/helpers/date.ts
  18. 2
      src/helpers/dom.ts
  19. 2
      src/helpers/mediaSizes.ts
  20. 2
      src/hooks/useHeavyAnimationCheck.ts
  21. 2
      src/lib/appManagers/apiUpdatesManager.ts
  22. 2
      src/lib/appManagers/appChatsManager.ts
  23. 3
      src/lib/appManagers/appDialogsManager.ts
  24. 2
      src/lib/appManagers/appDocsManager.ts
  25. 2
      src/lib/appManagers/appDraftsManager.ts
  26. 2
      src/lib/appManagers/appImManager.ts
  27. 2
      src/lib/appManagers/appMessagesManager.ts
  28. 2
      src/lib/appManagers/appPeersManager.ts
  29. 2
      src/lib/appManagers/appPhotosManager.ts
  30. 2
      src/lib/appManagers/appPollsManager.ts
  31. 2
      src/lib/appManagers/appPrivacyManager.ts
  32. 4
      src/lib/appManagers/appStateManager.ts
  33. 2
      src/lib/appManagers/appStickersManager.ts
  34. 3
      src/lib/appManagers/appUsersManager.ts
  35. 2
      src/lib/cacheStorage.ts
  36. 2
      src/lib/config.ts
  37. 1
      src/lib/cropper.ts
  38. 3
      src/lib/crypto/cryptoworker.ts
  39. 2
      src/lib/idb.ts
  40. 2
      src/lib/logger.ts
  41. 2
      src/lib/lottieLoader.ts
  42. 6
      src/lib/mtproto/apiFileManager.ts
  43. 3
      src/lib/mtproto/apiManager.ts
  44. 2
      src/lib/mtproto/authorizer.ts
  45. 11
      src/lib/mtproto/dcConfigurator.ts
  46. 5
      src/lib/mtproto/mtproto.ts
  47. 63
      src/lib/mtproto/mtproto_config.ts
  48. 3
      src/lib/mtproto/mtprotoworker.ts
  49. 142
      src/lib/mtproto/networker.ts
  50. 2
      src/lib/mtproto/passwordManager.ts
  51. 2
      src/lib/mtproto/referenceDatabase.ts
  52. 2
      src/lib/mtproto/timeManager.ts
  53. 2
      src/lib/mtproto/tl_utils.ts
  54. 5
      src/lib/mtproto/transports/http.ts
  55. 220
      src/lib/mtproto/transports/tcpObfuscated.ts
  56. 4
      src/lib/mtproto/transports/transport.ts
  57. 224
      src/lib/mtproto/transports/websocket.ts
  58. 2
      src/lib/opusDecodeController.ts
  59. 2
      src/lib/richtextprocessor.ts
  60. 4
      src/lib/rootScope.ts
  61. 3
      src/lib/sessionStorage.ts
  62. 2
      src/lib/storage.ts
  63. 2
      src/lib/webp/webpWorkerController.ts
  64. 1
      src/pages/pageAuthCode.ts
  65. 3
      src/pages/pageSignIn.ts
  66. 2
      src/pages/pageSignQR.ts
  67. 2
      src/pages/pagesManager.ts

2
src/components/animationIntersector.ts

@ -1,8 +1,8 @@
import { isInDOM } from "../helpers/dom"; import { isInDOM } from "../helpers/dom";
import { RLottiePlayer } from "../lib/lottieLoader"; import { RLottiePlayer } from "../lib/lottieLoader";
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config";
import rootScope from "../lib/rootScope"; import rootScope from "../lib/rootScope";
import { isSafari } from "../helpers/userAgent"; import { isSafari } from "../helpers/userAgent";
import { MOUNT_CLASS_TO } from "../config/debug";
export interface AnimationItem { export interface AnimationItem {
el: HTMLElement, el: HTMLElement,

2
src/components/appMediaPlaybackController.ts

@ -3,8 +3,8 @@ import appMessagesManager from "../lib/appManagers/appMessagesManager";
import appDocsManager, {MyDocument} from "../lib/appManagers/appDocsManager"; import appDocsManager, {MyDocument} from "../lib/appManagers/appDocsManager";
import { CancellablePromise, deferredPromise } from "../helpers/cancellablePromise"; import { CancellablePromise, deferredPromise } from "../helpers/cancellablePromise";
import { isSafari } from "../helpers/userAgent"; import { isSafari } from "../helpers/userAgent";
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config";
import { isInDOM } from "../helpers/dom"; import { isInDOM } from "../helpers/dom";
import { MOUNT_CLASS_TO } from "../config/debug";
// TODO: если удалить сообщение, и при этом аудио будет играть - оно не остановится, и можно будет по нему перейти вникуда // TODO: если удалить сообщение, и при этом аудио будет играть - оно не остановится, и можно будет по нему перейти вникуда

2
src/components/appMediaViewer.ts

@ -27,7 +27,7 @@ import appSidebarRight, { AppSidebarRight } from "./sidebarRight";
import SwipeHandler from "./swipeHandler"; import SwipeHandler from "./swipeHandler";
import { months, ONE_DAY } from "../helpers/date"; import { months, ONE_DAY } from "../helpers/date";
import { SearchSuperContext } from "./appSearchSuper."; import { SearchSuperContext } from "./appSearchSuper.";
import { DEBUG } from "../lib/mtproto/mtproto_config"; import DEBUG from "../config/debug";
// TODO: масштабирование картинок (не SVG) при ресайзе, и правильный возврат на исходную позицию // TODO: масштабирование картинок (не SVG) при ресайзе, и правильный возврат на исходную позицию
// TODO: картинки "обрезаются" если возвращаются или появляются с места, где есть их перекрытие (топбар, поле ввода) // TODO: картинки "обрезаются" если возвращаются или появляются с места, где есть их перекрытие (топбар, поле ввода)

1
src/components/appMediaViewerNew.ts

@ -27,7 +27,6 @@ import appSidebarRight, { AppSidebarRight } from "./sidebarRight";
import SwipeHandler from "./swipeHandler"; import SwipeHandler from "./swipeHandler";
import { months, ONE_DAY } from "../helpers/date"; import { months, ONE_DAY } from "../helpers/date";
import { SearchSuperContext } from "./appSearchSuper."; import { SearchSuperContext } from "./appSearchSuper.";
import { DEBUG } from "../lib/mtproto/mtproto_config";
import { PhotoSize } from "../layer"; import { PhotoSize } from "../layer";
// TODO: масштабирование картинок (не SVG) при ресайзе, и правильный возврат на исходную позицию // TODO: масштабирование картинок (не SVG) при ресайзе, и правильный возврат на исходную позицию

3
src/components/chat/bubbles.ts

@ -38,12 +38,13 @@ import ListenerSetter from "../../helpers/listenerSetter";
import PollElement from "../poll"; import PollElement from "../poll";
import AudioElement from "../audio"; import AudioElement from "../audio";
import { Message, MessageEntity, MessageReplyHeader } from "../../layer"; import { Message, MessageEntity, MessageReplyHeader } from "../../layer";
import { DEBUG, REPLIES_PEER_ID } from "../../lib/mtproto/mtproto_config"; import { REPLIES_PEER_ID } from "../../lib/mtproto/mtproto_config";
import { FocusDirection } from "../../helpers/fastSmoothScroll"; import { FocusDirection } from "../../helpers/fastSmoothScroll";
import useHeavyAnimationCheck, { getHeavyAnimationPromise, dispatchHeavyAnimationEvent } from "../../hooks/useHeavyAnimationCheck"; import useHeavyAnimationCheck, { getHeavyAnimationPromise, dispatchHeavyAnimationEvent } from "../../hooks/useHeavyAnimationCheck";
import { fastRaf } from "../../helpers/schedulers"; import { fastRaf } from "../../helpers/schedulers";
import { deferredPromise } from "../../helpers/cancellablePromise"; import { deferredPromise } from "../../helpers/cancellablePromise";
import RepliesElement from "./replies"; import RepliesElement from "./replies";
import DEBUG from "../../config/debug";
const USE_MEDIA_TAILS = false; const USE_MEDIA_TAILS = false;
const IGNORE_ACTIONS = ['messageActionHistoryClear']; const IGNORE_ACTIONS = ['messageActionHistoryClear'];

2
src/components/emoticonsDropdown/index.ts

@ -1,7 +1,6 @@
import { isTouchSupported } from "../../helpers/touchSupport"; import { isTouchSupported } from "../../helpers/touchSupport";
import appChatsManager from "../../lib/appManagers/appChatsManager"; import appChatsManager from "../../lib/appManagers/appChatsManager";
import appImManager from "../../lib/appManagers/appImManager"; import appImManager from "../../lib/appManagers/appImManager";
import { MOUNT_CLASS_TO } from "../../lib/mtproto/mtproto_config";
import rootScope from "../../lib/rootScope"; import rootScope from "../../lib/rootScope";
import { blurActiveElement, findUpClassName, findUpTag, whichChild } from "../../helpers/dom"; import { blurActiveElement, findUpClassName, findUpTag, whichChild } from "../../helpers/dom";
import animationIntersector from "../animationIntersector"; import animationIntersector from "../animationIntersector";
@ -14,6 +13,7 @@ import EmojiTab from "./tabs/emoji";
import GifsTab from "./tabs/gifs"; import GifsTab from "./tabs/gifs";
import StickersTab from "./tabs/stickers"; import StickersTab from "./tabs/stickers";
import { pause } from "../../helpers/schedulers"; import { pause } from "../../helpers/schedulers";
import { MOUNT_CLASS_TO } from "../../config/debug";
export const EMOTICONSSTICKERGROUP = 'emoticons-dropdown'; export const EMOTICONSSTICKERGROUP = 'emoticons-dropdown';

1
src/components/lazyLoadQueue.ts

@ -1,7 +1,6 @@
import { debounce } from "../helpers/schedulers"; import { debounce } from "../helpers/schedulers";
import { logger, LogLevels } from "../lib/logger"; import { logger, LogLevels } from "../lib/logger";
import VisibilityIntersector, { OnVisibilityChange } from "./visibilityIntersector"; import VisibilityIntersector, { OnVisibilityChange } from "./visibilityIntersector";
import { DEBUG } from "../lib/mtproto/mtproto_config";
import { findAndSpliceAll } from "../helpers/array"; import { findAndSpliceAll } from "../helpers/array";
type LazyLoadElementBase = { type LazyLoadElementBase = {

3
src/components/misc.ts

@ -1,11 +1,10 @@
import { MOUNT_CLASS_TO } from "../config/debug";
import Countries, { Country, PhoneCodesMain } from "../countries"; import Countries, { Country, PhoneCodesMain } from "../countries";
import { cancelEvent, CLICK_EVENT_NAME } from "../helpers/dom"; import { cancelEvent, CLICK_EVENT_NAME } from "../helpers/dom";
import ListenerSetter from "../helpers/listenerSetter"; import ListenerSetter from "../helpers/listenerSetter";
import mediaSizes from "../helpers/mediaSizes"; import mediaSizes from "../helpers/mediaSizes";
import { isTouchSupported } from "../helpers/touchSupport"; import { isTouchSupported } from "../helpers/touchSupport";
import { isApple } from "../helpers/userAgent"; import { isApple } from "../helpers/userAgent";
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config";
import { getHeavyAnimationPromise } from "../hooks/useHeavyAnimationCheck";
export const loadedURLs: {[url: string]: boolean} = {}; export const loadedURLs: {[url: string]: boolean} = {};
const set = (elem: HTMLElement | HTMLImageElement | SVGImageElement | HTMLVideoElement, url: string) => { const set = (elem: HTMLElement | HTMLImageElement | SVGImageElement | HTMLVideoElement, url: string) => {

2
src/components/sidebarLeft/index.ts

@ -4,7 +4,6 @@ import appImManager from "../../lib/appManagers/appImManager";
import appPeersManager from "../../lib/appManagers/appPeersManager"; import appPeersManager from "../../lib/appManagers/appPeersManager";
import appStateManager from "../../lib/appManagers/appStateManager"; import appStateManager from "../../lib/appManagers/appStateManager";
import appUsersManager from "../../lib/appManagers/appUsersManager"; import appUsersManager from "../../lib/appManagers/appUsersManager";
import { MOUNT_CLASS_TO } from "../../lib/mtproto/mtproto_config";
import rootScope from "../../lib/rootScope"; import rootScope from "../../lib/rootScope";
import { attachClickEvent, findUpClassName, findUpTag } from "../../helpers/dom"; import { attachClickEvent, findUpClassName, findUpTag } from "../../helpers/dom";
import { SearchGroup } from "../appSearch"; import { SearchGroup } from "../appSearch";
@ -30,6 +29,7 @@ import AppSearchSuper from "../appSearchSuper.";
import { DateData, fillTipDates } from "../../helpers/date"; import { DateData, fillTipDates } from "../../helpers/date";
import AppGeneralSettingsTab from "./tabs/generalSettings"; import AppGeneralSettingsTab from "./tabs/generalSettings";
import AppPrivacyAndSecurityTab from "./tabs/privacyAndSecurity"; import AppPrivacyAndSecurityTab from "./tabs/privacyAndSecurity";
import { MOUNT_CLASS_TO } from "../../config/debug";
const contactsTab = new AppContactsTab(); const contactsTab = new AppContactsTab();
const archivedTab = new AppArchivedTab(); const archivedTab = new AppArchivedTab();

2
src/components/sidebarRight/index.ts

@ -7,10 +7,10 @@ import mediaSizes, { ScreenSize } from "../../helpers/mediaSizes";
import AppPrivateSearchTab from "./tabs/search"; import AppPrivateSearchTab from "./tabs/search";
import AppSharedMediaTab from "./tabs/sharedMedia"; import AppSharedMediaTab from "./tabs/sharedMedia";
//import AppForwardTab from "./tabs/forward"; //import AppForwardTab from "./tabs/forward";
import { MOUNT_CLASS_TO } from "../../lib/mtproto/mtproto_config";
import { pause } from "../../helpers/schedulers"; import { pause } from "../../helpers/schedulers";
import rootScope from "../../lib/rootScope"; import rootScope from "../../lib/rootScope";
import { dispatchHeavyAnimationEvent } from "../../hooks/useHeavyAnimationCheck"; import { dispatchHeavyAnimationEvent } from "../../hooks/useHeavyAnimationCheck";
import { MOUNT_CLASS_TO } from "../../config/debug";
export const RIGHT_COLUMN_ACTIVE_CLASSNAME = 'is-right-column-shown'; export const RIGHT_COLUMN_ACTIVE_CLASSNAME = 'is-right-column-shown';

9
src/config/app.ts

@ -0,0 +1,9 @@
const App = {
id: 1025907,
hash: '452b0359b988148995f22ff0f4229750',
version: '0.4.0',
domains: [] as string[],
baseDcId: 2
};
export default App;

16
src/config/database.ts

@ -0,0 +1,16 @@
import { IDBStore } from "../lib/idb";
import Modes from "./modes";
export type DatabaseStoreName = 'session' | 'stickerSets';
export type DatabaseStore = Omit<IDBStore, 'name'> & {name: DatabaseStoreName};
const Database = {
name: 'tweb' + (Modes.test ? '_test' : ''),
version: 5,
stores: [{
name: 'session'
}, {
name: 'stickerSets'
}] as DatabaseStore[],
};
export default Database;

35
src/config/debug.ts

@ -0,0 +1,35 @@
import Modes from "./modes";
export const DEBUG = process.env.NODE_ENV !== 'production' || Modes.debug;
export const MOUNT_CLASS_TO: any = DEBUG ? (typeof(window) !== 'undefined' ? window : self) : null;
export default DEBUG;
export const superDebug = (object: any, key: string) => {
var d = object[key];
var beforeStr = '', afterStr = '';
for(var r of d) {
beforeStr += r.before.hex + '\n';
afterStr += r.after.hex + '\n';
}
beforeStr = beforeStr.trim();
afterStr = afterStr.trim();
//var beforeStr = d.map(r => r.before.hex).join('\n');
//var afterStr = d.map(r => r.after.hex).join('\n');
var dada = (name: string, str: string) => {
var a = document.createElement('a');
a.target = '_blank';
a.download = name + '.txt';
a.href = URL.createObjectURL(new Blob([str], {
type: 'text/plain'
}));
document.body.append(a);
a.click();
};
dada(key + '_' + 'before', beforeStr);
dada(key + '_' + 'after', afterStr);
}
MOUNT_CLASS_TO && (MOUNT_CLASS_TO.superDebug = superDebug);

9
src/config/modes.ts

@ -0,0 +1,9 @@
const Modes = {
test: location.search.indexOf('test=1') > 0/* || true */,
debug: location.search.indexOf('debug=1') > 0,
http: false, //location.search.indexOf('http=1') > 0,
ssl: true, // location.search.indexOf('ssl=1') > 0 || location.protocol === 'https:' && location.search.indexOf('ssl=0') === -1,
multipleConnections: true
};
export default Modes;

2
src/countries.ts

@ -1,4 +1,4 @@
import { MOUNT_CLASS_TO } from "./lib/mtproto/mtproto_config"; import { MOUNT_CLASS_TO } from "./config/debug";
export type Country = { export type Country = {
phoneCode: string, phoneCode: string,

2
src/helpers/blur.ts

@ -1,4 +1,4 @@
import { DEBUG } from '../lib/mtproto/mtproto_config'; import DEBUG from '../config/debug';
import fastBlur from '../vendor/fastBlur'; import fastBlur from '../vendor/fastBlur';
import pushHeavyTask from './heavyQueue'; import pushHeavyTask from './heavyQueue';

2
src/helpers/date.ts

@ -1,4 +1,4 @@
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config"; import { MOUNT_CLASS_TO } from "../config/debug";
export const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; export const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
export const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; export const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

2
src/helpers/dom.ts

@ -1,10 +1,10 @@
import { MessageEntity } from "../layer"; import { MessageEntity } from "../layer";
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config";
import RichTextProcessor from "../lib/richtextprocessor"; import RichTextProcessor from "../lib/richtextprocessor";
import ListenerSetter from "./listenerSetter"; import ListenerSetter from "./listenerSetter";
import { isTouchSupported } from "./touchSupport"; import { isTouchSupported } from "./touchSupport";
import { isApple } from "./userAgent"; import { isApple } from "./userAgent";
import rootScope from "../lib/rootScope"; import rootScope from "../lib/rootScope";
import { MOUNT_CLASS_TO } from "../config/debug";
/* export function isInDOM(element: Element, parentNode?: HTMLElement): boolean { /* export function isInDOM(element: Element, parentNode?: HTMLElement): boolean {
if(!element) { if(!element) {

2
src/helpers/mediaSizes.ts

@ -1,4 +1,4 @@
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config"; import { MOUNT_CLASS_TO } from "../config/debug";
import EventListenerBase from "./eventListenerBase"; import EventListenerBase from "./eventListenerBase";
type Size = Partial<{width: number, height: number}>; type Size = Partial<{width: number, height: number}>;

2
src/hooks/useHeavyAnimationCheck.ts

@ -6,7 +6,7 @@ import ListenerSetter from '../helpers/listenerSetter';
import { CancellablePromise, deferredPromise } from '../helpers/cancellablePromise'; import { CancellablePromise, deferredPromise } from '../helpers/cancellablePromise';
import { pause } from '../helpers/schedulers'; import { pause } from '../helpers/schedulers';
import rootScope from '../lib/rootScope'; import rootScope from '../lib/rootScope';
import { DEBUG } from '../lib/mtproto/mtproto_config'; import DEBUG from '../config/debug';
const ANIMATION_START_EVENT = 'event-heavy-animation-start'; const ANIMATION_START_EVENT = 'event-heavy-animation-start';
const ANIMATION_END_EVENT = 'event-heavy-animation-end'; const ANIMATION_END_EVENT = 'event-heavy-animation-end';

2
src/lib/appManagers/apiUpdatesManager.ts

@ -1,7 +1,7 @@
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import { MOUNT_CLASS_TO } from '../../config/debug';
import { logger, LogLevels } from '../logger'; import { logger, LogLevels } from '../logger';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config';
import rootScope from '../rootScope'; import rootScope from '../rootScope';
//import networkerFactory from '../mtproto/networkerFactory'; //import networkerFactory from '../mtproto/networkerFactory';
import appChatsManager from "./appChatsManager"; import appChatsManager from "./appChatsManager";

2
src/lib/appManagers/appChatsManager.ts

@ -1,8 +1,8 @@
import { MOUNT_CLASS_TO } from "../../config/debug";
import { numberThousandSplitter } from "../../helpers/number"; import { numberThousandSplitter } from "../../helpers/number";
import { isObject, safeReplaceObject, copy } from "../../helpers/object"; import { isObject, safeReplaceObject, copy } from "../../helpers/object";
import { ChatAdminRights, ChatBannedRights, ChatFull, ChatParticipants, InputChannel, InputChatPhoto, InputFile, InputPeer, SendMessageAction, Updates } from "../../layer"; import { ChatAdminRights, ChatBannedRights, ChatFull, ChatParticipants, InputChannel, InputChatPhoto, InputFile, InputPeer, SendMessageAction, Updates } from "../../layer";
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
import rootScope from "../rootScope"; import rootScope from "../rootScope";
import apiUpdatesManager from "./apiUpdatesManager"; import apiUpdatesManager from "./apiUpdatesManager";

3
src/lib/appManagers/appDialogsManager.ts

@ -19,13 +19,14 @@ import {MyDialogFilter as DialogFilter} from "../storages/filters";
import appPeersManager from './appPeersManager'; import appPeersManager from './appPeersManager';
import appStateManager from "./appStateManager"; import appStateManager from "./appStateManager";
import appUsersManager, { User } from "./appUsersManager"; import appUsersManager, { User } from "./appUsersManager";
import { App, DEBUG, MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import Button from "../../components/button"; import Button from "../../components/button";
import SetTransition from "../../components/singleTransition"; import SetTransition from "../../components/singleTransition";
import sessionStorage from '../sessionStorage'; import sessionStorage from '../sessionStorage';
import apiUpdatesManager from "./apiUpdatesManager"; import apiUpdatesManager from "./apiUpdatesManager";
import appDraftsManager, { MyDraftMessage } from "./appDraftsManager"; import appDraftsManager, { MyDraftMessage } from "./appDraftsManager";
import ProgressivePreloader from "../../components/preloader"; import ProgressivePreloader from "../../components/preloader";
import App from "../../config/app";
import DEBUG, { MOUNT_CLASS_TO } from "../../config/debug";
type DialogDom = { type DialogDom = {
avatarEl: AvatarElement, avatarEl: AvatarElement,

2
src/lib/appManagers/appDocsManager.ts

@ -1,7 +1,6 @@
import { FileURLType, getFileNameByLocation, getFileURL } from '../../helpers/fileName'; import { FileURLType, getFileNameByLocation, getFileURL } from '../../helpers/fileName';
import { safeReplaceArrayInObject, defineNotNumerableProperties, isObject } from '../../helpers/object'; import { safeReplaceArrayInObject, defineNotNumerableProperties, isObject } from '../../helpers/object';
import { Document, InputFileLocation, PhotoSize } from '../../layer'; import { Document, InputFileLocation, PhotoSize } from '../../layer';
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config';
import referenceDatabase, { ReferenceContext } from '../mtproto/referenceDatabase'; import referenceDatabase, { ReferenceContext } from '../mtproto/referenceDatabase';
import opusDecodeController from '../opusDecodeController'; import opusDecodeController from '../opusDecodeController';
import { RichTextProcessor } from '../richtextprocessor'; import { RichTextProcessor } from '../richtextprocessor';
@ -10,6 +9,7 @@ import appDownloadManager, { DownloadBlob } from './appDownloadManager';
import appPhotosManager from './appPhotosManager'; import appPhotosManager from './appPhotosManager';
import blur from '../../helpers/blur'; import blur from '../../helpers/blur';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from '../../config/debug';
export type MyDocument = Document.document; export type MyDocument = Document.document;

2
src/lib/appManagers/appDraftsManager.ts

@ -1,4 +1,3 @@
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import rootScope from "../rootScope"; import rootScope from "../rootScope";
import appPeersManager from "./appPeersManager"; import appPeersManager from "./appPeersManager";
import appMessagesManager from "./appMessagesManager"; import appMessagesManager from "./appMessagesManager";
@ -11,6 +10,7 @@ import { tsNow } from "../../helpers/date";
import { deepEqual } from "../../helpers/object"; import { deepEqual } from "../../helpers/object";
import appStateManager from "./appStateManager"; import appStateManager from "./appStateManager";
import { isObject } from "../mtproto/bin_utils"; import { isObject } from "../mtproto/bin_utils";
import { MOUNT_CLASS_TO } from "../../config/debug";
export type MyDraftMessage = DraftMessage.draftMessage; export type MyDraftMessage = DraftMessage.draftMessage;

2
src/lib/appManagers/appImManager.ts

@ -5,7 +5,6 @@ import appSidebarRight, { AppSidebarRight, RIGHT_COLUMN_ACTIVE_CLASSNAME } from
import mediaSizes, { ScreenSize } from '../../helpers/mediaSizes'; import mediaSizes, { ScreenSize } from '../../helpers/mediaSizes';
import { logger, LogLevels } from "../logger"; import { logger, LogLevels } from "../logger";
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config';
import rootScope from '../rootScope'; import rootScope from '../rootScope';
import apiUpdatesManager from './apiUpdatesManager'; import apiUpdatesManager from './apiUpdatesManager';
import appUsersManager from "./appUsersManager"; import appUsersManager from "./appUsersManager";
@ -36,6 +35,7 @@ import sessionStorage from '../sessionStorage';
import { renderImageFromUrl } from '../../components/misc'; import { renderImageFromUrl } from '../../components/misc';
import appDownloadManager from './appDownloadManager'; import appDownloadManager from './appDownloadManager';
import appStateManager, { AppStateManager } from './appStateManager'; import appStateManager, { AppStateManager } from './appStateManager';
import { MOUNT_CLASS_TO } from '../../config/debug';
//console.log('appImManager included33!'); //console.log('appImManager included33!');

2
src/lib/appManagers/appMessagesManager.ts

@ -13,7 +13,6 @@ import { logger, LogLevels } from "../logger";
import type { ApiFileManager } from '../mtproto/apiFileManager'; import type { ApiFileManager } from '../mtproto/apiFileManager';
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO, DEBUG } from "../mtproto/mtproto_config";
import referenceDatabase, { ReferenceContext } from "../mtproto/referenceDatabase"; import referenceDatabase, { ReferenceContext } from "../mtproto/referenceDatabase";
import serverTimeManager from "../mtproto/serverTimeManager"; import serverTimeManager from "../mtproto/serverTimeManager";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
@ -36,6 +35,7 @@ import appDraftsManager from "./appDraftsManager";
import pushHeavyTask from "../../helpers/heavyQueue"; import pushHeavyTask from "../../helpers/heavyQueue";
import { getFileNameByLocation } from "../../helpers/fileName"; import { getFileNameByLocation } from "../../helpers/fileName";
import appProfileManager from "./appProfileManager"; import appProfileManager from "./appProfileManager";
import DEBUG, { MOUNT_CLASS_TO } from "../../config/debug";
//console.trace('include'); //console.trace('include');
// TODO: если удалить сообщение в непрогруженном диалоге, то при обновлении, из-за стейта, последнего сообщения в чатлисте не будет // TODO: если удалить сообщение в непрогруженном диалоге, то при обновлении, из-за стейта, последнего сообщения в чатлисте не будет

2
src/lib/appManagers/appPeersManager.ts

@ -1,6 +1,6 @@
import { MOUNT_CLASS_TO } from "../../config/debug";
import { isObject } from "../../helpers/object"; import { isObject } from "../../helpers/object";
import { DialogPeer, InputDialogPeer, InputPeer, Peer } from "../../layer"; import { DialogPeer, InputDialogPeer, InputPeer, Peer } from "../../layer";
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
import rootScope from "../rootScope"; import rootScope from "../rootScope";
import appChatsManager from "./appChatsManager"; import appChatsManager from "./appChatsManager";

2
src/lib/appManagers/appPhotosManager.ts

@ -10,9 +10,9 @@ import { calcImageInBox } from "../../helpers/dom";
import { MyDocument } from "./appDocsManager"; import { MyDocument } from "./appDocsManager";
import appDownloadManager from "./appDownloadManager"; import appDownloadManager from "./appDownloadManager";
import appUsersManager from "./appUsersManager"; import appUsersManager from "./appUsersManager";
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import blur from "../../helpers/blur"; import blur from "../../helpers/blur";
import { renderImageFromUrl } from "../../components/misc"; import { renderImageFromUrl } from "../../components/misc";
import { MOUNT_CLASS_TO } from "../../config/debug";
export type MyPhoto = Photo.photo; export type MyPhoto = Photo.photo;

2
src/lib/appManagers/appPollsManager.ts

@ -1,8 +1,8 @@
import { MOUNT_CLASS_TO } from "../../config/debug";
import { copy } from "../../helpers/object"; import { copy } from "../../helpers/object";
import { InputMedia, MessageEntity } from "../../layer"; import { InputMedia, MessageEntity } from "../../layer";
import { logger, LogLevels } from "../logger"; import { logger, LogLevels } from "../logger";
import apiManager from "../mtproto/mtprotoworker"; import apiManager from "../mtproto/mtprotoworker";
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
import rootScope from "../rootScope"; import rootScope from "../rootScope";
import apiUpdatesManager from "./apiUpdatesManager"; import apiUpdatesManager from "./apiUpdatesManager";

2
src/lib/appManagers/appPrivacyManager.ts

@ -1,4 +1,4 @@
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config"; import { MOUNT_CLASS_TO } from "../../config/debug";
import { InputPrivacyKey, PrivacyRule } from "../../layer"; import { InputPrivacyKey, PrivacyRule } from "../../layer";
import apiManager from "../mtproto/mtprotoworker"; import apiManager from "../mtproto/mtprotoworker";
import appChatsManager from "./appChatsManager"; import appChatsManager from "./appChatsManager";

4
src/lib/appManagers/appStateManager.ts

@ -1,5 +1,5 @@
import type { Dialog } from './appMessagesManager'; import type { Dialog } from './appMessagesManager';
import { App, DEBUG, MOUNT_CLASS_TO, UserAuth } from '../mtproto/mtproto_config'; import { UserAuth } from '../mtproto/mtproto_config';
import EventListenerBase from '../../helpers/eventListenerBase'; import EventListenerBase from '../../helpers/eventListenerBase';
import rootScope from '../rootScope'; import rootScope from '../rootScope';
import sessionStorage from '../sessionStorage'; import sessionStorage from '../sessionStorage';
@ -12,6 +12,8 @@ import type DialogsStorage from '../storages/dialogs';
import type { AppDraftsManager } from './appDraftsManager'; import type { AppDraftsManager } from './appDraftsManager';
import { copy, setDeepProperty, validateInitObject } from '../../helpers/object'; import { copy, setDeepProperty, validateInitObject } from '../../helpers/object';
import { getHeavyAnimationPromise } from '../../hooks/useHeavyAnimationCheck'; import { getHeavyAnimationPromise } from '../../hooks/useHeavyAnimationCheck';
import App from '../../config/app';
import DEBUG, { MOUNT_CLASS_TO } from '../../config/debug';
const REFRESH_EVERY = 24 * 60 * 60 * 1000; // 1 day const REFRESH_EVERY = 24 * 60 * 60 * 1000; // 1 day
const STATE_VERSION = App.version; const STATE_VERSION = App.version;

2
src/lib/appManagers/appStickersManager.ts

@ -1,10 +1,10 @@
import { Document, InputFileLocation, InputStickerSet, MessagesAllStickers, MessagesFeaturedStickers, MessagesFoundStickerSets, MessagesRecentStickers, MessagesStickers, MessagesStickerSet, PhotoSize, StickerPack, StickerSet, StickerSetCovered } from '../../layer'; import { Document, InputFileLocation, InputStickerSet, MessagesAllStickers, MessagesFeaturedStickers, MessagesFoundStickerSets, MessagesRecentStickers, MessagesStickers, MessagesStickerSet, PhotoSize, StickerPack, StickerSet, StickerSetCovered } from '../../layer';
import { Modify } from '../../types'; import { Modify } from '../../types';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config';
import rootScope from '../rootScope'; import rootScope from '../rootScope';
import appDocsManager from './appDocsManager'; import appDocsManager from './appDocsManager';
import AppStorage from '../storage'; import AppStorage from '../storage';
import { MOUNT_CLASS_TO } from '../../config/debug';
// TODO: если пак будет сохранён и потом обновлён, то недостающие стикеры не подгрузит // TODO: если пак будет сохранён и потом обновлён, то недостающие стикеры не подгрузит

3
src/lib/appManagers/appUsersManager.ts

@ -1,10 +1,11 @@
import { formatPhoneNumber } from "../../components/misc"; import { formatPhoneNumber } from "../../components/misc";
import { MOUNT_CLASS_TO } from "../../config/debug";
import { tsNow } from "../../helpers/date"; import { tsNow } from "../../helpers/date";
import { safeReplaceObject, isObject } from "../../helpers/object"; import { safeReplaceObject, isObject } from "../../helpers/object";
import { InputUser, Update, User as MTUser, UserStatus } from "../../layer"; import { InputUser, Update, User as MTUser, UserStatus } from "../../layer";
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO, REPLIES_PEER_ID } from "../mtproto/mtproto_config"; import { REPLIES_PEER_ID } from "../mtproto/mtproto_config";
import serverTimeManager from "../mtproto/serverTimeManager"; import serverTimeManager from "../mtproto/serverTimeManager";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
import rootScope from "../rootScope"; import rootScope from "../rootScope";

2
src/lib/cacheStorage.ts

@ -1,6 +1,6 @@
import Modes from '../config/modes';
import { blobConstruct } from '../helpers/blob'; import { blobConstruct } from '../helpers/blob';
import FileManager from './filemanager'; import FileManager from './filemanager';
import { Modes } from './mtproto/mtproto_config';
//import { MOUNT_CLASS_TO } from './mtproto/mtproto_config'; //import { MOUNT_CLASS_TO } from './mtproto/mtproto_config';
//import { logger } from './polyfill'; //import { logger } from './polyfill';

2
src/lib/config.ts

File diff suppressed because one or more lines are too long

1
src/lib/cropper.ts

@ -1,4 +1,3 @@
function resizeableImage(originalImage: HTMLImageElement, canvas?: HTMLCanvasElement) { function resizeableImage(originalImage: HTMLImageElement, canvas?: HTMLCanvasElement) {
let cropComponent: HTMLDivElement, let cropComponent: HTMLDivElement,
container: HTMLDivElement, container: HTMLDivElement,

3
src/lib/crypto/cryptoworker.ts

@ -1,4 +1,4 @@
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config'; import { MOUNT_CLASS_TO } from '../../config/debug';
import CryptoWorkerMethods from './crypto_methods'; import CryptoWorkerMethods from './crypto_methods';
type Task = { type Task = {
@ -126,5 +126,4 @@ class CryptoWorker extends CryptoWorkerMethods {
const cryptoWorker = new CryptoWorker(); const cryptoWorker = new CryptoWorker();
MOUNT_CLASS_TO && (MOUNT_CLASS_TO.CryptoWorker = cryptoWorker); MOUNT_CLASS_TO && (MOUNT_CLASS_TO.CryptoWorker = cryptoWorker);
//(window as any).CryptoWorker = cryptoWorker;
export default cryptoWorker; export default cryptoWorker;

2
src/lib/idb.ts

@ -1,6 +1,6 @@
import Database from '../config/database';
import { blobConstruct } from '../helpers/blob'; import { blobConstruct } from '../helpers/blob';
import { logger } from './logger'; import { logger } from './logger';
import { Database } from './mtproto/mtproto_config';
/** /**
* https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex * https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex

2
src/lib/logger.ts

@ -1,4 +1,4 @@
import { DEBUG } from "./mtproto/mtproto_config"; import DEBUG from "../config/debug";
export enum LogLevels { export enum LogLevels {
log = 1, log = 1,

2
src/lib/lottieLoader.ts

@ -1,12 +1,12 @@
import RLottieWorker from 'worker-loader!./rlottie/rlottie.worker'; import RLottieWorker from 'worker-loader!./rlottie/rlottie.worker';
import animationIntersector from "../components/animationIntersector"; import animationIntersector from "../components/animationIntersector";
import { MOUNT_CLASS_TO } from '../config/debug';
import EventListenerBase from "../helpers/eventListenerBase"; import EventListenerBase from "../helpers/eventListenerBase";
import mediaSizes from "../helpers/mediaSizes"; import mediaSizes from "../helpers/mediaSizes";
import { clamp } from '../helpers/number'; import { clamp } from '../helpers/number';
import { isAndroid, isApple, isAppleMobile, isSafari } from "../helpers/userAgent"; import { isAndroid, isApple, isAppleMobile, isSafari } from "../helpers/userAgent";
import { logger, LogLevels } from "./logger"; import { logger, LogLevels } from "./logger";
import apiManager from "./mtproto/mtprotoworker"; import apiManager from "./mtproto/mtprotoworker";
import { MOUNT_CLASS_TO } from "./mtproto/mtproto_config";
let convert = (value: number) => { let convert = (value: number) => {
return Math.round(Math.min(Math.max(value, 0), 1) * 255); return Math.round(Math.min(Math.max(value, 0), 1) * 255);

6
src/lib/mtproto/apiFileManager.ts

@ -1,3 +1,5 @@
import { MOUNT_CLASS_TO } from "../../config/debug";
import Modes from "../../config/modes";
import { CancellablePromise, deferredPromise } from "../../helpers/cancellablePromise"; import { CancellablePromise, deferredPromise } from "../../helpers/cancellablePromise";
import { notifyAll, notifySomeone } from "../../helpers/context"; import { notifyAll, notifySomeone } from "../../helpers/context";
import { getFileNameByLocation } from "../../helpers/fileName"; import { getFileNameByLocation } from "../../helpers/fileName";
@ -9,8 +11,6 @@ import FileManager from "../filemanager";
import { logger, LogLevels } from "../logger"; import { logger, LogLevels } from "../logger";
import apiManager from "./apiManager"; import apiManager from "./apiManager";
import { isWebpSupported } from "./mtproto.worker"; import { isWebpSupported } from "./mtproto.worker";
import { DEBUG, Modes, MOUNT_CLASS_TO } from "./mtproto_config";
type Delayed = { type Delayed = {
offset: number, offset: number,
@ -87,7 +87,7 @@ export class ApiFileManager {
public downloadCheck(dcId: string | number) { public downloadCheck(dcId: string | number) {
const downloadPull = this.downloadPulls[dcId]; const downloadPull = this.downloadPulls[dcId];
const downloadLimit = dcId === 'upload' ? 256 : 48; const downloadLimit = dcId === 'upload' ? 24 : 48;
//const downloadLimit = Infinity; //const downloadLimit = Infinity;
if(this.downloadActives[dcId] >= downloadLimit || !downloadPull || !downloadPull.length) { if(this.downloadActives[dcId] >= downloadLimit || !downloadPull || !downloadPull.length) {

3
src/lib/mtproto/apiManager.ts

@ -5,7 +5,6 @@ import { isObject } from './bin_utils';
import networkerFactory from './networkerFactory'; import networkerFactory from './networkerFactory';
//import { telegramMeWebService } from './mtproto'; //import { telegramMeWebService } from './mtproto';
import authorizer from './authorizer'; import authorizer from './authorizer';
import {App, Modes, MOUNT_CLASS_TO} from './mtproto_config';
import dcConfigurator, { ConnectionType, TransportType } from './dcConfigurator'; import dcConfigurator, { ConnectionType, TransportType } from './dcConfigurator';
import { logger } from '../logger'; import { logger } from '../logger';
import type { InvokeApiOptions } from '../../types'; import type { InvokeApiOptions } from '../../types';
@ -14,6 +13,8 @@ import { CancellablePromise, deferredPromise } from '../../helpers/cancellablePr
import { bytesFromHex, bytesToHex } from '../../helpers/bytes'; import { bytesFromHex, bytesToHex } from '../../helpers/bytes';
//import { clamp } from '../../helpers/number'; //import { clamp } from '../../helpers/number';
import { isSafari } from '../../helpers/userAgent'; import { isSafari } from '../../helpers/userAgent';
import App from '../../config/app';
import { MOUNT_CLASS_TO } from '../../config/debug';
/// #if !MTPROTO_WORKER /// #if !MTPROTO_WORKER
import rootScope from '../rootScope'; import rootScope from '../rootScope';

2
src/lib/mtproto/authorizer.ts

@ -10,7 +10,7 @@ import CryptoWorker from "../crypto/cryptoworker";
import { logger, LogLevels } from "../logger"; import { logger, LogLevels } from "../logger";
import { bytesCmp, bytesToHex, bytesFromHex, bytesXor } from "../../helpers/bytes"; import { bytesCmp, bytesToHex, bytesFromHex, bytesXor } from "../../helpers/bytes";
import { DEBUG } from "./mtproto_config"; import DEBUG from "../../config/debug";
//import { bigInt2str, greater, int2bigInt, one, powMod, str2bigInt, sub } from "../../vendor/leemon"; //import { bigInt2str, greater, int2bigInt, one, powMod, str2bigInt, sub } from "../../vendor/leemon";
/* let fNewNonce: any = bytesFromHex('8761970c24cb2329b5b2459752c502f3057cb7e8dbab200e526e8767fdc73b3c').reverse(); /* let fNewNonce: any = bytesFromHex('8761970c24cb2329b5b2459752c502f3057cb7e8dbab200e526e8767fdc73b3c').reverse();

11
src/lib/mtproto/dcConfigurator.ts

@ -1,14 +1,14 @@
import MTTransport from './transports/transport'; import MTTransport from './transports/transport';
import { Modes } from './mtproto_config'; import Modes from '../../config/modes';
/// #if MTPROTO_HTTP_UPLOAD /// #if MTPROTO_HTTP_UPLOAD
// @ts-ignore // @ts-ignore
import Socket from './transports/websocket'; import TcpObfuscated from './transports/tcpObfuscated';
// @ts-ignore // @ts-ignore
import HTTP from './transports/http'; import HTTP from './transports/http';
/// #elif !MTPROTO_HTTP /// #elif !MTPROTO_HTTP
// @ts-ignore // @ts-ignore
import Socket from './transports/websocket'; import TcpObfuscated from './transports/tcpObfuscated';
import { isSafari } from '../../helpers/userAgent'; import { isSafari } from '../../helpers/userAgent';
import type MTPNetworker from './networker'; import type MTPNetworker from './networker';
import { notifyAll, isWebWorker } from '../../helpers/context'; import { notifyAll, isWebWorker } from '../../helpers/context';
@ -59,14 +59,13 @@ export class DcConfigurator {
const retryTimeout = connectionType === 'client' ? 30000 : 10000; const retryTimeout = connectionType === 'client' ? 30000 : 10000;
if(isSafari && isWebWorker && false) { if(isSafari && isWebWorker && false) {
class P extends MTTransport { class P implements MTTransport {
private id: number; private id: number;
private taskId = 0; private taskId = 0;
public networker: MTPNetworker; public networker: MTPNetworker;
public promises: Map<number, CancellablePromise<Uint8Array>> = new Map(); public promises: Map<number, CancellablePromise<Uint8Array>> = new Map();
constructor(dcId: number, url: string) { constructor(dcId: number, url: string) {
super(dcId, url);
this.id = ++socketId; this.id = ++socketId;
notifyAll({ notifyAll({
@ -109,7 +108,7 @@ export class DcConfigurator {
return new P(dcId, chosenServer); return new P(dcId, chosenServer);
} else { } else {
return new Socket(dcId, chosenServer, logSuffix, retryTimeout); return new TcpObfuscated(dcId, chosenServer, logSuffix, retryTimeout);
} }
}; };
/// #endif /// #endif

5
src/lib/mtproto/mtproto.ts

@ -1,6 +1,3 @@
import sessionStorage from '../sessionStorage';
import { Modes, App } from './mtproto_config';
/* import PasswordManager from './passwordManager'; /* import PasswordManager from './passwordManager';
import DcConfigurator from './dcConfigurator'; import DcConfigurator from './dcConfigurator';
import RSAKeysManager from './rsaKeysManager'; import RSAKeysManager from './rsaKeysManager';
@ -67,3 +64,5 @@ export const telegramMeWebService = new TelegramMeWebService(); */
} }
//(window as any).MTProto = MTProto; */ //(window as any).MTProto = MTProto; */
export default null;

63
src/lib/mtproto/mtproto_config.ts

@ -1,66 +1,3 @@
import { IDBIndex, IDBStore } from "../idb";
export type UserAuth = number; export type UserAuth = number;
export const REPLIES_PEER_ID = 1271266957; export const REPLIES_PEER_ID = 1271266957;
export const App = {
id: 1025907,
hash: '452b0359b988148995f22ff0f4229750',
version: '0.4.0',
domains: [] as string[],
baseDcId: 2
};
export const Modes = {
test: location.search.indexOf('test=1') > 0/* || true */,
debug: location.search.indexOf('debug=1') > 0,
http: false, //location.search.indexOf('http=1') > 0,
ssl: true, // location.search.indexOf('ssl=1') > 0 || location.protocol === 'https:' && location.search.indexOf('ssl=0') === -1,
multipleConnections: true
};
export type DatabaseStoreName = 'session' | 'stickerSets';
export type DatabaseStore = Omit<IDBStore, 'name'> & {name: DatabaseStoreName};
export const Database = {
name: 'tweb' + (Modes.test ? '_test' : ''),
version: 5,
stores: [{
name: 'session'
}, {
name: 'stickerSets'
}] as DatabaseStore[],
};
export const DEBUG = process.env.NODE_ENV !== 'production' || Modes.debug;
export const MOUNT_CLASS_TO: any = DEBUG ? (typeof(window) !== 'undefined' ? window : self) : null;
export const superDebug = (object: any, key: string) => {
var d = object[key];
var beforeStr = '', afterStr = '';
for(var r of d) {
beforeStr += r.before.hex + '\n';
afterStr += r.after.hex + '\n';
}
beforeStr = beforeStr.trim();
afterStr = afterStr.trim();
//var beforeStr = d.map(r => r.before.hex).join('\n');
//var afterStr = d.map(r => r.after.hex).join('\n');
var dada = (name: string, str: string) => {
var a = document.createElement('a');
a.target = '_blank';
a.download = name + '.txt';
a.href = URL.createObjectURL(new Blob([str], {
type: 'text/plain'
}));
document.body.append(a);
a.click();
};
dada(key + '_' + 'before', beforeStr);
dada(key + '_' + 'after', afterStr);
}
MOUNT_CLASS_TO && (MOUNT_CLASS_TO.superDebug = superDebug);

3
src/lib/mtproto/mtprotoworker.ts

@ -11,10 +11,11 @@ import webpWorkerController from '../webp/webpWorkerController';
import type { DownloadOptions } from './apiFileManager'; import type { DownloadOptions } from './apiFileManager';
import { ApiError } from './apiManager'; import { ApiError } from './apiManager';
import type { ServiceWorkerTask, ServiceWorkerTaskResponse } from './mtproto.service'; import type { ServiceWorkerTask, ServiceWorkerTaskResponse } from './mtproto.service';
import { DEBUG, MOUNT_CLASS_TO, UserAuth } from './mtproto_config'; import { UserAuth } from './mtproto_config';
import type { MTMessage } from './networker'; import type { MTMessage } from './networker';
import referenceDatabase from './referenceDatabase'; import referenceDatabase from './referenceDatabase';
import appDocsManager from '../appManagers/appDocsManager'; import appDocsManager from '../appManagers/appDocsManager';
import DEBUG, { MOUNT_CLASS_TO } from '../../config/debug';
type Task = { type Task = {
taskId: number, taskId: number,

142
src/lib/mtproto/networker.ts

@ -7,28 +7,28 @@ import Schema from './schema';
import timeManager from './timeManager'; import timeManager from './timeManager';
import NetworkerFactory from './networkerFactory'; import NetworkerFactory from './networkerFactory';
import { logger, LogLevels } from '../logger'; import { logger, LogLevels } from '../logger';
import { Modes, App, DEBUG } from './mtproto_config';
import { InvokeApiOptions } from '../../types'; import { InvokeApiOptions } from '../../types';
import { longToBytes } from '../crypto/crypto_utils'; import { longToBytes } from '../crypto/crypto_utils';
import MTTransport from './transports/transport'; import MTTransport from './transports/transport';
import { convertToUint8Array, bufferConcat, bytesCmp, bytesToHex } from '../../helpers/bytes'; import { convertToUint8Array, bufferConcat, bytesCmp, bytesToHex } from '../../helpers/bytes';
import { nextRandomInt, randomLong } from '../../helpers/random'; import { nextRandomInt } from '../../helpers/random';
import { CancellablePromise, deferredPromise } from '../../helpers/cancellablePromise'; import { CancellablePromise } from '../../helpers/cancellablePromise';
import { isSafari } from '../../helpers/userAgent'; import { isSafari } from '../../helpers/userAgent';
import App from '../../config/app';
import DEBUG from '../../config/debug';
import Modes from '../../config/modes';
import Obfuscation from './transports/obfuscation';
/// #if MTPROTO_HTTP_UPLOAD /// #if MTPROTO_HTTP_UPLOAD
// @ts-ignore // @ts-ignore
import HTTP from './transports/http'; import HTTP from './transports/http';
// @ts-ignore
import type Socket from './transports/websocket';
/// #elif MTPROTO_HTTP /// #elif MTPROTO_HTTP
// @ts-ignore // @ts-ignore
import HTTP from './transports/http'; import HTTP from './transports/http';
/// #else
// @ts-ignore
import type Socket from './transports/websocket';
/// #endif /// #endif
import type TcpObfuscated from './transports/tcpObfuscated';
//console.error('networker included!', new Error().stack); //console.error('networker included!', new Error().stack);
export type MTMessageOptions = InvokeApiOptions & Partial<{ export type MTMessageOptions = InvokeApiOptions & Partial<{
@ -122,6 +122,8 @@ export default class MTPNetworker {
private debugRequests: Array<{before: Uint8Array, after: Uint8Array}> = []; private debugRequests: Array<{before: Uint8Array, after: Uint8Array}> = [];
private obfuscation: Obfuscation;
constructor(public dcId: number, private authKey: number[], private authKeyId: Uint8Array, constructor(public dcId: number, private authKey: number[], private authKeyId: Uint8Array,
serverSalt: number[], private transport: MTTransport, options: InvokeApiOptions = {}) { serverSalt: number[], private transport: MTTransport, options: InvokeApiOptions = {}) {
this.authKeyUint8 = convertToUint8Array(this.authKey); this.authKeyUint8 = convertToUint8Array(this.authKey);
@ -156,7 +158,7 @@ export default class MTPNetworker {
/* this.longPollInt = */setInterval(this.checkLongPoll, 10000); /* this.longPollInt = */setInterval(this.checkLongPoll, 10000);
this.checkLongPoll(); this.checkLongPoll();
} else { } else {
(this.transport as Socket).networker = this; (this.transport as TcpObfuscated).networker = this;
} }
/// #elif MTPROTO_HTTP /// #elif MTPROTO_HTTP
//if(this.transport instanceof HTTP) { //if(this.transport instanceof HTTP) {
@ -164,18 +166,18 @@ export default class MTPNetworker {
this.checkLongPoll(); this.checkLongPoll();
/// #else /// #else
//} else { //} else {
(this.transport as Socket).networker = this; (this.transport as TcpObfuscated).networker = this;
//} //}
/// #endif /// #endif
// * handle outcoming dead socket, server will close the connection // * handle outcoming dead socket, server will close the connection
if((this.transport as Socket).networker) { if((this.transport as TcpObfuscated).networker) {
if(isSafari) { if(isSafari) {
this.pingPromise = Promise.resolve(); this.pingPromise = Promise.resolve();
} else { } else {
this.disconnectDelay = (this.transport as Socket).retryTimeout / 1000 | 0; this.disconnectDelay = (this.transport as TcpObfuscated).retryTimeout / 1000 | 0;
//setInterval(this.sendPingDelayDisconnect, (this.disconnectDelay - 5) * 1000); //setInterval(this.sendPingDelayDisconnect, (this.disconnectDelay - 5) * 1000);
this.sendPingDelayDisconnect(); // ! this.sendPingDelayDisconnect();
} }
} }
} }
@ -338,66 +340,66 @@ export default class MTPNetworker {
return this.pushMessage(message, options); return this.pushMessage(message, options);
} }
private sendPingDelayDisconnect = () => { // private sendPingDelayDisconnect = () => {
if(this.pingPromise || true) return; // if(this.pingPromise || true) return;
if(!this.isOnline) {
if((this.transport as Socket).connected) {
(this.transport as Socket).handleClose();
}
return;
}
this.log('sendPingDelayDisconnect', this.sentPingTimes);
/* if(this.tt) clearTimeout(this.tt); // if(!this.isOnline) {
this.tt = self.setTimeout(() => { // if((this.transport as TcpObfuscated).connected) {
(this.transport as any).ws.close(1000); // (this.transport as TcpObfuscated).handleClose();
this.tt = 0; // }
}, this.disconnectDelay * 1000); */
/* this.wrapMtpCall('ping_delay_disconnect', {
ping_id: randomLong(),
disconnect_delay: this.disconnectDelay
}, {
noResponse: true,
notContentRelated: true
}); */
const deferred = this.pingPromise = deferredPromise<void>();
const timeoutTime = this.disconnectDelay * 1000;
/* if(!this.sentPingTimes || true) { // return;
++this.sentPingTimes; */ // }
const startTime = Date.now();
this.wrapMtpCall('ping', {
ping_id: randomLong()
}, {}).then(pong => {
const elapsedTime = Date.now() - startTime;
this.log('sendPingDelayDisconnect: response', pong, elapsedTime > timeoutTime);
if(elapsedTime > timeoutTime) { // this.log('sendPingDelayDisconnect', this.sentPingTimes);
deferred.reject();
} else { // /* if(this.tt) clearTimeout(this.tt);
setTimeout(deferred.resolve, timeoutTime - elapsedTime); // this.tt = self.setTimeout(() => {
} // (this.transport as any).ws.close(1000);
}, deferred.reject).finally(() => { // this.tt = 0;
clearTimeout(rejectTimeout); // }, this.disconnectDelay * 1000); */
//--this.sentPingTimes; // /* this.wrapMtpCall('ping_delay_disconnect', {
}); // ping_id: randomLong(),
// disconnect_delay: this.disconnectDelay
// }, {
// noResponse: true,
// notContentRelated: true
// }); */
// const deferred = this.pingPromise = deferredPromise<void>();
// const timeoutTime = this.disconnectDelay * 1000;
// /* if(!this.sentPingTimes || true) {
// ++this.sentPingTimes; */
// const startTime = Date.now();
// this.wrapMtpCall('ping', {
// ping_id: randomLong()
// }, {}).then(pong => {
// const elapsedTime = Date.now() - startTime;
// this.log('sendPingDelayDisconnect: response', pong, elapsedTime > timeoutTime);
// if(elapsedTime > timeoutTime) {
// deferred.reject();
// } else {
// setTimeout(deferred.resolve, timeoutTime - elapsedTime);
// } // }
// }, deferred.reject).finally(() => {
// clearTimeout(rejectTimeout);
// //--this.sentPingTimes;
// });
// //}
const rejectTimeout = self.setTimeout(deferred.reject, timeoutTime); // const rejectTimeout = self.setTimeout(deferred.reject, timeoutTime);
deferred.catch(() => { // deferred.catch(() => {
(this.transport as Socket).handleClose(); // (this.transport as Socket).handleClose();
}); // });
deferred.finally(() => { // deferred.finally(() => {
this.pingPromise = null; // this.pingPromise = null;
this.sendPingDelayDisconnect(); // this.sendPingDelayDisconnect();
}); // });
}; // };
/// #if MTPROTO_HTTP || MTPROTO_HTTP_UPLOAD /// #if MTPROTO_HTTP || MTPROTO_HTTP_UPLOAD
public checkLongPoll = () => { public checkLongPoll = () => {
@ -638,9 +640,9 @@ export default class MTPNetworker {
}); });
} }
if(!this.pingPromise && (this.transport as Socket).networker) { /* if(!this.pingPromise && (this.transport as TcpObfuscated).networker) {
this.sendPingDelayDisconnect(); this.sendPingDelayDisconnect();
} } */
/* this.sentPingTimes = 0; /* this.sentPingTimes = 0;
this.sendPingDelayDisconnect(); */ this.sendPingDelayDisconnect(); */
} }
@ -962,7 +964,7 @@ export default class MTPNetworker {
} */ } */
const paddingLength = (16 - (data.offset % 16)) + 16 * (1 + nextRandomInt(5)); const paddingLength = (16 - (data.offset % 16)) + 16 * (1 + nextRandomInt(5));
const padding = (message as any).padding || new Uint8Array(paddingLength).randomize().fill(0); const padding = (message as any).padding || new Uint8Array(paddingLength).randomize()/* .fill(0) */;
/* const padding = [167, 148, 207, 226, 86, 192, 193, 57, 124, 153, 174, 145, 159, 1, 5, 70, 127, 157, /* const padding = [167, 148, 207, 226, 86, 192, 193, 57, 124, 153, 174, 145, 159, 1, 5, 70, 127, 157,
51, 241, 46, 85, 141, 212, 139, 234, 213, 164, 197, 116, 245, 70, 184, 40, 40, 201, 233, 211, 150, 51, 241, 46, 85, 141, 212, 139, 234, 213, 164, 197, 116, 245, 70, 184, 40, 40, 201, 233, 211, 150,
94, 57, 84, 1, 135, 108, 253, 34, 139, 222, 208, 71, 214, 90, 67, 36, 28, 167, 148, 207, 226, 86, 192, 193, 57, 124, 153, 174, 145, 159, 1, 5, 70, 127, 157, 94, 57, 84, 1, 135, 108, 253, 34, 139, 222, 208, 71, 214, 90, 67, 36, 28, 167, 148, 207, 226, 86, 192, 193, 57, 124, 153, 174, 145, 159, 1, 5, 70, 127, 157,
@ -1499,7 +1501,7 @@ export default class MTPNetworker {
} }
case 'pong': { // * https://core.telegram.org/mtproto/service_messages#ping-messages-pingpong - These messages doesn't require acknowledgments case 'pong': { // * https://core.telegram.org/mtproto/service_messages#ping-messages-pingpong - These messages doesn't require acknowledgments
if((this.transport as Socket).networker) { if((this.transport as TcpObfuscated).networker) {
const sentMessageId = message.msg_id; const sentMessageId = message.msg_id;
const sentMessage = this.sentMessages[sentMessageId]; const sentMessage = this.sentMessages[sentMessageId];

2
src/lib/mtproto/passwordManager.ts

@ -1,6 +1,6 @@
import { MOUNT_CLASS_TO } from '../../config/debug';
import { AccountPassword } from '../../layer'; import { AccountPassword } from '../../layer';
import apiManager from './mtprotoworker'; import apiManager from './mtprotoworker';
import { MOUNT_CLASS_TO } from './mtproto_config';
//import { computeCheck } from "../crypto/srp"; //import { computeCheck } from "../crypto/srp";
export class PasswordManager { export class PasswordManager {

2
src/lib/mtproto/referenceDatabase.ts

@ -1,8 +1,8 @@
import appMessagesManager from "../appManagers/appMessagesManager"; import appMessagesManager from "../appManagers/appMessagesManager";
import { Photo } from "../../layer"; import { Photo } from "../../layer";
import { MOUNT_CLASS_TO } from "./mtproto_config";
import { bytesToHex } from "../../helpers/bytes"; import { bytesToHex } from "../../helpers/bytes";
import { deepEqual } from "../../helpers/object"; import { deepEqual } from "../../helpers/object";
import { MOUNT_CLASS_TO } from "../../config/debug";
export type ReferenceContext = ReferenceContext.referenceContextProfilePhoto | ReferenceContext.referenceContextMessage; export type ReferenceContext = ReferenceContext.referenceContextProfilePhoto | ReferenceContext.referenceContextMessage;
export namespace ReferenceContext { export namespace ReferenceContext {

2
src/lib/mtproto/timeManager.ts

@ -1,7 +1,7 @@
import sessionStorage from '../sessionStorage'; import sessionStorage from '../sessionStorage';
import { longFromInts } from './bin_utils'; import { longFromInts } from './bin_utils';
import { nextRandomInt } from '../../helpers/random'; import { nextRandomInt } from '../../helpers/random';
import { MOUNT_CLASS_TO } from './mtproto_config'; import { MOUNT_CLASS_TO } from '../../config/debug';
/* /*
let lol: any = {}; let lol: any = {};

2
src/lib/mtproto/tl_utils.ts

@ -1,6 +1,6 @@
import { bytesToHex } from '../../helpers/bytes'; import { bytesToHex } from '../../helpers/bytes';
import { bigint, bigStringInt, isObject } from './bin_utils'; import { bigint, bigStringInt, isObject } from './bin_utils';
import { MOUNT_CLASS_TO } from './mtproto_config'; import { MOUNT_CLASS_TO } from '../../config/debug';
/// #if MTPROTO_WORKER /// #if MTPROTO_WORKER
// @ts-ignore // @ts-ignore
import { gzipUncompress } from '../crypto/crypto_utils'; import { gzipUncompress } from '../crypto/crypto_utils';

5
src/lib/mtproto/transports/http.ts

@ -1,9 +1,8 @@
import { bytesFromArrayBuffer } from '../../../helpers/bytes'; import { bytesFromArrayBuffer } from '../../../helpers/bytes';
import MTTransport from './transport'; import MTTransport from './transport';
export default class HTTP extends MTTransport { export default class HTTP implements MTTransport {
constructor(dcId: number, url: string) { constructor(protected dcId: number, protected url: string) {
super(dcId, url);
} }
send = (data: Uint8Array) => { send = (data: Uint8Array) => {

220
src/lib/mtproto/transports/tcpObfuscated.ts

@ -0,0 +1,220 @@
import Modes from "../../../config/modes";
import { logger, LogLevels } from "../../logger";
import MTPNetworker from "../networker";
import Obfuscation from "./obfuscation";
import MTTransport from "./transport";
import Socket from "./websocket";
import intermediatePacketCodec from './intermediate';
export default class TcpObfuscated implements MTTransport {
private codec = intermediatePacketCodec;
private obfuscation = new Obfuscation();
public networker: MTPNetworker;
private pending: Array<Partial<{
resolve: any,
reject: any,
body: Uint8Array,
encoded?: Uint8Array,
bodySent: boolean
}>> = [];
private debug = Modes.debug && false;
private log: ReturnType<typeof logger>;
public connected = false;
private lastCloseTime: number;
private socket: Socket;
//private debugPayloads: MTPNetworker['debugRequests'] = [];
constructor(private dcId: number, private url: string, private logSuffix: string, public retryTimeout: number) {
let logLevel = LogLevels.error | LogLevels.log;
if(this.debug) logLevel |= LogLevels.debug;
this.log = logger(`WS-${dcId}` + logSuffix, logLevel);
this.log('constructor');
this.connect();
}
private connect() {
this.socket = new Socket(this.dcId, this.url, this.logSuffix);
this.socket.addListener('open', () => {
this.connected = true;
const initPayload = this.obfuscation.init(this.codec);
if(this.networker) {
this.networker.setConnectionStatus(true);
if(this.lastCloseTime) {
this.networker.cleanupSent();
this.networker.resend();
}
}
setTimeout(() => {
this.releasePending();
}, 0);
this.socket.send(initPayload);
});
this.socket.addListener('message', (buffer) => {
let data = this.obfuscation.decode(new Uint8Array(buffer));
data = this.codec.readPacket(data);
if(this.networker) { // authenticated!
//this.pending = this.pending.filter(p => p.body); // clear pending
this.debug && this.log.debug('redirecting to networker', data.length);
this.networker.parseResponse(data).then(response => {
this.debug && this.log.debug('redirecting to networker response:', response);
try {
this.networker.processMessage(response.response, response.messageId, response.sessionId);
} catch(err) {
this.log.error('handleMessage networker processMessage error', err);
}
//this.releasePending();
}).catch(err => {
this.log.error('handleMessage networker parseResponse error', err);
});
//this.dd();
return;
}
//console.log('got hex:', data.hex);
const pending = this.pending.shift();
if(!pending) {
this.debug && this.log.debug('no pending for res:', data.hex);
return;
}
pending.resolve(data);
});
this.socket.addListener('close', () => {
this.connected = false;
this.socket = undefined;
const time = Date.now();
const diff = time - this.lastCloseTime;
const needTimeout = !isNaN(diff) && diff < this.retryTimeout ? this.retryTimeout - diff : 0;
if(this.networker) {
this.networker.setConnectionStatus(false);
}
this.log('will try to reconnect after timeout:', needTimeout / 1000);
setTimeout(() => {
this.log('trying to reconnect...');
this.lastCloseTime = Date.now();
for(const pending of this.pending) {
if(pending.bodySent) {
pending.bodySent = false;
}
}
this.connect();
}, needTimeout);
});
}
private encodeBody = (body: Uint8Array) => {
const toEncode = this.codec.encodePacket(body);
//this.log('send before obf:', /* body.hex, nonce.hex, */ toEncode.hex);
const encoded = this.obfuscation.encode(toEncode);
//this.log('send after obf:', enc.hex);
return encoded;
};
public send = (body: Uint8Array) => {
this.debug && this.log.debug('-> body length to pending:', body.length);
const encoded: typeof body = this.connected ? this.encodeBody(body) : undefined;
//return;
if(this.networker) {
this.pending.push({body, encoded});
this.releasePending();
} else {
const promise = new Promise<typeof body>((resolve, reject) => {
this.pending.push({resolve, reject, body, encoded});
});
this.releasePending();
return promise;
}
};
private releasePending(/* tt = false */) {
if(!this.connected) {
//this.connect();
return;
}
/* if(!tt) {
this.releasePendingDebounced();
return;
} */
//this.log('-> messages to send:', this.pending.length);
let length = this.pending.length;
//for(let i = length - 1; i >= 0; --i) {
for(let i = 0; i < length; ++i) {
/* if(this.ws.bufferedAmount) {
break;
} */
const pending = this.pending[i];
const {body, bodySent} = pending;
let encoded = pending.encoded;
if(body && !bodySent) {
//this.debugPayloads.push({before: body.slice(), after: enc});
this.debug && this.log.debug('-> body length to send:', body.length);
/* if(this.ws.bufferedAmount) {
this.log.error('bufferedAmount:', this.ws.bufferedAmount);
} */
/* if(this.ws.readyState !== this.ws.OPEN) {
this.log.error('ws is closed?');
this.connected = false;
break;
} */
if(!encoded) {
encoded = this.encodeBody(body);
}
//this.lol.push(body);
//setTimeout(() => {
this.socket.send(encoded);
//}, 100);
//this.dd();
if(!pending.resolve) { // remove if no response needed
this.pending.splice(i--, 1);
length--;
} else {
pending.bodySent = true;
}
//delete pending.body;
}
}
}
}

4
src/lib/mtproto/transports/transport.ts

@ -1,7 +1,3 @@
export default abstract class MTTransport { export default abstract class MTTransport {
constructor(protected dcId: number, protected url: string) {
}
abstract send: (data: Uint8Array) => Promise<Uint8Array>; abstract send: (data: Uint8Array) => Promise<Uint8Array>;
} }

224
src/lib/mtproto/transports/websocket.ts

@ -1,62 +1,24 @@
import MTTransport from './transport';
//import abridgedPacketCodec from './abridged';
import intermediatePacketCodec from './intermediate';
import MTPNetworker from '../networker';
import { logger, LogLevels } from '../../logger'; import { logger, LogLevels } from '../../logger';
import Obfuscation from './obfuscation'; import Modes from '../../../config/modes';
import { DEBUG, Modes } from '../mtproto_config'; import EventListenerBase from '../../../helpers/eventListenerBase';
import { isWebWorker } from '../../../helpers/context';
import { ctx } from '../../../helpers/userAgent'; export default class Socket extends EventListenerBase<{
open: () => void,
export default class Socket extends MTTransport { message: (buffer: ArrayBuffer) => any,
close: () => void,
}> {
public ws: WebSocket; public ws: WebSocket;
private pending: Array<Partial<{
resolve: any,
reject: any,
body: Uint8Array,
bodySent: boolean
}>> = [];
public connected = false;
private codec = intermediatePacketCodec;
private log: ReturnType<typeof logger>; private log: ReturnType<typeof logger>;
private obfuscation = new Obfuscation();
public networker: MTPNetworker;
private lastCloseTime: number;
private debug = Modes.debug && false; private debug = Modes.debug && false;
//private releasePendingDebounced: () => void;
/* private stream: Array<any>;
private canRead: Promise<any>;
private resolveRead: () => void; */
//private lol: Uint8Array[] = [];
//private dd: () => void;
//private debugPayloads: MTPNetworker['debugRequests'] = []; constructor(protected dcId: number, protected url: string, logSuffix: string) {
super();
constructor(dcId: number, url: string, logSuffix: string, public retryTimeout: number) {
super(dcId, url);
let logLevel = LogLevels.error | LogLevels.log; let logLevel = LogLevels.error | LogLevels.log;
if(this.debug) logLevel |= LogLevels.debug; if(this.debug) logLevel |= LogLevels.debug;
this.log = logger(`WS-${dcId}` + logSuffix, logLevel); this.log = logger(`WS-${dcId}` + logSuffix, logLevel);
this.log('constructor'); this.log('constructor');
this.connect(); this.connect();
//this.releasePendingDebounced = debounce(() => this.releasePending(true), 200, false, true);
/* this.dd = debounce(() => {
if(this.connected && this.lol.length) {
this.ws.send(this.lol.shift());
if(this.lol.length) {
this.dd();
}
}
}, 100, false, true); */
} }
private removeListeners() { private removeListeners() {
@ -66,45 +28,20 @@ export default class Socket extends MTTransport {
this.ws.removeEventListener('message', this.handleMessage); this.ws.removeEventListener('message', this.handleMessage);
} }
connect = () => { private connect() {
if(this.ws) {
this.removeListeners();
this.ws.close(1000);
}
/* this.stream = [];
this.canRead = new Promise<void>(resolve => {
this.resolveRead = resolve;
}); */
this.ws = new WebSocket(this.url, 'binary'); this.ws = new WebSocket(this.url, 'binary');
this.ws.binaryType = 'arraybuffer'; this.ws.binaryType = 'arraybuffer';
this.ws.addEventListener('open', this.handleOpen); this.ws.addEventListener('open', this.handleOpen);
this.ws.addEventListener('close', this.handleClose); this.ws.addEventListener('close', this.handleClose);
this.ws.addEventListener('error', this.handleError); this.ws.addEventListener('error', this.handleError);
this.ws.addEventListener('message', this.handleMessage); this.ws.addEventListener('message', this.handleMessage);
}; }
handleOpen = () => { handleOpen = () => {
this.log('opened'); this.log('opened');
this.debug && this.log.debug('sending init packet'); this.debug && this.log.debug('sending init packet');
this.ws.send(this.obfuscation.init(this.codec)); this.setListenerResult('open');
//setTimeout(() => {
this.connected = true;
this.releasePending();
if(this.networker) {
this.networker.setConnectionStatus(true);
if(this.lastCloseTime) {
this.networker.cleanupSent();
this.networker.resend();
}
}
//}, 3e3);
}; };
handleError = (e: Event) => { handleError = (e: Event) => {
@ -113,147 +50,22 @@ export default class Socket extends MTTransport {
handleClose = () => { handleClose = () => {
this.log('closed'/* , event, this.pending, this.ws.bufferedAmount */); this.log('closed'/* , event, this.pending, this.ws.bufferedAmount */);
this.connected = false;
this.removeListeners();
const time = Date.now(); this.removeListeners();
const diff = time - this.lastCloseTime; this.setListenerResult('close');
const needTimeout = !isNaN(diff) && diff < this.retryTimeout ? this.retryTimeout - diff : 0;
if(this.networker) {
this.networker.setConnectionStatus(false);
}
this.log('will try to reconnect after timeout:', needTimeout / 1000);
setTimeout(() => {
this.log('trying to reconnect...');
this.lastCloseTime = Date.now();
for(const pending of this.pending) {
if(pending.bodySent) {
pending.bodySent = false;
}
}
this.connect();
}, needTimeout);
}; };
handleMessage = (event: MessageEvent) => { handleMessage = (event: MessageEvent) => {
this.debug && this.log.debug('<-', 'handleMessage', /* event, */event.data.byteLength); this.debug && this.log.debug('<-', 'handleMessage', /* event, */event.data.byteLength);
let data = this.obfuscation.decode(new Uint8Array(event.data)); this.setListenerResult('message', event.data as ArrayBuffer);
data = this.codec.readPacket(data);
if(this.networker) { // authenticated!
//this.pending = this.pending.filter(p => p.body); // clear pending
this.debug && this.log.debug('redirecting to networker', data.length);
this.networker.parseResponse(data).then(response => {
this.debug && this.log.debug('redirecting to networker response:', response);
try {
this.networker.processMessage(response.response, response.messageId, response.sessionId);
} catch(err) {
this.log.error('handleMessage networker processMessage error', err);
}
//this.releasePending();
}).catch(err => {
this.log.error('handleMessage networker parseResponse error', err);
});
//this.dd();
return;
}
//console.log('got hex:', data.hex);
const pending = this.pending.shift();
if(!pending) {
this.debug && this.log.debug('no pending for res:', data.hex);
return;
}
pending.resolve(data);
}; };
send = (body: Uint8Array) => { send = (body: Uint8Array) => {
this.debug && this.log.debug('-> body length to pending:', body.length); this.debug && this.log.debug('-> body length to send:', body.length);
//return;
if(this.networker) {
this.pending.push({body});
this.releasePending();
} else {
const promise = new Promise<Uint8Array>((resolve, reject) => {
this.pending.push({resolve, reject, body});
});
this.releasePending();
return promise; this.ws.send(body);
}
}; };
releasePending(/* tt = false */) {
if(!this.connected) {
//this.connect();
return;
}
/* if(!tt) {
this.releasePendingDebounced();
return;
} */
//this.log('-> messages to send:', this.pending.length);
let length = this.pending.length;
//for(let i = length - 1; i >= 0; --i) {
for(let i = 0; i < length; ++i) {
/* if(this.ws.bufferedAmount) {
break;
} */
const pending = this.pending[i];
const {body, bodySent} = pending;
if(body && !bodySent) {
const toEncode = this.codec.encodePacket(body);
//this.log('send before obf:', /* body.hex, nonce.hex, */ toEncode.hex);
const enc = this.obfuscation.encode(toEncode);
//this.log('send after obf:', enc.hex);
//this.debugPayloads.push({before: body.slice(), after: enc});
this.debug && this.log.debug('-> body length to send:', enc.length, this.ws.bufferedAmount);
/* if(this.ws.bufferedAmount) {
this.log.error('bufferedAmount:', this.ws.bufferedAmount);
} */
/* if(this.ws.readyState !== this.ws.OPEN) {
this.log.error('ws is closed?');
this.connected = false;
break;
} */
//this.lol.push(enc);
//setTimeout(() => {
this.ws.send(enc);
//}, 100);
//this.dd();
if(!pending.resolve) { // remove if no response needed
this.pending.splice(i--, 1);
length--;
} else {
pending.bodySent = true;
}
//delete pending.body;
}
}
}
} }
/* const setupSafariFix = () => { /* const setupSafariFix = () => {

2
src/lib/opusDecodeController.ts

@ -1,6 +1,6 @@
import { MOUNT_CLASS_TO } from "../config/debug";
import { isSafari } from "../helpers/userAgent"; import { isSafari } from "../helpers/userAgent";
import { logger, LogLevels } from "./logger"; import { logger, LogLevels } from "./logger";
import { MOUNT_CLASS_TO } from "./mtproto/mtproto_config";
type Result = { type Result = {
bytes: Uint8Array, bytes: Uint8Array,

2
src/lib/richtextprocessor.ts

@ -2,10 +2,10 @@ import Config from './config';
import emojiRegExp from '../emoji/regex'; import emojiRegExp from '../emoji/regex';
import { encodeEmoji } from '../emoji'; import { encodeEmoji } from '../emoji';
import { MOUNT_CLASS_TO } from './mtproto/mtproto_config';
import { MessageEntity } from '../layer'; import { MessageEntity } from '../layer';
import { encodeEntities } from '../helpers/string'; import { encodeEntities } from '../helpers/string';
import { isSafari } from '../helpers/userAgent'; import { isSafari } from '../helpers/userAgent';
import { MOUNT_CLASS_TO } from '../config/debug';
const EmojiHelper = { const EmojiHelper = {
emojiMap: (code: string) => { return code; }, emojiMap: (code: string) => { return code; },

4
src/lib/rootScope.ts

@ -6,10 +6,11 @@ import type { MyDialogFilter } from "./storages/filters";
import type { ConnectionStatusChange } from "../types"; import type { ConnectionStatusChange } from "../types";
import type { UserTyping } from "./appManagers/appChatsManager"; import type { UserTyping } from "./appManagers/appChatsManager";
import type Chat from "../components/chat/chat"; import type Chat from "../components/chat/chat";
import { DEBUG, MOUNT_CLASS_TO, UserAuth } from "./mtproto/mtproto_config"; import { UserAuth } from "./mtproto/mtproto_config";
import { State } from "./appManagers/appStateManager"; import { State } from "./appManagers/appStateManager";
import EventListenerBase from "../helpers/eventListenerBase"; import EventListenerBase from "../helpers/eventListenerBase";
import { MyDraftMessage } from "./appManagers/appDraftsManager"; import { MyDraftMessage } from "./appManagers/appDraftsManager";
import { MOUNT_CLASS_TO } from "../config/debug";
type BroadcastEvents = { type BroadcastEvents = {
'user_update': number, 'user_update': number,
@ -147,6 +148,5 @@ class RootScope extends EventListenerBase<any> {
} }
const rootScope = new RootScope(); const rootScope = new RootScope();
MOUNT_CLASS_TO && (MOUNT_CLASS_TO.rootScope = rootScope); MOUNT_CLASS_TO && (MOUNT_CLASS_TO.rootScope = rootScope);
export default rootScope; export default rootScope;

3
src/lib/sessionStorage.ts

@ -1,6 +1,5 @@
import type { AppImManager } from './appManagers/appImManager'; import { MOUNT_CLASS_TO } from '../config/debug';
import type { State } from './appManagers/appStateManager'; import type { State } from './appManagers/appStateManager';
import { MOUNT_CLASS_TO } from './mtproto/mtproto_config';
import AppStorage from './storage'; import AppStorage from './storage';
const sessionStorage = new AppStorage<{ const sessionStorage = new AppStorage<{

2
src/lib/storage.ts

@ -1,5 +1,5 @@
import { DatabaseStore, DatabaseStoreName } from "../config/database";
import IDBStorage, { IDBOptions } from "./idb"; import IDBStorage, { IDBOptions } from "./idb";
import { DatabaseStore, DatabaseStoreName } from "./mtproto/mtproto_config";
export default class AppStorage<Storage extends Record<string, any>/* Storage extends {[name: string]: any} *//* Storage extends Record<string, any> */> { export default class AppStorage<Storage extends Record<string, any>/* Storage extends {[name: string]: any} *//* Storage extends Record<string, any> */> {
private storage: IDBStorage;//new CacheStorageController('session'); private storage: IDBStorage;//new CacheStorageController('session');

2
src/lib/webp/webpWorkerController.ts

@ -1,7 +1,7 @@
import WebpWorker from 'worker-loader!./webp.worker'; import WebpWorker from 'worker-loader!./webp.worker';
import { MOUNT_CLASS_TO } from '../../config/debug';
import { CancellablePromise, deferredPromise } from '../../helpers/cancellablePromise'; import { CancellablePromise, deferredPromise } from '../../helpers/cancellablePromise';
import apiManagerProxy from '../mtproto/mtprotoworker'; import apiManagerProxy from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from '../mtproto/mtproto_config';
export type WebpConvertTask = { export type WebpConvertTask = {
type: 'convertWebp', type: 'convertWebp',

1
src/pages/pageAuthCode.ts

@ -5,7 +5,6 @@ import LottieLoader, { RLottiePlayer } from '../lib/lottieLoader';
//import CryptoWorker from '../lib/crypto/cryptoworker'; //import CryptoWorker from '../lib/crypto/cryptoworker';
//import apiManager from '../lib/mtproto/apiManager'; //import apiManager from '../lib/mtproto/apiManager';
import apiManager from '../lib/mtproto/mtprotoworker'; import apiManager from '../lib/mtproto/mtprotoworker';
import { App } from '../lib/mtproto/mtproto_config';
import Page from './page'; import Page from './page';
import pageIm from './pageIm'; import pageIm from './pageIm';
import pagePassword from './pagePassword'; import pagePassword from './pagePassword';

3
src/pages/pageSignIn.ts

@ -3,7 +3,6 @@ import Scrollable from '../components/scrollable';
import Countries, { Country as _Country } from "../countries"; import Countries, { Country as _Country } from "../countries";
import appStateManager from "../lib/appManagers/appStateManager"; import appStateManager from "../lib/appManagers/appStateManager";
import apiManager from "../lib/mtproto/mtprotoworker"; import apiManager from "../lib/mtproto/mtprotoworker";
import { App, Modes } from "../lib/mtproto/mtproto_config";
import { RichTextProcessor } from '../lib/richtextprocessor'; import { RichTextProcessor } from '../lib/richtextprocessor';
import { findUpTag, findUpClassName } from "../helpers/dom"; import { findUpTag, findUpClassName } from "../helpers/dom";
import Page from "./page"; import Page from "./page";
@ -15,6 +14,8 @@ import Button from "../components/button";
import { isAppleMobile } from "../helpers/userAgent"; import { isAppleMobile } from "../helpers/userAgent";
import fastSmoothScroll from "../helpers/fastSmoothScroll"; import fastSmoothScroll from "../helpers/fastSmoothScroll";
import { isTouchSupported } from "../helpers/touchSupport"; import { isTouchSupported } from "../helpers/touchSupport";
import App from "../config/app";
import Modes from "../config/modes";
type Country = _Country & { type Country = _Country & {
li?: HTMLLIElement[] li?: HTMLLIElement[]

2
src/pages/pageSignQR.ts

@ -4,11 +4,11 @@ import Page from './page';
import pageIm from './pageIm'; import pageIm from './pageIm';
import pagePassword from './pagePassword'; import pagePassword from './pagePassword';
import pageSignIn from './pageSignIn'; import pageSignIn from './pageSignIn';
import { App } from '../lib/mtproto/mtproto_config';
import serverTimeManager from '../lib/mtproto/serverTimeManager'; import serverTimeManager from '../lib/mtproto/serverTimeManager';
import { AuthAuthorization, AuthLoginToken } from '../layer'; import { AuthAuthorization, AuthLoginToken } from '../layer';
import { bytesCmp, bytesToBase64 } from '../helpers/bytes'; import { bytesCmp, bytesToBase64 } from '../helpers/bytes';
import { pause } from '../helpers/schedulers'; import { pause } from '../helpers/schedulers';
import App from '../config/app';
let onFirstMount = async() => { let onFirstMount = async() => {
const pageElement = page.pageEl; const pageElement = page.pageEl;

2
src/pages/pagesManager.ts

@ -2,7 +2,7 @@ import Page from "./page";
import { whichChild } from "../helpers/dom"; import { whichChild } from "../helpers/dom";
import lottieLoader from "../lib/lottieLoader"; import lottieLoader from "../lib/lottieLoader";
import { horizontalMenu } from "../components/horizontalMenu"; import { horizontalMenu } from "../components/horizontalMenu";
import { MOUNT_CLASS_TO } from "../lib/mtproto/mtproto_config"; import { MOUNT_CLASS_TO } from "../config/debug";
class PagesManager { class PagesManager {
private pageId = -1; private pageId = -1;

Loading…
Cancel
Save