2021-08-12 17:34:49 +00:00
|
|
|
const { Octokit } = require('@octokit/rest');
|
|
|
|
const got = require('got');
|
2024-09-23 18:07:20 +00:00
|
|
|
const { createGitHubTokenStrategy } = require('./github-token');
|
2021-08-12 17:34:49 +00:00
|
|
|
|
|
|
|
async function getAssetContents (repo, assetId) {
|
2024-09-23 18:07:20 +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({
|
|
|
|
owner: 'electron',
|
|
|
|
repo,
|
|
|
|
asset_id: assetId,
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/octet-stream'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const { url, headers } = requestOptions;
|
2024-09-23 18:07:20 +00:00
|
|
|
headers.authorization = `token ${(await octokit.auth()).token}`;
|
2021-08-12 17:34:49 +00:00
|
|
|
|
|
|
|
const response = await got(url, {
|
|
|
|
followRedirect: false,
|
|
|
|
method: 'HEAD',
|
2024-09-17 22:27:27 +00:00
|
|
|
headers,
|
|
|
|
throwHttpErrors: false
|
2021-08-12 17:34:49 +00:00
|
|
|
});
|
2024-09-17 22:27:27 +00:00
|
|
|
|
|
|
|
if (response.statusCode !== 302 && response.statusCode !== 301) {
|
|
|
|
console.error('Failed to HEAD github asset contents for redirect: ' + url);
|
|
|
|
throw new Error('Unexpected status HEAD\'ing github asset for redirect: ' + response.statusCode);
|
|
|
|
}
|
|
|
|
|
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 22:27:27 +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 22:27:27 +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;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
getAssetContents
|
|
|
|
};
|