MCPcopy Create free account
hub / github.com/PrivacySafe/sticktock / downloadFileHelper

Function downloadFileHelper

backend-api/utils/disk-utils.ts:21–140  ·  view source on GitHub ↗
(
  url: string,
  dirPath: string,
  filePath: string,
  cookies?: string
)

Source from the content-addressed store, hash-verified

19 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36';
20
21export const downloadFileHelper = async (
22 url: string,
23 dirPath: string,
24 filePath: string,
25 cookies?: string
26): Promise<void> => {
27 ensureDirectoryExistence(filePath);
28
29 // Delete any existing partial download
30 if (fs.existsSync(filePath)) {
31 fs.unlinkSync(filePath);
32 }
33
34 const headers = {
35 'User-Agent': USER_AGENT,
36 Accept: '*/*',
37 'Accept-Language': 'en-US,en;q=0.9',
38 'Accept-Encoding': 'identity', // Prevent gzip to avoid corruption
39 Connection: 'keep-alive',
40 Range: 'bytes=0-', // Support range requests
41 Referer: 'https://www.tiktok.com/',
42 ...(cookies ? { Cookie: cookies } : {}),
43 };
44
45 return new Promise((resolve, reject) => {
46 const handleResponse = (response: http.IncomingMessage) => {
47 // Handle redirects
48 if (response.statusCode === 301 || response.statusCode === 302) {
49 const redirectUrl = response.headers.location;
50 if (!redirectUrl) {
51 reject(new Error('Redirect location not found'));
52 return;
53 }
54 logger.info(`Following redirect to: ${redirectUrl}`);
55 const redirectReq = https.get(redirectUrl, { headers }, handleResponse);
56 redirectReq.on('error', reject);
57 return;
58 }
59
60 // Check content type
61 const contentType = response.headers['content-type'];
62 if (
63 !contentType?.includes('video') &&
64 !contentType?.includes('audio') &&
65 !contentType?.includes('image')
66 ) {
67 reject(new Error(`Unexpected content type: ${contentType}`));
68 return;
69 }
70
71 // Check content length
72 const contentLength = parseInt(
73 response.headers['content-length'] || '0',
74 10
75 );
76 if (contentLength === 0) {
77 reject(new Error('Content length is 0'));
78 return;

Callers 2

fetchPostByUrlAndModeFunction · 0.90
downloadPostByUrlFunction · 0.90

Calls 1

ensureDirectoryExistenceFunction · 0.70

Tested by

no test coverage detected