hk_bot/utils.ts
2022-12-09 19:38:09 +03:00

149 lines
5.4 KiB
TypeScript

import Docker from "dockerode";
import logger from "./logger";
import {database as db,settings} from './database';
// import Hero from "@ulixee/hero";
// import Miner from "@ulixee/miner";
import { sleep } from "telegram/Helpers";
import { AccountInterface } from "./interfaces/databaseInterface";
import * as telegram from 'telegram';
import axios from "axios";
import cliProgress from "cli-progress"
export const randomAB=function(a:number,b:number){
return Math.floor(Math.random() * (b - a + 1) + a)
}
export const isBannedByClient=async function(client:telegram.TelegramClient,username: string): Promise<boolean> {
const blockedUsers=(await client.invoke(new telegram.Api.contacts.GetBlocked({limit:2147483647}))).users as telegram.Api.User[];
for (const blockedUser of blockedUsers){
if (blockedUser.username!==undefined && blockedUser.username==username.replace('@','')){
return true;
}
}
return false;
}
export const getMessagesByEntity=async function(client:telegram.TelegramClient,chatEntity:telegram.Api.Chat | telegram.Api.User,entity: telegram.Api.User | telegram.Api.User,params={}){
var messages=new telegram.helpers.TotalList<telegram.Api.Message>;
for (const message of await client.getMessages(chatEntity,params)){
if ((message.sender as telegram.Api.User).username==entity.username){
messages.push(message);
}
}
return messages;
}
export const arrayWithoutElementAtIndex = function (arr: AccountInterface[] | [], index: number) {
return arr.filter(function(value, arrIndex) {
return index !== arrIndex;
});
}
export const getIP=async function (proxyPort: number): Promise<string | null> {
let data: string | PromiseLike<string | null> | null
try{
data=(await axios.get('http://api.ipify.org',{
proxy:{
host:'127.0.0.1',
port:proxyPort
},
timeout:100_000
})).data;
} catch (err){
logger.debug(err);
return null;
}
if ((await data)==null || (await data)!.trim()==""){
return null
}
return await data
}
export const waitNewMessages=async function(client: telegram.TelegramClient,worker: AccountInterface,chatEntity: telegram.Api.Chat | telegram.Api.User,idOfLastMessage: number,timeout: number=20): Promise<void>{
const start_time=new Date();
while ((await client.getMessages(chatEntity,{minId:idOfLastMessage,limit:2147483647})).length==0){
if ((+(new Date())-+start_time)/1000>=timeout){
logger.error(`${worker.phoneNumber} | Bot didnt answer for ${timeout}s`);
throw new Error('Is bot working?');
}
}
logger.debug(`${worker.phoneNumber} | Bot answered`);
}
export const startNewTorDocker=async function(proxyPort: number,socksPort: number,controlPort: number,mainProgressBar: cliProgress.MultiBar,timeout: number=200): Promise<Docker.Container>{
timeout*=2;
let docker = new Docker({socketPath: '/var/run/docker.sock'});
let isPulled=false;
mainLoop:
for (const image of await docker.listImages()){
const tags=image.RepoTags;
if (tags!==undefined)
for (const repoTag of tags){
if (repoTag.search('dperson/torproxy:latest')!=-1){
isPulled=true;
break mainLoop;
}
}
}
if (isPulled!=true){
await docker.pull('dperson/torproxy:latest');
}
// bugy shit
const options: Docker.ContainerCreateOptions={
Image:'dperson/torproxy',
Env:[
"PASSWORD=qwerty",
"LOCATION=US",
"TOR_NewCircuitPeriod=50",
],
ExposedPorts:{},
HostConfig:{
PortBindings:{
'8118/tcp':[{
HostPort: `${proxyPort}`
}],
'9050/tcp':[{
HostPort: `${socksPort}`
}],
'9051/tcp':[{
HostPort: `${controlPort}`
}]
}
},
Healthcheck:{
Interval:2*1_000_000_000,
Timeout:50*1_000_000_000,
StartPeriod:50*1_000_000_000,
// Test:['CMD_SHELL',`curl -sx localhost:8118 'https://check.torproject.org/' | grep -qm1 Congratulations`]
}
}
const container=await docker.createContainer(options);
await container.start();
const progressBar=mainProgressBar.create(timeout/2, 0,{status:`Starting docker${(settings.logLevel=='debug') ? ` ${proxyPort} ${socksPort} ${controlPort}` : ''}`});
while ((await container.inspect())!.State.Health!.Status!='healthy'){
const state=(await container.inspect())!.State.Health!.Status
if (progressBar.getProgress()>=timeout){
await container.kill();
progressBar.update(timeout/2,{status:'Failed'})
progressBar.stop();
throw new Error(`Docker ${container.id} is broken`);
}
if (state=='unhealthy'){
await container.kill();
progressBar.update(timeout/2,{status:'Docker is unhealthy...'})
progressBar.stop();
return await startNewTorDocker(proxyPort,socksPort,controlPort,mainProgressBar,timeout/2);
}
progressBar.increment();
await sleep(2000);
}
progressBar.update(0,{status:'Started'})
progressBar.stop();
return container;
}