n8n/packages/nodes-base/nodes/Slack/V2/GenericFunctions.ts
agobrech 4df69428f1
feat(Slack Node): Revamp the node with more functionalities in a new version (#4587)
* 🔥 Remove useless tooltips

* Slack change additional fields to Options in node

* 🥅 Add error handeling for out of Scope request

* ♻️ Refactor channel visibility

* ♻️ refactor user ressource

* Update user profile

* 🔥 remove JSON parameter

* 🔥 remove attchmant json and block json

* 🎨 refactors message post

* 🎨 refactor ts property into timestamps

* 🎨 change action name for messages

*  add new operation to message ressouce

*  add search backend logic + channel RLC

* 🎨 improve timestamp description and plaecholder

* 🎨 change timestamp disaplay name

*  add RLC for channels

*  add versioning

* 🐛 Fix imports for versioning

*  Add RLC for users when sending messages

*  RLC for user presence

*  Add json builder for slack blocks

* 🐛 Fix option in search query

* Add loadoption for search in channels

* Fix indentation issue

*  Add more scopes to Oauth2

* 🐛 Fix lint issue

* 🐛 oauth fix

*  Merge user and user profile

*  Improve reactions and star resource

* ️Merges ephemeral operation into one

* ️Merge image and emoji in profile picture

* 🐛Fix bug for replying to messages

* ️Add username type to User Rlc

* 🐛 Fix typo

* 🎨 Improves tooltip and naming for ephemeral messages

* 🎨 Improve display name and description

* ️Add the ability to delete within username channel

* 🎨 Add informations on how to use the emojis and add doc

* 🎨 Fix typos and improve display names

*  Improve FE validation for timestamp

* 🎨 Change block description

* 🚨 Fix linting

* 🚨 More lint fixes

* 🐛 Fix timestamps bug

* 🐛 Fix timestamp not showing up

* 🐛 More small fixes

* 🐛 Fix logic error

* Add searchable to slack rlc channels and users

* Fix lint rules

* ️Message Search -> fix limit request using qs count

* ️Message Search -> sort by relevance use qs score

* Fix messages by username rlc

* 🐛 fix messages search all operation

* Add error when using username with ephemeral message

* 🎨 fix linting errors

* 🎨 send message ephemeral error message improvement

---------

Co-authored-by: Marcus <marcus@n8n.io>
2023-02-03 17:04:37 +01:00

138 lines
3.9 KiB
TypeScript

import type { OptionsWithUri } from 'request';
import type { IExecuteFunctions, IExecuteSingleFunctions, ILoadOptionsFunctions } from 'n8n-core';
import type { IDataObject, IOAuth2Options } from 'n8n-workflow';
import { NodeOperationError } from 'n8n-workflow';
import _ from 'lodash';
export async function slackApiRequest(
this: IExecuteFunctions | IExecuteSingleFunctions | ILoadOptionsFunctions,
method: string,
resource: string,
body: object = {},
query: object = {},
headers: {} | undefined = undefined,
option: {} = {},
// tslint:disable-next-line:no-any
): Promise<any> {
const authenticationMethod = this.getNodeParameter('authentication', 0, 'accessToken') as string;
let options: OptionsWithUri = {
method,
headers: headers ?? {
'Content-Type': 'application/json; charset=utf-8',
},
body,
qs: query,
uri: `https://slack.com/api${resource}`,
json: true,
};
options = Object.assign({}, options, option);
if (Object.keys(body).length === 0) {
delete options.body;
}
if (Object.keys(query).length === 0) {
delete options.qs;
}
const oAuth2Options: IOAuth2Options = {
tokenType: 'Bearer',
property: 'authed_user.access_token',
};
const credentialType = authenticationMethod === 'accessToken' ? 'slackApi' : 'slackOAuth2Api';
const response = await this.helpers.requestWithAuthentication.call(
this,
credentialType,
options,
{
oauth2: oAuth2Options,
},
);
if (response.ok === false) {
if (response.error === 'paid_teams_only') {
throw new NodeOperationError(
this.getNode(),
`Your current Slack plan does not include the resource '${
this.getNodeParameter('resource', 0) as string
}'`,
{
description:
'Hint: Upgrate to the Slack plan that includes the funcionality you want to use.',
},
);
} else if (response.error === 'missing_scope') {
throw new NodeOperationError(
this.getNode(),
'Your Slack credential is missing required Oauth Scopes',
{
description: `Add the following scope(s) to your Slack App: ${response.needed}`,
},
);
}
throw new NodeOperationError(
this.getNode(),
'Slack error response: ' + JSON.stringify(response.error),
);
}
if (response.ts !== undefined) {
Object.assign(response, { message_timestamp: response.ts });
delete response.ts;
}
return response;
}
export async function slackApiRequestAllItems(
this: IExecuteFunctions | ILoadOptionsFunctions,
propertyName: string,
method: string,
endpoint: string,
// tslint:disable-next-line:no-any
body: any = {},
query: IDataObject = {},
// tslint:disable-next-line:no-any
): Promise<any> {
const returnData: IDataObject[] = [];
let responseData;
query.page = 1;
//if the endpoint uses legacy pagination use count
//https://api.slack.com/docs/pagination#classic
if (endpoint.includes('files.list')) {
query.count = 100;
} else {
query.limit = 100;
}
do {
responseData = await slackApiRequest.call(this, method, endpoint, body, query);
query.cursor = _.get(responseData, 'response_metadata.next_cursor');
query.page++;
returnData.push.apply(
returnData,
responseData[propertyName].matches ?? responseData[propertyName],
);
} while (
(responseData.response_metadata?.next_cursor !== undefined &&
responseData.response_metadata.next_cursor !== '' &&
responseData.response_metadata.next_cursor !== null) ||
(responseData.paging?.pages !== undefined &&
responseData.paging.page !== undefined &&
responseData.paging.page < responseData.paging.pages) ||
(responseData[propertyName].paging?.pages !== undefined &&
responseData[propertyName].paging.page !== undefined &&
responseData[propertyName].paging.page < responseData[propertyName].paging.pages)
);
return returnData;
}
// tslint:disable-next-line:no-any
export function validateJSON(json: string | undefined): any {
let result;
try {
result = JSON.parse(json!);
} catch (exception) {
result = undefined;
}
return result;
}