get-asset.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { Octokit } from '@octokit/rest';
  2. import got from 'got';
  3. import { createGitHubTokenStrategy } from './github-token';
  4. import { ELECTRON_ORG, ElectronReleaseRepo } from './types';
  5. export async function getAssetContents (repo: ElectronReleaseRepo, assetId: number) {
  6. const octokit = new Octokit({
  7. userAgent: 'electron-asset-fetcher',
  8. authStrategy: createGitHubTokenStrategy(repo)
  9. });
  10. const requestOptions = octokit.repos.getReleaseAsset.endpoint({
  11. owner: ELECTRON_ORG,
  12. repo,
  13. asset_id: assetId,
  14. headers: {
  15. Accept: 'application/octet-stream'
  16. }
  17. });
  18. const { url, headers } = requestOptions;
  19. headers.authorization = `token ${(await octokit.auth() as { token: string }).token}`;
  20. const response = await got(url, {
  21. followRedirect: false,
  22. method: 'HEAD',
  23. headers: headers as Record<string, string>,
  24. throwHttpErrors: false
  25. });
  26. if (response.statusCode !== 302 && response.statusCode !== 301) {
  27. console.error('Failed to HEAD github asset contents for redirect: ' + url);
  28. throw new Error('Unexpected status HEAD\'ing github asset for redirect: ' + response.statusCode);
  29. }
  30. if (!response.headers.location) {
  31. console.error(response.headers, `${response.body}`.slice(0, 300));
  32. throw new Error(`cannot find asset[${assetId}], asset download did not redirect`);
  33. }
  34. const fileResponse = await got(response.headers.location, {
  35. throwHttpErrors: false
  36. });
  37. if (fileResponse.statusCode !== 200) {
  38. console.error(fileResponse.headers, `${fileResponse.body}`.slice(0, 300));
  39. throw new Error(`cannot download asset[${assetId}] from ${response.headers.location}, got status: ${fileResponse.statusCode}`);
  40. }
  41. return fileResponse.body;
  42. }