Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(HTTP Request Node): Determine binary file name from content-disposition headers #7032

Merged
merged 4 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@
"@types/bcryptjs": "^2.4.2",
"@types/compression": "1.0.1",
"@types/connect-history-api-fallback": "^1.3.1",
"@types/content-disposition": "^0.5.5",
"@types/content-type": "^1.1.5",
"@types/convict": "^6.1.1",
"@types/cookie-parser": "^1.4.2",
"@types/express": "^4.17.6",
Expand Down Expand Up @@ -121,8 +119,6 @@
"class-validator": "^0.14.0",
"compression": "^1.7.4",
"connect-history-api-fallback": "^1.6.0",
"content-disposition": "^0.5.4",
"content-type": "^1.0.4",
"convict": "^6.2.4",
"cookie-parser": "^1.4.6",
"crypto-js": "~4.1.1",
Expand Down
24 changes: 2 additions & 22 deletions packages/cli/src/middlewares/bodyParser.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { parse as parseContentDisposition } from 'content-disposition';
import { parse as parseContentType } from 'content-type';
import getRawBody from 'raw-body';
import type { Request, RequestHandler } from 'express';
import { parse as parseQueryString } from 'querystring';
import { Parser as XmlParser } from 'xml2js';
import { parseIncomingMessage } from 'n8n-core';
import { jsonParse } from 'n8n-workflow';
import config from '@/config';
import { UnprocessableRequestError } from '@/ResponseHelper';
Expand All @@ -17,26 +16,7 @@ const xmlParser = new XmlParser({

const payloadSizeMax = config.getEnv('endpoints.payloadSizeMax');
export const rawBodyReader: RequestHandler = async (req, res, next) => {
if ('content-type' in req.headers) {
const { type: contentType, parameters } = (() => {
try {
return parseContentType(req);
} catch {
return { type: undefined, parameters: undefined };
}
})();
req.contentType = contentType;
req.encoding = (parameters?.charset ?? 'utf-8').toLowerCase() as BufferEncoding;

const contentDispositionHeader = req.headers['content-disposition'];
if (contentDispositionHeader?.length) {
const {
type,
parameters: { filename },
} = parseContentDisposition(contentDispositionHeader);
req.contentDisposition = { type, filename };
}
}
parseIncomingMessage(req);

req.readRawBody = async () => {
if (!req.rawBody) {
Expand Down
4 changes: 4 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
],
"devDependencies": {
"@types/concat-stream": "^2.0.0",
"@types/content-disposition": "^0.5.5",
"@types/content-type": "^1.1.5",
"@types/cron": "~1.7.1",
"@types/crypto-js": "^4.0.1",
"@types/express": "^4.17.6",
Expand All @@ -47,6 +49,8 @@
"axios": "^0.21.1",
"@n8n/client-oauth2": "workspace:*",
"concat-stream": "^2.0.0",
"content-disposition": "^0.5.4",
"content-type": "^1.0.4",
"cron": "~1.7.2",
"crypto-js": "~4.1.1",
"fast-glob": "^3.2.5",
Expand Down
86 changes: 55 additions & 31 deletions packages/core/src/NodeExecuteFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,11 @@ import {
validateFieldType,
NodeSSLError,
} from 'n8n-workflow';

import { parse as parseContentDisposition } from 'content-disposition';
import { parse as parseContentType } from 'content-type';
import pick from 'lodash/pick';
import { Agent } from 'https';
import { IncomingMessage } from 'http';
import { IncomingMessage, type IncomingHttpHeaders } from 'http';
import { stringify } from 'qs';
import type { Token } from 'oauth-1.0a';
import clientOAuth1 from 'oauth-1.0a';
Expand All @@ -100,7 +101,6 @@ import type { OptionsWithUri, OptionsWithUrl } from 'request';
import type { RequestPromiseOptions } from 'request-promise-native';
import FileType from 'file-type';
import { lookup, extension } from 'mime-types';
import type { IncomingHttpHeaders } from 'http';
import type {
AxiosError,
AxiosPromise,
Expand Down Expand Up @@ -600,6 +600,29 @@ type ConfigObject = {
simple?: boolean;
};

export function parseIncomingMessage(message: IncomingMessage) {
if ('content-type' in message.headers) {
const { type: contentType, parameters } = (() => {
try {
return parseContentType(message);
} catch {
return { type: undefined, parameters: undefined };
}
})();
message.contentType = contentType;
message.encoding = (parameters?.charset ?? 'utf-8').toLowerCase() as BufferEncoding;
}

const contentDispositionHeader = message.headers['content-disposition'];
if (contentDispositionHeader?.length) {
const {
type,
parameters: { filename },
} = parseContentDisposition(contentDispositionHeader);
message.contentDisposition = { type, filename };
}
}

export async function proxyRequestToAxios(
workflow: Workflow | undefined,
additionalData: IWorkflowExecuteAdditionalData | undefined,
Expand Down Expand Up @@ -654,35 +677,22 @@ export async function proxyRequestToAxios(

try {
const response = await requestFn();
if (configObject.resolveWithFullResponse === true) {
let body = response.data;
if (response.data === '') {
if (axiosConfig.responseType === 'arraybuffer') {
body = Buffer.alloc(0);
} else {
body = undefined;
}
}
await additionalData?.hooks?.executeHookFunctions('nodeFetchedData', [workflow?.id, node]);
return {
body,
headers: response.headers,
statusCode: response.status,
statusMessage: response.statusText,
request: response.request,
};
} else {
let body = response.data;
if (response.data === '') {
if (axiosConfig.responseType === 'arraybuffer') {
body = Buffer.alloc(0);
} else {
body = undefined;
}
}
await additionalData?.hooks?.executeHookFunctions('nodeFetchedData', [workflow?.id, node]);
return body;
let body = response.data;
if (body instanceof IncomingMessage && axiosConfig.responseType === 'stream') {
parseIncomingMessage(body);
} else if (body === '') {
body = axiosConfig.responseType === 'arraybuffer' ? Buffer.alloc(0) : undefined;
}
await additionalData?.hooks?.executeHookFunctions('nodeFetchedData', [workflow?.id, node]);
return configObject.resolveWithFullResponse
? {
body,
headers: response.headers,
statusCode: response.status,
statusMessage: response.statusText,
request: response.request,
}
: body;
} catch (error) {
const { config, response } = error;

Expand Down Expand Up @@ -998,6 +1008,20 @@ async function prepareBinaryData(
mimeType?: string,
): Promise<IBinaryData> {
let fileExtension: string | undefined;
if (binaryData instanceof IncomingMessage) {
if (!filePath) {
try {
const { responseUrl } = binaryData;
filePath =
binaryData.contentDisposition?.filename ??
((responseUrl && new URL(responseUrl).pathname) ?? binaryData.req?.path)?.slice(1);
} catch {}
}
if (!mimeType) {
mimeType = binaryData.contentType;
}
}

if (!mimeType) {
// If no mime type is given figure it out

Expand Down
23 changes: 9 additions & 14 deletions packages/nodes-base/nodes/HttpRequest/V1/HttpRequestV1.node.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Readable } from 'stream';

import type {
IExecuteFunctions,
IDataObject,
Expand Down Expand Up @@ -632,7 +634,7 @@ export class HttpRequestV1 implements INodeType {
oAuth2Api = await this.getCredentials('oAuth2Api');
} catch {}

let requestOptions: OptionsWithUri;
let requestOptions: OptionsWithUri & { useStream?: boolean };
let setUiParameter: IDataObject;

const uiParameters: IDataObject = {
Expand Down Expand Up @@ -873,6 +875,7 @@ export class HttpRequestV1 implements INodeType {

if (responseFormat === 'file') {
requestOptions.encoding = null;
requestOptions.useStream = true;

if (options.bodyContentType !== 'raw') {
requestOptions.body = JSON.stringify(requestOptions.body);
Expand All @@ -885,6 +888,7 @@ export class HttpRequestV1 implements INodeType {
}
} else if (options.bodyContentType === 'raw') {
requestOptions.json = false;
requestOptions.useStream = true;
} else {
requestOptions.json = true;
}
Expand Down Expand Up @@ -991,7 +995,6 @@ export class HttpRequestV1 implements INodeType {
response = response.value;

const options = this.getNodeParameter('options', itemIndex, {});
const url = this.getNodeParameter('url', itemIndex) as string;

const fullResponse = !!options.fullResponse;

Expand All @@ -1014,8 +1017,7 @@ export class HttpRequestV1 implements INodeType {
Object.assign(newItem.binary, items[itemIndex].binary);
}

const fileName = url.split('/').pop();

let binaryData: Buffer | Readable;
if (fullResponse) {
const returnItem: IDataObject = {};
for (const property of fullResponseProperties) {
Expand All @@ -1026,20 +1028,13 @@ export class HttpRequestV1 implements INodeType {
}

newItem.json = returnItem;

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(
response!.body as Buffer,
fileName,
);
binaryData = response!.body;
} else {
newItem.json = items[itemIndex].json;

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(
response! as Buffer,
fileName,
);
binaryData = response;
}

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(binaryData);
netroy marked this conversation as resolved.
Show resolved Hide resolved
returnItems.push(newItem);
} else if (responseFormat === 'string') {
const dataPropertyName = this.getNodeParameter('dataPropertyName', 0);
Expand Down
23 changes: 9 additions & 14 deletions packages/nodes-base/nodes/HttpRequest/V2/HttpRequestV2.node.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Readable } from 'stream';

import type {
IDataObject,
IExecuteFunctions,
Expand Down Expand Up @@ -672,7 +674,7 @@ export class HttpRequestV2 implements INodeType {
} catch {}
}

let requestOptions: OptionsWithUri;
let requestOptions: OptionsWithUri & { useStream?: boolean };
let setUiParameter: IDataObject;

const uiParameters: IDataObject = {
Expand Down Expand Up @@ -913,6 +915,7 @@ export class HttpRequestV2 implements INodeType {

if (responseFormat === 'file') {
requestOptions.encoding = null;
requestOptions.useStream = true;

if (options.bodyContentType !== 'raw') {
requestOptions.body = JSON.stringify(requestOptions.body);
Expand All @@ -925,6 +928,7 @@ export class HttpRequestV2 implements INodeType {
}
} else if (options.bodyContentType === 'raw') {
requestOptions.json = false;
requestOptions.useStream = true;
} else {
requestOptions.json = true;
}
Expand Down Expand Up @@ -1044,7 +1048,6 @@ export class HttpRequestV2 implements INodeType {
response = response.value;

const options = this.getNodeParameter('options', itemIndex, {});
const url = this.getNodeParameter('url', itemIndex) as string;

const fullResponse = !!options.fullResponse;

Expand All @@ -1067,8 +1070,7 @@ export class HttpRequestV2 implements INodeType {
Object.assign(newItem.binary, items[itemIndex].binary);
}

const fileName = url.split('/').pop();

let binaryData: Buffer | Readable;
if (fullResponse) {
const returnItem: IDataObject = {};
for (const property of fullResponseProperties) {
Expand All @@ -1079,20 +1081,13 @@ export class HttpRequestV2 implements INodeType {
}

newItem.json = returnItem;

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(
response!.body as Buffer,
fileName,
);
binaryData = response!.body;
} else {
newItem.json = items[itemIndex].json;

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(
response! as Buffer,
fileName,
);
binaryData = response;
}

newItem.binary![dataPropertyName] = await this.helpers.prepareBinaryData(binaryData);
netroy marked this conversation as resolved.
Show resolved Hide resolved
returnItems.push(newItem);
} else if (responseFormat === 'string') {
const dataPropertyName = this.getNodeParameter('dataPropertyName', 0);
Expand Down
18 changes: 4 additions & 14 deletions packages/nodes-base/nodes/HttpRequest/V3/HttpRequestV3.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1452,8 +1452,6 @@ export class HttpRequestV3 implements INodeType {

response = response.value;

const url = this.getNodeParameter('url', itemIndex) as string;

let responseFormat = this.getNodeParameter(
'options.response.response.responseFormat',
0,
Expand Down Expand Up @@ -1525,8 +1523,7 @@ export class HttpRequestV3 implements INodeType {
Object.assign(newItem.binary as IBinaryKeyData, items[itemIndex].binary);
}

const fileName = url.split('/').pop();

let binaryData: Buffer | Readable;
if (fullResponse) {
const returnItem: IDataObject = {};
for (const property of fullResponseProperties) {
Expand All @@ -1537,19 +1534,12 @@ export class HttpRequestV3 implements INodeType {
}

newItem.json = returnItem;

newItem.binary![outputPropertyName] = await this.helpers.prepareBinaryData(
response!.body as Buffer | Readable,
fileName,
);
binaryData = response!.body;
} else {
newItem.json = items[itemIndex].json;

newItem.binary![outputPropertyName] = await this.helpers.prepareBinaryData(
response! as Buffer | Readable,
fileName,
);
binaryData = response;
}
newItem.binary![outputPropertyName] = await this.helpers.prepareBinaryData(binaryData);

returnItems.push(newItem);
} else if (responseFormat === 'text') {
Expand Down
Loading
Loading