tgsnake
Version:
Telegram MTProto framework for nodejs.
298 lines (297 loc) • 14.7 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Snake = void 0;
exports.shutdown = shutdown;
const platform_node_js_1 = require("../platform.node.js");
const node_fs_1 = __importDefault(require("node:fs"));
const SnakeSession_js_1 = require("./SnakeSession.js");
const BrowserSession_js_1 = require("./BrowserSession.js");
const Cli_js_1 = require("./Login/Cli.js");
const Version = __importStar(require("../Version.node.js"));
const index_js_1 = require("../Context/index.js");
const Telegram_js_1 = require("../Methods/Telegram.js");
class Snake extends index_js_1.MainContext {
_options;
_client;
_cacheMessage;
_me;
_rndMsgId;
api;
constructor(options) {
super();
this._options = options;
}
async _init() {
let options = this._options;
index_js_1.Logger.log(`Welcome to tgsnake!`);
index_js_1.Logger.log(`Using version: ${Version.version} - ${Version.getType()}`);
index_js_1.Logger.log(`Thanks for using tgsnake`);
if (!options) {
if (node_fs_1.default.existsSync(platform_node_js_1.path.join((0, platform_node_js_1.cwd)(), 'tgsnake.config.js'))) {
if (platform_node_js_1.isBrowser) {
index_js_1.Logger.error(`Config file is not supported on browser!`);
}
else {
index_js_1.Logger.info(`Found config file: ${platform_node_js_1.path.join((0, platform_node_js_1.cwd)(), 'tgsnake.config.js')}`);
if (platform_node_js_1.isDeno) {
options = (await Promise.resolve(`${platform_node_js_1.path.join((0, platform_node_js_1.cwd)(), 'tgsnake.config.js')}`).then(s => __importStar(require(s)))).default;
}
else {
options = require(platform_node_js_1.path.join((0, platform_node_js_1.cwd)(), 'tgsnake.config.js'));
}
}
}
else {
options = {};
}
}
if (options) {
this._options = Object.assign({
logLevel: [platform_node_js_1.sysprc.env.LOGLEVEL || 'debug'],
experimental: {},
}, options);
this._options.clientOptions = Object.assign({
appVersion: Version.version.replace(/(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/gm, ''),
}, this._options.clientOptions);
this._options.login = Object.assign({
session: '',
forceDotSession: true,
sessionName: 'tgsnake',
}, this._options.login);
this._options.experimental = Object.assign({
alwaysOnline: false,
onlineOnStart: false,
shutdown: true,
syncEvery: 10000,
alwaysSync: false,
customPath: {},
}, this._options.experimental);
this._options.experimental.customPath = Object.assign({
loginDir: (0, platform_node_js_1.cwd)(),
loginExt: 'session',
cacheDir: (0, platform_node_js_1.cwd)(),
cacheExt: 'cache',
}, this._options.experimental.customPath);
if (this._options.login.session !== undefined) {
if (typeof this._options.login.session === 'string') {
this._options.login.session;
if (this._options.login.session === '') {
if (this._options.login.forceDotSession) {
if (!options.login.sessionName) {
this._options.login.sessionName = (0, SnakeSession_js_1.generateName)(this._options.login.sessionName, this._options.experimental.customPath.loginDir, this._options.experimental.customPath.loginExt, this._options.experimental.customPath.cacheDir, this._options.experimental.customPath.cacheExt);
index_js_1.Logger.info(`Creating \`${this._options.login.sessionName}\` dot session. Change default sessionName to \`${this._options.login.sessionName}\` for login in next time.`);
}
if (platform_node_js_1.isBrowser) {
this._options.login.session = new BrowserSession_js_1.BrowserSession(this._options.login.sessionName);
}
else {
this._options.login.session = new SnakeSession_js_1.SnakeSession(this._options.login.sessionName, this._options.experimental.customPath.loginDir, this._options.experimental.customPath.loginExt, this._options.experimental.customPath.cacheDir, this._options.experimental.customPath.cacheExt);
}
}
else {
this._options.login.session = new platform_node_js_1.Storages.StringSession(this._options.login.session);
}
}
else {
const _session = new platform_node_js_1.Storages.StringSession(this._options.login.session);
if (this._options.login.forceDotSession) {
this._options.login.sessionName = (0, SnakeSession_js_1.generateName)(this._options.login.sessionName, this._options.experimental.customPath.loginDir, this._options.experimental.customPath.loginExt, this._options.experimental.customPath.cacheDir, this._options.experimental.customPath.cacheExt);
index_js_1.Logger.info(`Creating \`${this._options.login.sessionName}\` dot session. Change default sessionName to \`${this._options.login.sessionName}\` for login in next time.`);
if (platform_node_js_1.isBrowser) {
this._options.login.session = new BrowserSession_js_1.BrowserSession(this._options.login.sessionName);
}
else {
this._options.login.session = new SnakeSession_js_1.SnakeSession(this._options.login.sessionName, this._options.experimental.customPath.loginDir, this._options.experimental.customPath.loginExt, this._options.experimental.customPath.cacheDir, this._options.experimental.customPath.cacheExt);
}
_session.move(this._options.login.session);
}
else {
this._options.login.session = _session;
}
}
}
}
if (typeof this._options.logLevel === 'string') {
this._options.logLevel = String(this._options?.logLevel).split('|');
}
index_js_1.Logger.setLogLevel(this._options.logLevel);
if (options.experimental) {
index_js_1.Logger.warning('If you use the experimental option, we strongly do not recommend using this function.');
}
}
this._cacheMessage = new Map();
this.api = new Telegram_js_1.Telegram(this);
this._rndMsgId = new platform_node_js_1.Sessions.MsgId();
if (this._options.plugins && this._options.plugins?.length) {
index_js_1.Logger.debug('Registering plugin.');
for (const plugin of this._options.plugins) {
if (typeof plugin === 'function') {
try {
await plugin(this._plugin);
}
catch (error) {
index_js_1.Logger.error(`Failed to initialize plug-in: ${plugin.name}`, error);
}
}
else if (typeof plugin === 'object' && 'init' in plugin) {
try {
await plugin.init(this._plugin);
}
catch (error) {
index_js_1.Logger.error(`Failed to initialize plug-in: ${plugin.constructor.name}`, error);
}
}
}
}
}
async stop() {
index_js_1.Logger.info('Gracefully Stop.');
if (this._options.login?.session && typeof this._options.login.session !== 'string') {
index_js_1.Logger.info('Saving session before killed.');
await this._options.login.session.save();
}
if (this._plugin.getEventHandler('gracefullyStop').length) {
index_js_1.Logger.debug(`Running ${this._plugin.getEventHandler('gracefullyStop').length} gracefully stop handler plugin.`);
for (const plugin of this._plugin.getEventHandler('gracefullyStop')) {
try {
await plugin({ client: this });
}
catch (error) {
index_js_1.Logger.error(`Failed to running plug-in (gracefullyStop) ${plugin.name}`, error);
}
}
}
await this._client._session.stop();
}
async run() {
await this._init();
if (this._options.experimental.shutdown) {
shutdown(this);
}
if (this._plugin.getEventHandler('beforeStart').length) {
index_js_1.Logger.debug(`Running ${this._plugin.getEventHandler('beforeStart').length} before start handler plugin.`);
for (const plugin of this._plugin.getEventHandler('beforeStart')) {
try {
await plugin({ client: this });
}
catch (error) {
index_js_1.Logger.error(`Failed to running plug-in (beforeStart) ${plugin.name}`, error);
}
}
}
if (this._plugin.getEventHandler('onLogin').length) {
if (this._plugin.getEventHandler('onLogin').length > 1) {
index_js_1.Logger.info(`The plug-in of login handler is more than one, to prevent several undesirable things, only the last plug-in will be used. {${this._plugin.getEventHandler('onLogin').length}}`);
}
const plugin = this._plugin.getEventHandler('onLogin')[this._plugin.getEventHandler('onLogin').length - 1];
try {
const user = await plugin({ client: this });
if (user) {
this._me = user.users[0];
}
}
catch (error) {
index_js_1.Logger.error(`Failed to running plug-in (onLogin) ${plugin.name}`, error);
}
}
else {
const user = await (0, Cli_js_1.LoginWithCLI)(this);
if (user) {
this._me = user.users[0];
}
}
this._client.addHandler((update) => this.handleUpdate(update, this));
if (this._options.experimental.alwaysSync) {
this.syncChannelUpdate(this)();
}
index_js_1.Logger.info('Client is running');
if (this._me) {
index_js_1.Logger.log(`Loggined as : ${this._me.lastName ? `${this._me.firstName} ${this._me.lastName}` : this._me.firstName} - ${this._me.id}`);
if (this._options.experimental.onlineOnStart) {
await this._client.invoke(new platform_node_js_1.Raw.account.UpdateStatus({ offline: false }));
}
}
if (this._plugin.getEventHandler('afterStart').length) {
index_js_1.Logger.debug(`Running ${this._plugin.getEventHandler('afterStart').length} after start handler plugin.`);
for (const plugin of this._plugin.getEventHandler('afterStart')) {
try {
await plugin({ client: this });
}
catch (error) {
index_js_1.Logger.error(`Failed to running plug-in (afterStart) ${plugin.name}`, error);
}
}
}
return true;
}
restart() {
this._client._session.restart();
this._cacheMessage = new Map();
this._rndMsgId = new platform_node_js_1.Sessions.MsgId();
this._commonBox = new Map();
this._localPtsChat = new Map();
}
getMe() {
return platform_node_js_1.Clients.Auth.getMe.call(this._client);
}
connect() {
return platform_node_js_1.Clients.Session.connect.call(this._client);
}
exportSession() {
return this._client.exportSession();
}
get core() {
return this._client;
}
get conversation() {
return this._conversation;
}
}
exports.Snake = Snake;
function shutdown(...clients) {
const handler = async () => {
for (const client of clients) {
await client.stop();
}
return platform_node_js_1.sysprc.exit();
};
platform_node_js_1.sysprc.on('SIGINT', handler);
platform_node_js_1.sysprc.on('SIGTERM', handler);
index_js_1.Logger.info(`Gracefull Stop enable for ${clients.length} clients`);
}