Skip to content

Commit

Permalink
Merge branch 'ShirokamiRyzen:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
NeofetchNpc authored Dec 12, 2024
2 parents cfe6a80 + 0ee1d2b commit 0e41c42
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 68 deletions.
101 changes: 84 additions & 17 deletions plugins/info-speedtest.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,90 @@
import cp from 'child_process'
import { promisify } from 'util'
let exec = promisify(cp.exec).bind(cp)
var handler = async (m) => {
await conn.reply(m.chat, "Wait", m)
let o
import { exec as execCallback } from 'child_process'
const exec = promisify(execCallback);

const handler = async (m, { conn }) => {

m.reply(wait)

try {
o = await exec('python3 speed.py --share')
} catch (e) {
o = e
} finally {
let { stdout, stderr } = o
if (stdout.trim()) m.reply(stdout)
if (stderr.trim()) m.reply(stderr)
const { stdout, stderr } = await exec('python3 speed.py --share --secure');

const { download, upload, ping, server, client, timestamp, bytes_sent, bytes_received, share, } = JSON.parse(stdout.match(/\{(.|\n)*\}/)[0]);

const message = `
🚀 Download Speed: ${formatSpeed(download)} Mbps
📤 Upload Speed: ${formatSpeed(upload)} Mbps
⏱ Ping: ${ping} ms
Server Details:
Name: ${server.name}
Country: ${server.country}
Sponsor: ${server.sponsor}
Client Details:
IP: #HIDDEN
ISP: ${client.isp}
Country: ${client.country}
📅 Timestamp: ${formatTimestamp(timestamp)}
💾 Bytes Sent: ${formatBytes(bytes_sent)}
💽 Bytes Received: ${formatBytes(bytes_received)}
🔗 Share Link: ${share}
`;

await conn.reply(m.chat, message, m, {
contextInfo: {
mentionedJid: [m.sender],
externalAdReply: {
body: "SPEEDTEST",
containsAutoReply: true,
mediaType: 1,
mediaUrl: 'https://www.speedtest.net/id',
renderLargerThumbnail: true,
showAdAttribution: true,
sourceUrl: 'https://www.speedtest.net/id',
thumbnail: await conn.resize(share, 350, 200),
thumbnailUrl: share,
title: " O O K L A ",
},
},
});
} catch (error) {
console.error('Terjadi kesalahan:', error.message);
}
}
handler.help = ['speedtest']
handler.tags = ['info']
handler.command = /^(speedtest)$/i
};

handler.help = ['speedtest'];
handler.tags = ['info'];
handler.command = /^(speedtest)$/i;

handler.register = true
handler.rowner = true

export default handler

function formatSpeed(speed) {
return (speed / (1024 * 1024)).toFixed(2);
}

function formatTimestamp(timestamp) {
const date = new Date(timestamp);
const options = {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
};
return new Intl.DateTimeFormat('en-US', options).format(date);
}

export default handler
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
44 changes: 10 additions & 34 deletions plugins/youtube-yta.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,60 +3,36 @@ import fs from 'fs'
import { pipeline } from 'stream'
import { promisify } from 'util'
import os from 'os'
import yts from 'yt-search'

const streamPipeline = promisify(pipeline);

// Fungsi untuk mengekstrak ID video dari URL
const extractVideoID = (url) => {
const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
const match = url.match(regex);
return match ? match[1] : null;
};

let handler = async (m, { conn, command, text, usedPrefix }) => {
if (!text) throw `Usage: ${usedPrefix}${command} <YouTube Video URL>`;
const videoUrl = text;

// Ekstrak ID video dari URL
const videoID = extractVideoID(videoUrl);
if (!videoID) throw new Error('Format URL tidak valid.');

m.reply(wait)
m.reply(wait);

try {
// Mengambil informasi video menggunakan yt-search dengan ID video
const videoInfo = await yts(videoID);
if (!videoInfo || !videoInfo.videos.length) throw new Error('Video tidak ditemukan.');

const video = videoInfo.videos[0];
const { title, timestamp: lengthSeconds, views, ago: uploadDate, thumbnail } = video;

// Fetch audio URL dari ryzendesu API
const response = await axios.get(`${APIs.ryzen}/api/downloader/ytmp3?url=${encodeURIComponent(videoUrl)}`);

if (!response.data.url) throw new Error('URL audio tidak tersedia.');
const { url } = response.data;

if (!url) throw new Error('URL audio tidak tersedia.');
if (!response.data || !response.data.url) throw new Error('Audio not found or unavailable.');

const { title, lengthSeconds, views, uploadDate, thumbnail, url, filename, author } = response.data;

const tmpDir = os.tmpdir();
const filePath = `${tmpDir}/${title}.mp3`;
const filePath = `${tmpDir}/${filename}`;

// Mengunduh file audio menggunakan URL
const audioResponse = await axios({
method: 'get',
url: url,
responseType: 'stream'
});

// Menulis stream ke file
const writableStream = fs.createWriteStream(filePath);
await streamPipeline(audioResponse.data, writableStream);

const info = `Title: ${title}\nLength: ${lengthSeconds}\nViews: ${views}\nUploaded: ${uploadDate}`;
const info = `Title: ${title}\n*Author*: ${author}\nLength: ${lengthSeconds}\nViews: ${views}\nUploaded: ${uploadDate}`;

// Mengirim file audio
await conn.sendMessage(m.chat, {
document: {
url: filePath,
Expand All @@ -66,17 +42,17 @@ let handler = async (m, { conn, command, text, usedPrefix }) => {
caption: info,
}, { quoted: m });

// Membersihkan: hapus file audio
fs.unlink(filePath, (err) => {
if (err) {
console.error(`Gagal menghapus file audio: ${err}`);
console.error(`Failed to delete audio file: ${err}`);
} else {
console.log(`Berhasil menghapus file audio: ${filePath}`);
console.log(`Successfully deleted audio file: ${filePath}`);
}
});

} catch (error) {
console.error('Error:', error.message);
throw `Error: ${error.message}. Silakan periksa format URL dan coba lagi.`;
throw `Error: ${error.message}. Please check the URL and try again.`;
}
};

Expand Down
24 changes: 7 additions & 17 deletions plugins/youtube-ytv.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,36 @@ let handler = async (m, { conn, command, text, usedPrefix }) => {
if (!text) throw `Usage: ${usedPrefix}${command} url reso`;

m.reply(wait);

// Parse URL and resolution from the input text
const args = text.split(' ');
const videoUrl = args[0];
const resolution = args[1] || '480';

// API URL to fetch the video download link
const apiUrl = `${APIs.ryzen}/api/downloader/ytmp4?url=${encodeURIComponent(videoUrl)}&reso=${resolution}`;

try {
// Fetch video URL from the API
const response = await axios.get(apiUrl);
const { url: videoStreamUrl, filename } = response.data;
const { url: videoStreamUrl, filename, lengthSeconds, title, uploadDate, views, author } = response.data;

if (!videoStreamUrl) throw 'Video URL not found in API response.';

// Define the temporary directory and file name
const tmpDir = os.tmpdir();
const filePath = `${tmpDir}/${filename}`;

// Download video directly to a local file
const writer = fs.createWriteStream(filePath);
const downloadResponse = await axios({
url: videoStreamUrl,
method: 'GET',
responseType: 'stream',
});

// Pipe the stream directly to the file
downloadResponse.data.pipe(writer);

// Wait until the download is complete
await new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});

// Process the video with ffmpeg to fix metadata (duration)
// Fix the video duration using ffmpeg
const outputFilePath = `${tmpDir}/${filename.replace('.mp4', '_fixed.mp4')}`;
await new Promise((resolve, reject) => {
exec(`ffmpeg -i "${filePath}" -c copy "${outputFilePath}"`, (error) => {
Expand All @@ -53,10 +45,9 @@ let handler = async (m, { conn, command, text, usedPrefix }) => {
});
});

// Message caption with the filename from the API
const caption = `Here's the video for you @${m.sender.split('@')[0]}\n\nFilename: ${filename}`;
const caption = `Ini kak videonya @${m.sender.split('@')[0]}\n\n*Title*: ${title} (${resolution})\n*Author*: ${author}\n*Duration*: ${lengthSeconds}\n*Views*: ${views}\n*Uploaded*: ${uploadDate}`;

// Send the video with the caption directly from the processed file
// Send the fixed video
await conn.sendMessage(m.chat, {
video: { url: outputFilePath },
mimetype: 'video/mp4',
Expand All @@ -65,7 +56,7 @@ let handler = async (m, { conn, command, text, usedPrefix }) => {
mentions: [m.sender],
}, { quoted: m });

// Delete the original downloaded file
// Clean up temporary files
fs.unlink(filePath, (err) => {
if (err) {
console.error(`Failed to delete original video file: ${err}`);
Expand All @@ -74,12 +65,11 @@ let handler = async (m, { conn, command, text, usedPrefix }) => {
}
});

// Delete the processed file
fs.unlink(outputFilePath, (err) => {
if (err) {
console.error(`Failed to delete processed video file: ${err}`);
console.error(`Failed to delete fixed video file: ${err}`);
} else {
console.log(`Deleted processed video file: ${outputFilePath}`);
console.log(`Deleted fixed video file: ${outputFilePath}`);
}
});

Expand Down

0 comments on commit 0e41c42

Please sign in to comment.