Skip to content

Commit

Permalink
Replace axios with node-fetch
Browse files Browse the repository at this point in the history
node-fetch@2 is used as it supports older node versions (e.g. 12)

Fixes error "Failed to open scan results: getaddrinfo ENOTFOUND [::1]" on Linux when the option "Open manual scan results in a separate file/tab" is enabled
  • Loading branch information
maksis committed May 26, 2023
1 parent 295df82 commit 7690ddb
Show file tree
Hide file tree
Showing 7 changed files with 400 additions and 387 deletions.
719 changes: 362 additions & 357 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,17 @@
"devDependencies": {
"@types/invariant": "^2.2.35",
"@types/jest": "^29.0.2",
"@types/node-fetch": "^2.6.4",
"airdcpp-extension": "^1.5.1",
"airdcpp-extension-settings": "^1.2.1",
"async-file": "^2.0.2",
"axios": "^1.3.4",
"cross-env": "^7.0.3",
"eol": "^0.9.0",
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"jest": "^29.0.3",
"jest-cli": "^29.0.3",
"node-fetch": "^2.6.11",
"nodemon": "^2.0.19",
"prettier": "^2.7.1",
"rimraf": "^4.4.1",
Expand Down
9 changes: 4 additions & 5 deletions src/helpers/LogViewer.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import { Context } from 'types';


const postData = (path: string, data: string, { application, axios }: Context) => {
const postData = (path: string, body: string, { application, fetch }: Context) => {
const baseUrl = (application.server.secure ? 'https://' : 'http://') + application.server.address;
return axios({
url: `${baseUrl}/${path}`,
return fetch(`${baseUrl}/${path}`, {
method: 'POST',
headers: {
'Authorization': `${application.session.tokenType} ${application.session.token}`,
},
data,
body,
})
};

export const openLog = async (text: string, context: Context) => {
// Upload text
const { api, generateResultLogName } = context;
const fileUploadRes = await postData('temp', text, context);
const tempFileId = fileUploadRes.headers['location'];
const tempFileId = fileUploadRes.headers.get('location')!;

// Create a temp share item so that we get a TTH to view
const tempShareRes = await api.postTempShare(tempFileId, generateResultLogName(), context.application.cid);
Expand Down
5 changes: 2 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

const CONFIG_VERSION = 1;


import axios from 'axios';
import fetch from 'node-fetch';

import { addContextMenuItems, APISocket } from 'airdcpp-apisocket';
import { ExtensionEntryData } from 'airdcpp-extension';
Expand Down Expand Up @@ -49,7 +48,7 @@ export default function (socket: APISocket, extension: ExtensionEntryData) {
const api = API(socket);
const context: Context = {
api,
axios,
fetch,
logger: socket.logger,
extensionName: extension.name,
generateResultLogName: () => `Share scan ${new Date().toLocaleString()}`,
Expand Down
5 changes: 3 additions & 2 deletions src/types/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { ServerInfo } from 'airdcpp-extension';
import { Validator } from './internal';
import { APIType } from 'api';
import { Logger } from 'airdcpp-apisocket';
import { AxiosInstance } from 'axios';

import fetch from 'node-fetch';


// CONTEXT
Expand All @@ -28,6 +29,6 @@ export interface Context {
application: ApplicationInfo;
api: APIType;
logger: Logger;
axios: AxiosInstance;
fetch: typeof fetch;
generateResultLogName: () => string;
}
42 changes: 25 additions & 17 deletions tests/ScanRunners.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,8 @@ describe('Scan runner', () => {
},
dupe: {
id: 'share full',
paths: [
scanPath,
]
}
paths: [scanPath],
},
};

const api = getMockApi({
Expand All @@ -240,7 +238,10 @@ describe('Scan runner', () => {
});

const runner = getScanRunners(api);
const scanner = await runner.scanOwnFilelistDirectories([1], 'CWXQGJYK3QERDRGB25M4ABJMGF2F4ODDDOON25A');
const scanner = await runner.scanOwnFilelistDirectories(
[1],
'CWXQGJYK3QERDRGB25M4ABJMGF2F4ODDDOON25A'
);

expect(scanner.errors.count() > 0).toBe(true);
expect(scanner.stats.scannedDirectories).toBe(2);
Expand Down Expand Up @@ -287,12 +288,15 @@ describe('Scan runner', () => {
});

const runner = getScanRunners(api as APIType, {
axios: (data) => {
uploadContentFn(data);
fetch: (url, options) => {
uploadContentFn(url, options);

const headers = new Headers({
location: MOCK_UPLOAD_LOCATION_ID,
});

return Promise.resolve({
headers: {
location: MOCK_UPLOAD_LOCATION_ID,
},
headers,
});
},
configOverrides: {
Expand All @@ -309,22 +313,26 @@ describe('Scan runner', () => {
expect(deleteTempShareFn).toHaveBeenCalledWith(MOCK_VIEW_FILE_ID);
expect(createViewFileFn).toHaveBeenCalledWith(MOCK_TTH);

const axiosCall = uploadContentFn.mock.calls[0][0];
const sanitizedCall = {
...axiosCall,
data: sanitizeResultPaths(axiosCall.data),
const fetchCall = uploadContentFn.mock.calls[0];

const callUrl = fetchCall[0];
const callOptions = fetchCall[1];

const sanitizedCallOptions = {
...callOptions,
body: sanitizeResultPaths(callOptions.body), // Remove absolute paths
};

expect(sanitizedCall).toMatchInlineSnapshot(`
expect(callUrl).toMatchInlineSnapshot(`"http://mock_url/temp"`);
expect(sanitizedCallOptions).toMatchInlineSnapshot(`
{
"data": "/TESTS_ROOT/data/Test.Release-TEST: Extra files in release directory (1 file(s): forbidden_extra.zip)
"body": "/TESTS_ROOT/data/Test.Release-TEST: Extra files in release directory (1 file(s): forbidden_extra.zip)
/TESTS_ROOT/data/Test.Release-TEST/Sample/: NFO/SFV found but there are no other files in the folder
/TESTS_ROOT/data/Test.Release-TEST/Sample/: No valid lines were parsed from the SFV file (1 file(s): invalid.sfv)",
"headers": {
"Authorization": "mock-token-type mock-token",
},
"method": "POST",
"url": "http://mock_url/temp",
}
`);
});
Expand Down
4 changes: 2 additions & 2 deletions tests/mock-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const getMockApi = (customHandlers: Partial<APIType> = {}): APIType => {

export interface MockContextOptions {
configOverrides?: Partial<Config>;
axios?: (data: object) => Promise<any>;
fetch?: (url: string, options: object) => Promise<any>;
}

export const MOCK_RESULT_LOG_NAME = 'mock_log_name';
Expand All @@ -38,7 +38,7 @@ export const MockApplicationInfo: ApplicationInfo = {
export const getMockContext = (api: APIType, options: Partial<MockContextOptions> = {}) => {
const context: Context = {
api,
axios: options.axios || (() => {}) as any,
fetch: options.fetch || (() => {}) as any,
logger,
extensionName: 'test-extension',
configGetter: () => ({
Expand Down

0 comments on commit 7690ddb

Please sign in to comment.