File size: 8,463 Bytes
fc362a5
 
 
 
94bfb19
fc362a5
f1cfc72
 
 
fc362a5
f1cfc72
fc362a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1cfc72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
const { Telegraf } = require('telegraf');
const fetch = require('node-fetch');
const fs = require('fs');
const axios = require('axios');
const instagramDl = require('@sasmeee/igdl');
const { Headers } = fetch;
const express = require('express');
const app = express();
const port = 7860;

const botToken = '6773241108:AAHz1TCLqpjR880ZLYHdaqJsL9Vxoqcr7jo'; // Replace with your Telegram bot token
const bot = new Telegraf(botToken);

const headers = new Headers();

const getRedirectUrl = async (url) => {
    if (url.includes("vm.tiktok.com") || url.includes("vt.tiktok.com")) {
        url = await fetch(url, {
            redirect: "follow",
            follow: 10,
        });
        url = url.url;
        console.log("[*] Redirecting to: " + url);
    }
    return url;
};

const getIdVideo = async (url) => {
    if (url.includes("/t/")) {
        url = await new Promise((resolve) => {
            require("follow-redirects").https.get(url, function (res) {
                return resolve(res.responseUrl);
            });
        });
    }
    const matching = url.includes("/video/");
    const matchingPhoto = url.includes("/photo/");
    let idVideo = url.substring(
        url.indexOf("/video/") + 7,
        url.indexOf("/video/") + 26
    );
    if (matchingPhoto)
        idVideo = url.substring(
            url.indexOf("/photo/") + 7,
            url.indexOf("/photo/") + 26
        );
    else if (!matching) {
        throw new Error("URL not found");
    }
    return idVideo.length > 19
        ? idVideo.substring(0, idVideo.indexOf("?"))
        : idVideo;
};

const getVideo = async (url, watermark) => {
    const idVideo = await getIdVideo(url);
    const API_URL = `https://api22-normal-c-alisg.tiktokv.com/aweme/v1/feed/?aweme_id=${idVideo}&iid=7318518857994389254&device_id=7318517321748022790&channel=googleplay&app_name=musical_ly&version_code=300904&device_platform=android&device_type=ASUS_Z01QD&version=9`;
    const request = await fetch(API_URL, {
        method: "OPTIONS",
        headers: headers,
    });
    const body = await request.text();
    try {
        var res = JSON.parse(body);
    } catch (err) {
        console.error("Error:", err);
        console.error("Response body:", body);
        throw err;
    }

    if (res.aweme_list[0].aweme_id != idVideo) {
        return null;
    }

    let urlMedia = "";
    let image_urls = [];

    if (!!res.aweme_list[0].image_post_info) {
        console.log("[*] Video is slideshow");
        res.aweme_list[0].image_post_info.images.forEach((element) => {
            image_urls.push(element.display_image.url_list[1]);
        });
    } else {
        urlMedia = watermark
            ? res.aweme_list[0].video.download_addr.url_list[0]
            : res.aweme_list[0].video.play_addr.url_list[0];
    }

    return {
        url: urlMedia,
        images: image_urls,
        id: idVideo,
    };
};

const downloadMedia = async (item) => {
    const folder = "downloads/";
    if (!fs.existsSync(folder)) fs.mkdirSync(folder, { recursive: true });

    if (item.images.length != 0) {
        console.log("[*] Downloading Slideshow");
        let index = 0;
        for (const image_url of item.images) {
            const fileName = `${item.id}_${index}.jpeg`;
            if (fs.existsSync(folder + fileName)) {
                console.log(`[!] File '${fileName}' already exists. Skipping`);
                continue;
            }
            index++;
            const response = await fetch(image_url);
            const buffer = await response.buffer();
            fs.writeFileSync(folder + fileName, buffer);
        }
    } else {
        const fileName = `${item.id}.mp4`;
        if (fs.existsSync(folder + fileName)) {
            console.log(`[!] File '${fileName}' already exists. Skipping`);
            return;
        }
        const response = await fetch(item.url);
        const buffer = await response.buffer();
        fs.writeFileSync(folder + fileName, buffer);
    }
};

bot.start((ctx) => ctx.reply('My love! send me a TikTok or Instagram video link baby 😘'));

bot.on('text', async (ctx) => {
    const url = ctx.message.text;

    if (!url.includes('instagram.com') && !url.includes('tiktok.com')) {
        return ctx.reply('Baby, the url is not correct...');
    }

    try {
        const processingMessage = await ctx.reply('🤗Honey, wait a bit my love. Processing the URL...');
        let data;
        if (url.includes('instagram.com')) {
            const dataList = await instagramDl(url);
            const downloadLink = dataList[0].download_link;
            const response = await axios.get(downloadLink, { responseType: 'stream' });
            await ctx.editMessageText('Uploading the video...my baby ><', { message_id: processingMessage.message_id });
            const filePath = `video_${Date.now()}.mp4`;
            const writer = fs.createWriteStream(filePath);
            response.data.pipe(writer);

            writer.on('finish', () => {
                ctx.replyWithVideo({ source: filePath })
                    .then(() => {
                        fs.unlinkSync(filePath); // Delete the file after sending
                    })
                    .catch((error) => {
                        console.error('Error sending video:', error);
                        ctx.reply('Failed to send the video.');
                    });
            });

            writer.on('error', (error) => {
                console.error('Error downloading video:', error);
                ctx.reply('Failed to download the video.');
            });
        } else if (url.includes('tiktok.com')) {
            const processingMessage = await ctx.reply('🤗Honey, wait a bit my love. Processing the URL...');
            const resolvedUrl = await getRedirectUrl(url);
            data = await getVideo(resolvedUrl, false);

            if (data == null) {
                return ctx.reply('Video not found or has been deleted.');
            }

            await downloadMedia(data);

            if (data.images.length > 0) {
                data.images.forEach((image, index) => {
                    ctx.replyWithPhoto({ url: image });
                });
            } else {
                const filePath = `downloads/${data.id}.mp4`;
                await ctx.editMessageText('Uploading the video...my baby ><', { message_id: processingMessage.message_id });
                ctx.replyWithVideo({ source: filePath }, { caption: 'Downloaded TikTok Video' })
                    .then(() => {
                        fs.unlinkSync(filePath); // Delete the file after sending
                    })
                    .catch((error) => {
                        console.error('Error sending video:', error);
                        ctx.reply('Failed to send the video.');
                    });
            }
        }
    } catch (error) {
        console.error('Error:', error);
        ctx.reply('Failed to process the URL.');
    }
});

bot.launch();

console.log('Bot is running...');

app.get('/download', async (req, res) => {
    const url = req.query.url;
    const watermark = req.query.watermark === 'true';

    if (!url) {
        return res.status(400).json({ error: 'URL parameter is required' });
    }

    try {
        const resolvedUrl = await getRedirectUrl(url);
        const data = await getVideo(resolvedUrl, watermark);

        if (data == null) {
            return res.status(404).json({ error: 'Video not found or has been deleted' });
        }

        await downloadMedia(data);

        if (data.images.length > 0) {
            res.json({
                message: 'Slideshow downloaded successfully',
                files: data.images.map((_, index) => `${data.id}_${index}.jpeg`)
            });
        } else {
            const filePath = `downloads/${data.id}.mp4`;
            res.download(filePath, (err) => {
                if (err) {
                    console.error('Error sending file:', err);
                    res.status(500).json({ error: 'Error sending file' });
                }
                // Optionally delete the file after sending
                // fs.unlinkSync(filePath);
            });
        }
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

app.listen(port, () => {
    console.log(`TikTok Downloader API listening at http://localhost:${port}`);
});