2024-10-01 00:55:27 +00:00
|
|
|
import { Octokit } from '@octokit/rest';
|
|
|
|
import got from 'got';
|
2024-10-03 02:10:44 +00:00
|
|
|
|
2024-10-01 00:55:27 +00:00
|
|
|
import { createGitHubTokenStrategy } from './github-token';
|
2024-10-01 20:51:40 +00:00
|
|
|
import { ELECTRON_ORG, ElectronReleaseRepo } from './types';
|
2021-08-12 17:34:49 +00:00
|
|
|
|
2024-10-01 00:55:27 +00:00
|
|
|
export async function getAssetContents (repo: ElectronReleaseRepo, assetId: number) {
|
2024-09-23 16:39:54 +00:00
|
|
|
const octokit = new Octokit({
|
|
|
|
userAgent: 'electron-asset-fetcher',
|
|
|
|
authStrategy: createGitHubTokenStrategy(repo)
|
|
|
|
});
|
|
|
|
|
2021-08-12 17:34:49 +00:00
|
|
|
const requestOptions = octokit.repos.getReleaseAsset.endpoint({
|
2024-10-01 20:51:40 +00:00
|
|
|
owner: ELECTRON_ORG,
|
2021-08-12 17:34:49 +00:00
|
|
|
repo,
|
|
|
|
asset_id: assetId,
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/octet-stream'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const { url, headers } = requestOptions;
|
2024-10-01 00:55:27 +00:00
|
|
|
headers.authorization = `token ${(await octokit.auth() as { token: string }).token}`;
|
2021-08-12 17:34:49 +00:00
|
|
|
|
|
|
|
const response = await got(url, {
|
|
|
|
followRedirect: false,
|
|
|
|
method: 'HEAD',
|
2024-10-01 00:55:27 +00:00
|
|
|
headers: headers as Record<string, string>,
|
2024-09-17 21:30:51 +00:00
|
|
|
throwHttpErrors: false
|
2021-08-12 17:34:49 +00:00
|
|
|
});
|
2024-09-17 21:30:51 +00:00
|
|
|
|
2024-09-17 21:49:59 +00:00
|
|
|
if (response.statusCode !== 302 && response.statusCode !== 301) {
|
2024-09-17 21:30:51 +00:00
|
|
|
console.error('Failed to HEAD github asset contents for redirect: ' + url);
|
2024-09-17 21:49:59 +00:00
|
|
|
throw new Error('Unexpected status HEAD\'ing github asset for redirect: ' + response.statusCode);
|
2024-09-17 21:30:51 +00:00
|
|
|
}
|
|
|
|
|
2021-08-12 17:34:49 +00:00
|
|
|
if (!response.headers.location) {
|
2021-08-13 20:15:39 +00:00
|
|
|
console.error(response.headers, `${response.body}`.slice(0, 300));
|
2021-08-12 17:34:49 +00:00
|
|
|
throw new Error(`cannot find asset[${assetId}], asset download did not redirect`);
|
|
|
|
}
|
|
|
|
|
2024-09-17 21:30:51 +00:00
|
|
|
const fileResponse = await got(response.headers.location, {
|
|
|
|
throwHttpErrors: false
|
|
|
|
});
|
|
|
|
|
2021-08-13 20:26:27 +00:00
|
|
|
if (fileResponse.statusCode !== 200) {
|
2021-08-13 20:15:39 +00:00
|
|
|
console.error(fileResponse.headers, `${fileResponse.body}`.slice(0, 300));
|
2024-09-17 21:49:59 +00:00
|
|
|
throw new Error(`cannot download asset[${assetId}] from ${response.headers.location}, got status: ${fileResponse.statusCode}`);
|
2021-08-12 17:34:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return fileResponse.body;
|
|
|
|
}
|