Skip to content

Commit

Permalink
stable
Browse files Browse the repository at this point in the history
  • Loading branch information
besoeasy authored Nov 6, 2024
1 parent 20d6e8d commit 0d31f1d
Showing 1 changed file with 82 additions and 143 deletions.
225 changes: 82 additions & 143 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,176 +2,138 @@

require("dotenv").config();

// Import required functions

const { version } = require("./package.json");

const {
getGlobalStats,
downloadAria,
getDownloadStatus,
getOngoingDownloads,
cancelDownload,
} = require("./func/aria2.js");

const { getGlobalStats, downloadAria, getDownloadStatus, getOngoingDownloads, cancelDownload } = require("./func/aria2.js");
const { getIpData } = require("./func/ip.js");

const { bytesToSize, deleteOldFiles } = require("./func/utils.js");

const { Telegraf } = require("telegraf");

const sha256 = require("crypto-js/sha256");

// Load environment variables

if (!process.env.TELEGRAMBOT) {
console.error("Error: TELEGRAMBOT Environment Variable is not set.");
process.exit(1);
}

const bot = new Telegraf(process.env.TELEGRAMBOT);

// Hash user id

function cleanUser(str) {
return str.toString();
}

// Available commands

// Define commands with more user-friendly descriptions
const commands = [
"/about - About this bot",
"/start - Start this bot",
"/stats - Get global stats",
"/download <url> - Start a download",
"/ongoing - Get ongoing downloads",
"/status_<gid> - Get status of a download",
"/cancel_<gid> - Cancel a download",
"/ip - Get IP data",
"/about - Info about this bot",
"/start - Get started with the bot",
"/stats - View global download/upload stats",
"/download <url> - Start a new download",
"/downloading - Check ongoing downloads",
"/status_<gid> - Get specific download status",
"/cancel_<gid> - Cancel a specific download",
"/ip - Display server IP info",
];

const handleAbout = (ctx) => {
ctx.reply("https://github.com/besoeasy/telearia");
ctx.reply("🔗 GitHub Repo: [TeleAria](https://github.com/besoeasy/telearia)");
};

const handleStart = (ctx) => {
const user_id_hash = cleanUser(ctx.chat.id);

const download_url = process.env.TUNNELURL || "http://pi.local:6799";

ctx.reply(
`
TeleAria Version : ${version}
User Id : ${user_id_hash}
Downloads : ${download_url}/${user_id_hash}/
Available commands:\n${commands.join("\n")}
`
);
const userIdHash = cleanUser(ctx.chat.id);
const downloadUrl = process.env.TUNNELURL || "http://pi.local:6799";
ctx.replyWithMarkdown(`
**Welcome to TeleAria!** 🎉
🔹 **Version:** ${version}
🔹 **User ID:** ${userIdHash}
🔹 **Your Downloads:** [Manage here](${downloadUrl}/${userIdHash}/)
**Available Commands:**
${commands.map(cmd => `🔸 ${cmd}`).join("\n")}
`);
};

const handleStats = async (ctx) => {
try {
const { result: stats } = await getGlobalStats();

ctx.reply(
`Download speed: ${bytesToSize(stats.downloadSpeed)}\n` +
`Upload speed: ${bytesToSize(stats.uploadSpeed)}\n\n` +
`Active downloads: ${stats.numActive}\n` +
`Waiting downloads: ${stats.numWaiting}\n` +
`Stopped downloads: ${stats.numStopped}\n\n`
);
ctx.replyWithMarkdown(`
**📊 Global Stats:**
🔹 **Download Speed:** ${bytesToSize(stats.downloadSpeed)}
🔹 **Upload Speed:** ${bytesToSize(stats.uploadSpeed)}
🔹 **Active Downloads:** ${stats.numActive}
🔹 **Waiting Downloads:** ${stats.numWaiting}
🔹 **Stopped Downloads:** ${stats.numStopped}
`);
} catch (error) {
console.error(error);
ctx.reply("Failed to retrieve stats. Please try again later.");
ctx.reply("⚠️ Failed to retrieve stats. Please try again later.");
}
};

const handleDownload = async (ctx, url) => {
try {
const user_id_hash = cleanUser(ctx.chat.id);
const userIdHash = cleanUser(ctx.chat.id);
const downloadData = await downloadAria(userIdHash, url);
const downloadId = downloadData.result;

const ddta = await downloadAria(user_id_hash, url);
ctx.replyWithMarkdown(`
📥 **Download Started!**
const downloadId = ddta.result;

ctx.reply(
`Track all downloads with /ongoing \n\nDownload started with id: ${downloadId}\n\n/status_${downloadId}`
);
🔹 **Download ID:** ${downloadId}
🔹 **Track progress with** /status_${downloadId} or view all downloads with /downloading
`);
} catch (error) {
console.error(error);
ctx.reply("Failed to start download. Please try again later.");
ctx.reply("⚠️ Failed to start download. Please try again later.");
}
};

const handleStatus = async (ctx, downloadId) => {
try {
const ddta = await getDownloadStatus(downloadId);
const downloadSize_c = (
ddta.result.completedLength / 1024 / 1024 || 0
).toFixed(2);
const downloadSize_t = (ddta.result.totalLength / 1024 / 1024 || 0).toFixed(
2
);

let reply = `Download status: ${ddta.result.status}\n\nDownload size: ${downloadSize_c} MB / ${downloadSize_t} MB`;

if (ddta.result.status === "active") {
reply = reply + `\n\nCancel download with /cancel_${downloadId}`;
}
const downloadData = await getDownloadStatus(downloadId);
const completedSize = (downloadData.result.completedLength / 1024 / 1024).toFixed(2);
const totalSize = (downloadData.result.totalLength / 1024 / 1024).toFixed(2);

if (ddta.result.status === "active") {
const file = ddta.result.files[0].path;
let reply = `**🔍 Download Status:**\n\n**Status:** ${downloadData.result.status}\n**Progress:** ${completedSize} MB / ${totalSize} MB`;

reply = reply + `\n\nDownloading file: ${file}`;
if (downloadData.result.status === "active") {
reply += `\n🔸 **Cancel with** /cancel_${downloadId}`;
} else if (downloadData.result.status === "complete") {
const files = downloadData.result.files.map(file => file.path).join("\n");
reply += `\n🔹 **Downloaded Files:**\n${files}`;
}

if (ddta.result.status === "complete") {
const files = ddta.result.files.map((file) => file.path).join("\n");

reply = reply + `\n\nDownloaded files:\n${files}`;
}

ctx.reply(reply);
ctx.replyWithMarkdown(reply);
} catch (error) {
console.error(error);
ctx.reply(
`Failed to retrieve status for download id: ${downloadId}. Please try again later.`
);
ctx.reply(`⚠️ Failed to retrieve status for download ID: ${downloadId}. Please try again later.`);
}
};

const handleCancel = async (ctx, downloadId) => {
try {
await cancelDownload(downloadId);
ctx.reply(`Download canceled with id: ${downloadId}`);
ctx.reply(`✅ **Download with ID ${downloadId} canceled successfully.**`);
} catch (error) {
console.error(error);
ctx.reply(
`Failed to cancel download with id: ${downloadId}. Please try again later.`
);
ctx.reply(`⚠️ Failed to cancel download with ID: ${downloadId}. Please try again later.`);
}
};

const handleIpData = async (ctx) => {
try {
const ipdata = await getIpData();

const msg_ipdata = `
IP: ${ipdata.query}
Country: ${ipdata.country}
Region: ${ipdata.regionName}
City: ${ipdata.city}
ISP: ${ipdata.isp}
`;

ctx.reply(`${msg_ipdata}`);
const ipData = await getIpData();
ctx.replyWithMarkdown(`
**🌍 Server IP Information:**
🔹 **IP:** ${ipData.query}
🔹 **Country:** ${ipData.country}
🔹 **Region:** ${ipData.regionName}
🔹 **City:** ${ipData.city}
🔹 **ISP:** ${ipData.isp}
`);
} catch (error) {
console.error(error);
ctx.reply("Failed to retrieve IP data. Please try again later.");
ctx.reply("⚠️ Failed to retrieve IP data. Please try again later.");
}
};

Expand All @@ -185,9 +147,9 @@ const downloading = async (ctx) => {
for (const download of ongoingDownloads) {
const { gid, completedLength, totalLength, status } = download;

const downloadedSize = (completedLength / 1024 / 1024).toFixed(2); // Convert to MB
const totalSize = (totalLength / 1024 / 1024).toFixed(2); // Convert to MB
const progress = ((completedLength / totalLength) * 100).toFixed(2); // Calculate progress
const downloadedSize = (completedLength / 1024 / 1024).toFixed(2);
const totalSize = (totalLength / 1024 / 1024).toFixed(2);
const progress = ((completedLength / totalLength) * 100).toFixed(2);

reply += `🆔 **ID**: /status_${gid}\n`;
reply += `📊 **Status**: ${status}\n`;
Expand All @@ -197,87 +159,64 @@ const downloading = async (ctx) => {

ctx.replyWithMarkdown(reply);
} else {
ctx.reply("✅ No ongoing downloads.");
ctx.reply("✅ **No ongoing downloads.**");
}
} catch (error) {
console.error(error);
ctx.reply(
"⚠️ Failed to retrieve ongoing downloads. Please try again later."
);
ctx.reply("⚠️ Failed to retrieve ongoing downloads. Please try again later.");
}
};

// Handle messages
// Message handler
bot.on("message", async (ctx) => {
if (ctx.message.text) {
try {
// text classification
const { text } = ctx.message;
const [command, ...args] = text.split(" ");
const lowerCaseCommand = command.toLowerCase().trim();
const trimmedArgs = args.map((arg) => arg.trim());

const log = `@${ctx.from.username} (id: ${ctx.from.id}) at ${ctx.message.date}: ${text}`;

console.log(log);
const trimmedArgs = args.map(arg => arg.trim());

// handle commands
console.log(`@${ctx.from.username} (ID: ${ctx.from.id}): ${text}`);

switch (lowerCaseCommand) {
case "/clean":
deleteOldFiles(process.env.PURGEINTERVAL || 7);
ctx.reply("-- Cleaned --");
ctx.reply("🧹 **Old files cleaned!**");
break;

case "/about":
handleAbout(ctx);
break;

case "/start":
handleStart(ctx);
break;

case "/stats":
handleStats(ctx);
break;

case "/downloading":
downloading(ctx);
break;

case "/ip":
handleIpData(ctx);
break;

case "/download":
case "/dl":
if (trimmedArgs.length > 0) {
handleDownload(ctx, trimmedArgs[0]);
} else {
ctx.reply("Please provide a URL to download.");
}
if (trimmedArgs.length > 0) handleDownload(ctx, trimmedArgs[0]);
else ctx.reply("⚠️ **Please provide a URL to download.**");
break;

default:
if (lowerCaseCommand.startsWith("/status_")) {
handleStatus(ctx, lowerCaseCommand.split("_")[1]);
} else if (lowerCaseCommand.startsWith("/cancel_")) {
handleCancel(ctx, lowerCaseCommand.split("_")[1]);
} else {
ctx.reply(
`Unknown command: ${lowerCaseCommand}\n\nType /start to see available commands`
);
}
if (lowerCaseCommand.startsWith("/status_")) handleStatus(ctx, lowerCaseCommand.split("_")[1]);
else if (lowerCaseCommand.startsWith("/cancel_")) handleCancel(ctx, lowerCaseCommand.split("_")[1]);
else ctx.reply(`❔ Unknown command: ${lowerCaseCommand}\n\nType /start to see available commands.`);
}
} catch (error) {
console.error(error);
ctx.reply("An error occurred. Please try again later.");
ctx.reply("⚠️ An error occurred. Please try again later.");
}
}
});

bot.catch((err, ctx) => {
console.error(`Encountered an error for ${ctx.updateType}`, err);
console.error(`Error for ${ctx.updateType}`, err);
});

bot.launch();
Expand Down

0 comments on commit 0d31f1d

Please sign in to comment.