MCPcopy Index your code
hub / github.com/APKLab/APKLab / downloadFile

Function downloadFile

src/utils/downloader.ts:69–140  ·  view source on GitHub ↗
(
    urlString: string,
    redirectCount = 0,
)

Source from the content-addressed store, hash-verified

67 * @returns a Buffer of the file contents.
68 */
69export async function downloadFile(
70 urlString: string,
71 redirectCount = 0,
72): Promise<Buffer> {
73 if (redirectCount >= MAX_REDIRECTS) {
74 throw new Error(`Too many redirects (max ${MAX_REDIRECTS})`);
75 }
76
77 const buffers: Buffer[] = [];
78
79 return new Promise<Buffer>((resolve, reject) => {
80 const request = https.request(new URL(urlString), (response) => {
81 if (
82 (response.statusCode === 301 || response.statusCode === 302) &&
83 response.headers.location
84 ) {
85 // Redirect - download from new location
86 return resolve(
87 downloadFile(response.headers.location, redirectCount + 1),
88 );
89 } else if (response.statusCode !== 200) {
90 // Download failed - print error message
91 const errorMsg = `Download failed with response code: ${response.statusCode}`;
92 outputChannel.appendLine(errorMsg);
93 reject(new Error(errorMsg));
94 }
95
96 // Downloading - hook up events
97 const contentLength = response.headers["content-length"]
98 ? response.headers["content-length"]
99 : "0";
100 const packageSize = parseInt(contentLength, 10);
101 let downloadedBytes = 0;
102 let downloadPercentage = 0;
103
104 outputChannel.appendLine(
105 `Download size: ${(packageSize / 1024 / 1024).toFixed(2)} MB`,
106 );
107
108 response.on("data", (data) => {
109 downloadedBytes += data.length;
110 buffers.push(data);
111
112 // Update status bar item with percentage
113 const newPercentage = Math.ceil(
114 100 * (downloadedBytes / packageSize),
115 );
116 if (newPercentage !== downloadPercentage) {
117 downloadPercentage = newPercentage;
118 outputChannel.appendLine(
119 `Downloaded ${downloadPercentage}%`,
120 );
121 }
122 });
123
124 response.on("end", () => {
125 resolve(Buffer.concat(buffers));
126 });

Callers 2

getUpdateConfigFunction · 0.90
downloadToolFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected